patch
stringlengths 17
31.2k
| y
int64 1
1
| oldf
stringlengths 0
2.21M
| idx
int64 1
1
| id
int64 4.29k
68.4k
| msg
stringlengths 8
843
| proj
stringclasses 212
values | lang
stringclasses 9
values |
---|---|---|---|---|---|---|---|
@@ -36,8 +36,7 @@ public class GleanMetricsService {
} else {
GleanMetricsService.stop();
}
- Configuration config = new Configuration(Configuration.DEFAULT_TELEMETRY_ENDPOINT,
- BuildConfig.BUILD_TYPE);
+ Configuration config = new Configuration();
Glean.INSTANCE.initialize(aContext, config);
}
| 1 | package org.mozilla.vrbrowser.telemetry;
import android.content.Context;
import android.util.Log;
import androidx.annotation.UiThread;
import org.mozilla.vrbrowser.browser.SettingsStore;
import org.mozilla.vrbrowser.utils.DeviceType;
import org.mozilla.vrbrowser.utils.SystemUtils;
import org.mozilla.vrbrowser.BuildConfig;
import org.mozilla.vrbrowser.GleanMetrics.Distribution;
import mozilla.components.service.glean.Glean;
import mozilla.components.service.glean.config.Configuration;
public class GleanMetricsService {
private final static String APP_NAME = "FirefoxReality";
private static boolean initialized = false;
private final static String LOGTAG = SystemUtils.createLogtag(GleanMetricsService.class);
private static Context context = null;
// We should call this at the application initial stage.
public static void init(Context aContext) {
if (initialized)
return;
context = aContext;
initialized = true;
final boolean telemetryEnabled = SettingsStore.getInstance(aContext).isTelemetryEnabled();
if (telemetryEnabled) {
GleanMetricsService.start();
} else {
GleanMetricsService.stop();
}
Configuration config = new Configuration(Configuration.DEFAULT_TELEMETRY_ENDPOINT,
BuildConfig.BUILD_TYPE);
Glean.INSTANCE.initialize(aContext, config);
}
// It would be called when users turn on/off the setting of telemetry.
// e.g., SettingsStore.getInstance(context).setTelemetryEnabled();
public static void start() {
Glean.INSTANCE.setUploadEnabled(true);
setStartupMetrics();
}
// It would be called when users turn on/off the setting of telemetry.
// e.g., SettingsStore.getInstance(context).setTelemetryEnabled();
public static void stop() {
Glean.INSTANCE.setUploadEnabled(false);
}
private static void setStartupMetrics() {
Distribution.INSTANCE.getChannelName().set(DeviceType.isOculusBuild() ? "oculusvr" : BuildConfig.FLAVOR_platform);
}
}
| 1 | 8,359 | This was just fixed in mozilla-mobile/android-components#4892. @pocmo is cutting a new Android Components 19 dot release today, so you'll be able to jump to the new version and restore the build type. | MozillaReality-FirefoxReality | java |
@@ -131,6 +131,7 @@ func (r *genericInjectReconciler) Reconcile(req ctrl.Request) (ctrl.Result, erro
if err := r.Client.Get(ctx, req.NamespacedName, target.AsObject()); err != nil {
if dropNotFound(err) == nil {
// don't requeue on deletions, which yield a non-found object
+ log.V(logf.TraceLevel).Info("not found", "err", err)
return ctrl.Result{}, nil
}
log.Error(err, "unable to fetch target object to inject into") | 1 | /*
Copyright 2019 The Jetstack cert-manager contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cainjector
import (
"context"
"fmt"
"strings"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
certmanager "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
logf "github.com/jetstack/cert-manager/pkg/logs"
)
// dropNotFound ignores the given error if it's a not-found error,
// but otherwise just returns the argument.
func dropNotFound(err error) error {
if apierrors.IsNotFound(err) {
return nil
}
return err
}
// OwningCertForSecret gets the name of the owning certificate for a
// given secret, returning nil if no such object exists.
// Right now, this actually uses a label instead of owner refs,
// since certmanager doesn't set owner refs on secrets.
func OwningCertForSecret(secret *corev1.Secret) *types.NamespacedName {
lblVal, hasLbl := secret.Annotations[certmanager.CertificateNameKey]
if !hasLbl {
return nil
}
return &types.NamespacedName{
Name: lblVal,
Namespace: secret.Namespace,
}
}
// InjectTarget is a Kubernetes API object that has one or more references to Kubernetes
// Services with corresponding fields for CA bundles.
type InjectTarget interface {
// AsObject returns this injectable as an object.
// It should be a pointer suitable for mutation.
AsObject() runtime.Object
// SetCA sets the CA of this target to the given certificate data (in the standard
// PEM format used across Kubernetes). In cases where multiple CA fields exist per
// target (like admission webhook configs), all CAs are set to the given value.
SetCA(data []byte)
}
// Injectable is a point in a Kubernetes API object that represents a Kubernetes Service
// reference with a corresponding spot for a CA bundle.
type Injectable interface {
}
// CertInjector knows how to create an instance of an InjectTarget for some particular type
// of inject target. For instance, an implementation might create a InjectTarget
// containing an empty MutatingWebhookConfiguration. The underlying API object can
// be populated (via AsObject) using client.Client#Get, and then CAs can be injected with
// Injectables (representing the various individual webhooks in the config) retrieved with
// Services.
type CertInjector interface {
// NewTarget creates a new InjectTarget containing an empty underlying object.
NewTarget() InjectTarget
// IsAlpha tells the client to disregard "no matching kind" type of errors
IsAlpha() bool
}
// genericInjectReconciler is a reconciler that knows how to check if a given object is
// marked as requiring a CA, chase down the corresponding Service, Certificate, Secret, and
// inject that into the object.
type genericInjectReconciler struct {
// injector is responsible for the logic of actually setting a CA -- it's the component
// that contains type-specific logic.
injector CertInjector
// sources is a list of available 'data sources' that can be used to extract
// caBundles from various source.
// This is defined as a variable to allow an instance of the secret-based
// cainjector to run even when Certificate resources cannot we watched due to
// the conversion webhook not being available.
sources []caDataSource
log logr.Logger
client.Client
resourceName string // just used for logging
}
// splitNamespacedName turns the string form of a namespaced name
// (<namespace>/<name>) back into a types.NamespacedName.
func splitNamespacedName(nameStr string) types.NamespacedName {
splitPoint := strings.IndexRune(nameStr, types.Separator)
if splitPoint == -1 {
return types.NamespacedName{Name: nameStr}
}
return types.NamespacedName{Namespace: nameStr[:splitPoint], Name: nameStr[splitPoint+1:]}
}
// Reconcile attempts to ensure that a particular object has all the CAs injected that
// it has requested.
func (r *genericInjectReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
ctx := context.Background()
log := r.log.WithValues(r.resourceName, req.NamespacedName)
// fetch the target object
target := r.injector.NewTarget()
if err := r.Client.Get(ctx, req.NamespacedName, target.AsObject()); err != nil {
if dropNotFound(err) == nil {
// don't requeue on deletions, which yield a non-found object
return ctrl.Result{}, nil
}
log.Error(err, "unable to fetch target object to inject into")
return ctrl.Result{}, err
}
// ensure that it wants injection
metaObj, err := meta.Accessor(target.AsObject())
if err != nil {
log.Error(err, "unable to get metadata for object")
return ctrl.Result{}, err
}
log = logf.WithResource(r.log, metaObj)
dataSource, err := r.caDataSourceFor(log, metaObj)
if err != nil {
log.V(logf.DebugLevel).Info("failed to determine ca data source for injectable")
return ctrl.Result{}, nil
}
caData, err := dataSource.ReadCA(ctx, log, metaObj)
if err != nil {
log.Error(err, "failed to read CA from data source")
return ctrl.Result{}, err
}
if caData == nil {
log.V(logf.InfoLevel).Info("could not find any ca data in data source for target")
return ctrl.Result{}, nil
}
// actually do the injection
target.SetCA(caData)
// actually update with injected CA data
if err := r.Client.Update(ctx, target.AsObject()); err != nil {
log.Error(err, "unable to update target object with new CA data")
return ctrl.Result{}, err
}
log.V(logf.InfoLevel).Info("updated object")
return ctrl.Result{}, nil
}
func (r *genericInjectReconciler) caDataSourceFor(log logr.Logger, metaObj metav1.Object) (caDataSource, error) {
for _, s := range r.sources {
if s.Configured(log, metaObj) {
return s, nil
}
}
return nil, fmt.Errorf("could not determine ca data source for resource")
}
| 1 | 23,403 | Leaving this log line because it helped me to diagnose that the reconciler client was using a different cache than the event sources, so not always seeing the injectable that triggered the reconcile. | jetstack-cert-manager | go |
@@ -4867,7 +4867,10 @@ func (mset *stream) processCatchupMsg(msg []byte) (uint64, error) {
return 0, errors.New("bad catchup msg")
}
+ mset.mu.RLock()
st := mset.cfg.Storage
+ mset.mu.RUnlock()
+
if mset.js.limitsExceeded(st) || mset.jsa.limitsExceeded(st) {
return 0, NewJSInsufficientResourcesError()
} | 1 | // Copyright 2020-2021 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"math"
"math/rand"
"path"
"reflect"
"sort"
"strings"
"sync/atomic"
"time"
"github.com/klauspost/compress/s2"
"github.com/nats-io/nuid"
)
// jetStreamCluster holds information about the meta group and stream assignments.
type jetStreamCluster struct {
// The metacontroller raftNode.
meta RaftNode
// For stream and consumer assignments. All servers will have this be the same.
// ACCOUNT -> STREAM -> Stream Assignment -> Consumers
streams map[string]map[string]*streamAssignment
// Signals meta-leader should check the stream assignments.
streamsCheck bool
// Server.
s *Server
// Internal client.
c *client
// Processing assignment results.
streamResults *subscription
consumerResults *subscription
// System level request to have the leader stepdown.
stepdown *subscription
// System level requests to remove a peer.
peerRemove *subscription
}
// Used to guide placement of streams and meta controllers in clustered JetStream.
type Placement struct {
Cluster string `json:"cluster"`
Tags []string `json:"tags,omitempty"`
}
// Define types of the entry.
type entryOp uint8
const (
// Meta ops.
assignStreamOp entryOp = iota
assignConsumerOp
removeStreamOp
removeConsumerOp
// Stream ops.
streamMsgOp
purgeStreamOp
deleteMsgOp
// Consumer ops
updateDeliveredOp
updateAcksOp
// Compressed consumer assignments.
assignCompressedConsumerOp
// Filtered Consumer skip.
updateSkipOp
// Update Stream
updateStreamOp
)
// raftGroups are controlled by the metagroup controller.
// The raftGroups will house streams and consumers.
type raftGroup struct {
Name string `json:"name"`
Peers []string `json:"peers"`
Storage StorageType `json:"store"`
Preferred string `json:"preferred,omitempty"`
// Internal
node RaftNode
}
// streamAssignment is what the meta controller uses to assign streams to peers.
type streamAssignment struct {
Client *ClientInfo `json:"client,omitempty"`
Created time.Time `json:"created"`
Config *StreamConfig `json:"stream"`
Group *raftGroup `json:"group"`
Sync string `json:"sync"`
Subject string `json:"subject"`
Reply string `json:"reply"`
Restore *StreamState `json:"restore_state,omitempty"`
// Internal
consumers map[string]*consumerAssignment
responded bool
err error
}
// consumerAssignment is what the meta controller uses to assign consumers to streams.
type consumerAssignment struct {
Client *ClientInfo `json:"client,omitempty"`
Created time.Time `json:"created"`
Name string `json:"name"`
Stream string `json:"stream"`
Config *ConsumerConfig `json:"consumer"`
Group *raftGroup `json:"group"`
Subject string `json:"subject"`
Reply string `json:"reply"`
State *ConsumerState `json:"state,omitempty"`
// Internal
responded bool
deleted bool
pending bool
err error
}
// streamPurge is what the stream leader will replicate when purging a stream.
type streamPurge struct {
Client *ClientInfo `json:"client,omitempty"`
Stream string `json:"stream"`
LastSeq uint64 `json:"last_seq"`
Subject string `json:"subject"`
Reply string `json:"reply"`
Request *JSApiStreamPurgeRequest `json:"request,omitempty"`
}
// streamMsgDelete is what the stream leader will replicate when deleting a message.
type streamMsgDelete struct {
Client *ClientInfo `json:"client,omitempty"`
Stream string `json:"stream"`
Seq uint64 `json:"seq"`
NoErase bool `json:"no_erase,omitempty"`
Subject string `json:"subject"`
Reply string `json:"reply"`
}
const (
defaultStoreDirName = "_js_"
defaultMetaGroupName = "_meta_"
defaultMetaFSBlkSize = 1024 * 1024
)
// Returns information useful in mixed mode.
func (s *Server) trackedJetStreamServers() (js, total int) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.running || !s.eventsEnabled() {
return -1, -1
}
s.nodeToInfo.Range(func(k, v interface{}) bool {
si := v.(nodeInfo)
if si.js {
js++
}
total++
return true
})
return js, total
}
func (s *Server) getJetStreamCluster() (*jetStream, *jetStreamCluster) {
s.mu.Lock()
shutdown := s.shutdown
js := s.js
s.mu.Unlock()
if shutdown || js == nil {
return nil, nil
}
js.mu.RLock()
cc := js.cluster
js.mu.RUnlock()
if cc == nil {
return nil, nil
}
return js, cc
}
func (s *Server) JetStreamIsClustered() bool {
js := s.getJetStream()
if js == nil {
return false
}
js.mu.RLock()
isClustered := js.cluster != nil
js.mu.RUnlock()
return isClustered
}
func (s *Server) JetStreamIsLeader() bool {
js := s.getJetStream()
if js == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return js.cluster.isLeader()
}
func (s *Server) JetStreamIsCurrent() bool {
js := s.getJetStream()
if js == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return js.cluster.isCurrent()
}
func (s *Server) JetStreamSnapshotMeta() error {
js := s.getJetStream()
if js == nil {
return NewJSNotEnabledError()
}
js.mu.RLock()
cc := js.cluster
isLeader := cc.isLeader()
meta := cc.meta
js.mu.RUnlock()
if !isLeader {
return errNotLeader
}
return meta.InstallSnapshot(js.metaSnapshot())
}
func (s *Server) JetStreamStepdownStream(account, stream string) error {
js, cc := s.getJetStreamCluster()
if js == nil {
return NewJSNotEnabledError()
}
if cc == nil {
return NewJSClusterNotActiveError()
}
// Grab account
acc, err := s.LookupAccount(account)
if err != nil {
return err
}
// Grab stream
mset, err := acc.lookupStream(stream)
if err != nil {
return err
}
if node := mset.raftNode(); node != nil && node.Leader() {
node.StepDown()
}
return nil
}
func (s *Server) JetStreamSnapshotStream(account, stream string) error {
js, cc := s.getJetStreamCluster()
if js == nil {
return NewJSNotEnabledForAccountError()
}
if cc == nil {
return NewJSClusterNotActiveError()
}
// Grab account
acc, err := s.LookupAccount(account)
if err != nil {
return err
}
// Grab stream
mset, err := acc.lookupStream(stream)
if err != nil {
return err
}
mset.mu.RLock()
if !mset.node.Leader() {
mset.mu.RUnlock()
return NewJSNotEnabledForAccountError()
}
n := mset.node
mset.mu.RUnlock()
return n.InstallSnapshot(mset.stateSnapshot())
}
func (s *Server) JetStreamClusterPeers() []string {
js := s.getJetStream()
if js == nil {
return nil
}
js.mu.RLock()
defer js.mu.RUnlock()
cc := js.cluster
if !cc.isLeader() {
return nil
}
peers := cc.meta.Peers()
var nodes []string
for _, p := range peers {
si, ok := s.nodeToInfo.Load(p.ID)
if !ok || si.(nodeInfo).offline || !si.(nodeInfo).js {
continue
}
nodes = append(nodes, si.(nodeInfo).name)
}
return nodes
}
// Read lock should be held.
func (cc *jetStreamCluster) isLeader() bool {
if cc == nil {
// Non-clustered mode
return true
}
return cc.meta != nil && cc.meta.Leader()
}
// isCurrent will determine if this node is a leader or an up to date follower.
// Read lock should be held.
func (cc *jetStreamCluster) isCurrent() bool {
if cc == nil {
// Non-clustered mode
return true
}
if cc.meta == nil {
return false
}
return cc.meta.Current()
}
// isStreamCurrent will determine if this node is a participant for the stream and if its up to date.
// Read lock should be held.
func (cc *jetStreamCluster) isStreamCurrent(account, stream string) bool {
if cc == nil {
// Non-clustered mode
return true
}
as := cc.streams[account]
if as == nil {
return false
}
sa := as[stream]
if sa == nil {
return false
}
rg := sa.Group
if rg == nil || rg.node == nil {
return false
}
isCurrent := rg.node.Current()
if isCurrent {
// Check if we are processing a snapshot and are catching up.
acc, err := cc.s.LookupAccount(account)
if err != nil {
return false
}
mset, err := acc.lookupStream(stream)
if err != nil {
return false
}
if mset.isCatchingUp() {
return false
}
}
return isCurrent
}
func (a *Account) getJetStreamFromAccount() (*Server, *jetStream, *jsAccount) {
a.mu.RLock()
jsa := a.js
a.mu.RUnlock()
if jsa == nil {
return nil, nil, nil
}
jsa.mu.RLock()
js := jsa.js
jsa.mu.RUnlock()
if js == nil {
return nil, nil, nil
}
js.mu.RLock()
s := js.srv
js.mu.RUnlock()
return s, js, jsa
}
func (s *Server) JetStreamIsStreamLeader(account, stream string) bool {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return cc.isStreamLeader(account, stream)
}
func (a *Account) JetStreamIsStreamLeader(stream string) bool {
s, js, jsa := a.getJetStreamFromAccount()
if s == nil || js == nil || jsa == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return js.cluster.isStreamLeader(a.Name, stream)
}
func (s *Server) JetStreamIsStreamCurrent(account, stream string) bool {
js, cc := s.getJetStreamCluster()
if js == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return cc.isStreamCurrent(account, stream)
}
func (a *Account) JetStreamIsConsumerLeader(stream, consumer string) bool {
s, js, jsa := a.getJetStreamFromAccount()
if s == nil || js == nil || jsa == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return js.cluster.isConsumerLeader(a.Name, stream, consumer)
}
func (s *Server) JetStreamIsConsumerLeader(account, stream, consumer string) bool {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return cc.isConsumerLeader(account, stream, consumer)
}
func (s *Server) enableJetStreamClustering() error {
if !s.isRunning() {
return nil
}
js := s.getJetStream()
if js == nil {
return NewJSNotEnabledForAccountError()
}
// Already set.
if js.cluster != nil {
return nil
}
s.Noticef("Starting JetStream cluster")
// We need to determine if we have a stable cluster name and expected number of servers.
s.Debugf("JetStream cluster checking for stable cluster name and peers")
hasLeafNodeSystemShare := s.wantsToExtendOtherDomain()
if s.isClusterNameDynamic() && !hasLeafNodeSystemShare {
return errors.New("JetStream cluster requires cluster name")
}
if s.configuredRoutes() == 0 && !hasLeafNodeSystemShare {
return errors.New("JetStream cluster requires configured routes or solicited leafnode for the system account")
}
return js.setupMetaGroup()
}
func (js *jetStream) setupMetaGroup() error {
s := js.srv
s.Noticef("Creating JetStream metadata controller")
// Setup our WAL for the metagroup.
sysAcc := s.SystemAccount()
storeDir := path.Join(js.config.StoreDir, sysAcc.Name, defaultStoreDirName, defaultMetaGroupName)
fs, err := newFileStore(
FileStoreConfig{StoreDir: storeDir, BlockSize: defaultMetaFSBlkSize, AsyncFlush: false},
StreamConfig{Name: defaultMetaGroupName, Storage: FileStorage},
)
if err != nil {
s.Errorf("Error creating filestore: %v", err)
return err
}
cfg := &RaftConfig{Name: defaultMetaGroupName, Store: storeDir, Log: fs}
// If we are soliciting leafnode connections and we are sharing a system account
// we want to move to observer mode so that we extend the solicited cluster or supercluster
// but do not form our own.
cfg.Observer = s.wantsToExtendOtherDomain()
var bootstrap bool
if _, err := readPeerState(storeDir); err != nil {
s.Noticef("JetStream cluster bootstrapping")
bootstrap = true
peers := s.ActivePeers()
s.Debugf("JetStream cluster initial peers: %+v", peers)
if err := s.bootstrapRaftNode(cfg, peers, false); err != nil {
return err
}
} else {
s.Noticef("JetStream cluster recovering state")
}
// Start up our meta node.
n, err := s.startRaftNode(cfg)
if err != nil {
s.Warnf("Could not start metadata controller: %v", err)
return err
}
// If we are bootstrapped with no state, start campaign early.
if bootstrap {
n.Campaign()
}
c := s.createInternalJetStreamClient()
sacc := s.SystemAccount()
js.mu.Lock()
defer js.mu.Unlock()
js.cluster = &jetStreamCluster{
meta: n,
streams: make(map[string]map[string]*streamAssignment),
s: s,
c: c,
}
c.registerWithAccount(sacc)
js.srv.startGoRoutine(js.monitorCluster)
return nil
}
func (js *jetStream) getMetaGroup() RaftNode {
js.mu.RLock()
defer js.mu.RUnlock()
if js.cluster == nil {
return nil
}
return js.cluster.meta
}
func (js *jetStream) server() *Server {
js.mu.RLock()
s := js.srv
js.mu.RUnlock()
return s
}
// Will respond if we do not think we have a metacontroller leader.
func (js *jetStream) isLeaderless() bool {
js.mu.RLock()
defer js.mu.RUnlock()
cc := js.cluster
if cc == nil || cc.meta == nil {
return false
}
// If we don't have a leader.
// Make sure we have been running for enough time.
if cc.meta.GroupLeader() == _EMPTY_ && time.Since(cc.meta.Created()) > lostQuorumInterval {
return true
}
return false
}
// Will respond iff we are a member and we know we have no leader.
func (js *jetStream) isGroupLeaderless(rg *raftGroup) bool {
if rg == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
cc := js.cluster
// If we are not a member we can not say..
if !rg.isMember(cc.meta.ID()) {
return false
}
// Single peer groups always have a leader if we are here.
if rg.node == nil {
return false
}
// If we don't have a leader.
if rg.node.GroupLeader() == _EMPTY_ {
if rg.node.HadPreviousLeader() {
return true
}
// Make sure we have been running for enough time.
if time.Since(rg.node.Created()) > lostQuorumInterval {
return true
}
}
return false
}
func (s *Server) JetStreamIsStreamAssigned(account, stream string) bool {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return false
}
acc, _ := s.LookupAccount(account)
if acc == nil {
return false
}
return cc.isStreamAssigned(acc, stream)
}
// streamAssigned informs us if this server has this stream assigned.
func (jsa *jsAccount) streamAssigned(stream string) bool {
jsa.mu.RLock()
js, acc := jsa.js, jsa.account
jsa.mu.RUnlock()
if js == nil {
return false
}
js.mu.RLock()
assigned := js.cluster.isStreamAssigned(acc, stream)
js.mu.RUnlock()
return assigned
}
// Read lock should be held.
func (cc *jetStreamCluster) isStreamAssigned(a *Account, stream string) bool {
// Non-clustered mode always return true.
if cc == nil {
return true
}
as := cc.streams[a.Name]
if as == nil {
return false
}
sa := as[stream]
if sa == nil {
return false
}
rg := sa.Group
if rg == nil {
return false
}
// Check if we are the leader of this raftGroup assigned to the stream.
ourID := cc.meta.ID()
for _, peer := range rg.Peers {
if peer == ourID {
return true
}
}
return false
}
// Read lock should be held.
func (cc *jetStreamCluster) isStreamLeader(account, stream string) bool {
// Non-clustered mode always return true.
if cc == nil {
return true
}
if cc.meta == nil {
return false
}
var sa *streamAssignment
if as := cc.streams[account]; as != nil {
sa = as[stream]
}
if sa == nil {
return false
}
rg := sa.Group
if rg == nil {
return false
}
// Check if we are the leader of this raftGroup assigned to the stream.
ourID := cc.meta.ID()
for _, peer := range rg.Peers {
if peer == ourID {
if len(rg.Peers) == 1 || rg.node != nil && rg.node.Leader() {
return true
}
}
}
return false
}
// Read lock should be held.
func (cc *jetStreamCluster) isConsumerLeader(account, stream, consumer string) bool {
// Non-clustered mode always return true.
if cc == nil {
return true
}
if cc.meta == nil {
return false
}
var sa *streamAssignment
if as := cc.streams[account]; as != nil {
sa = as[stream]
}
if sa == nil {
return false
}
// Check if we are the leader of this raftGroup assigned to this consumer.
ca := sa.consumers[consumer]
if ca == nil {
return false
}
rg := ca.Group
ourID := cc.meta.ID()
for _, peer := range rg.Peers {
if peer == ourID {
if len(rg.Peers) == 1 || (rg.node != nil && rg.node.Leader()) {
return true
}
}
}
return false
}
func (js *jetStream) monitorCluster() {
s, n := js.server(), js.getMetaGroup()
qch, lch, ach := n.QuitC(), n.LeadChangeC(), n.ApplyC()
defer s.grWG.Done()
s.Debugf("Starting metadata monitor")
defer s.Debugf("Exiting metadata monitor")
const compactInterval = 2 * time.Minute
t := time.NewTicker(compactInterval)
defer t.Stop()
// Used to check cold boot cluster when possibly in mixed mode.
const leaderCheckInterval = time.Second
lt := time.NewTicker(leaderCheckInterval)
defer lt.Stop()
var (
isLeader bool
lastSnap []byte
lastSnapTime time.Time
isRecovering bool
beenLeader bool
)
// Set to true to start.
isRecovering = true
// Snapshotting function.
doSnapshot := func() {
// Suppress during recovery.
if isRecovering {
return
}
if snap := js.metaSnapshot(); !bytes.Equal(lastSnap, snap) {
if err := n.InstallSnapshot(snap); err == nil {
lastSnap = snap
lastSnapTime = time.Now()
}
}
}
for {
select {
case <-s.quitCh:
return
case <-qch:
return
case ce := <-ach:
if ce == nil {
// Signals we have replayed all of our metadata.
isRecovering = false
s.Debugf("Recovered JetStream cluster metadata")
continue
}
// FIXME(dlc) - Deal with errors.
if didSnap, didRemoval, err := js.applyMetaEntries(ce.Entries, isRecovering); err == nil {
_, nb := n.Applied(ce.Index)
if js.hasPeerEntries(ce.Entries) || didSnap || (didRemoval && time.Since(lastSnapTime) > 2*time.Second) {
// Since we received one make sure we have our own since we do not store
// our meta state outside of raft.
doSnapshot()
} else if lls := len(lastSnap); nb > uint64(lls*8) && lls > 0 {
doSnapshot()
}
}
case isLeader = <-lch:
js.processLeaderChange(isLeader)
if isLeader && !beenLeader {
beenLeader = true
if n.NeedSnapshot() {
if err := n.InstallSnapshot(js.metaSnapshot()); err != nil {
s.Warnf("Error snapshotting JetStream cluster state: %v", err)
}
}
js.checkClusterSize()
}
case <-t.C:
doSnapshot()
// Periodically check the cluster size.
if n.Leader() {
js.checkClusterSize()
}
case <-lt.C:
s.Debugf("Checking JetStream cluster state")
// If we have a current leader or had one in the past we can cancel this here since the metaleader
// will be in charge of all peer state changes.
// For cold boot only.
if n.GroupLeader() != _EMPTY_ || n.HadPreviousLeader() {
lt.Stop()
continue
}
// If we are here we do not have a leader and we did not have a previous one, so cold start.
// Check to see if we can adjust our cluster size down iff we are in mixed mode and we have
// seen a total that is what our original estimate was.
if js, total := s.trackedJetStreamServers(); js < total && total >= n.ClusterSize() {
s.Noticef("Adjusting JetStream expected peer set size to %d from original %d", js, n.ClusterSize())
n.AdjustBootClusterSize(js)
}
}
}
}
// This is called on first leader transition to double check the peers and cluster set size.
func (js *jetStream) checkClusterSize() {
s, n := js.server(), js.getMetaGroup()
if n == nil {
return
}
// We will check that we have a correct cluster set size by checking for any non-js servers
// which can happen in mixed mode.
ps := n.(*raft).currentPeerState()
if len(ps.knownPeers) >= ps.clusterSize {
return
}
// Grab our active peers.
peers := s.ActivePeers()
// If we have not registered all of our peers yet we can't do
// any adjustments based on a mixed mode. We will periodically check back.
if len(peers) < ps.clusterSize {
return
}
s.Debugf("Checking JetStream cluster size")
// If we are here our known set as the leader is not the same as the cluster size.
// Check to see if we have a mixed mode setup.
var totalJS int
for _, p := range peers {
if si, ok := s.nodeToInfo.Load(p); ok && si != nil {
if si.(nodeInfo).js {
totalJS++
}
}
}
// If we have less then our cluster size adjust that here. Can not do individual peer removals since
// they will not be in the tracked peers.
if totalJS < ps.clusterSize {
s.Debugf("Adjusting JetStream cluster size from %d to %d", ps.clusterSize, totalJS)
if err := n.AdjustClusterSize(totalJS); err != nil {
s.Warnf("Error adjusting JetStream cluster size: %v", err)
}
}
}
// Represents our stable meta state that we can write out.
type writeableStreamAssignment struct {
Client *ClientInfo `json:"client,omitempty"`
Created time.Time `json:"created"`
Config *StreamConfig `json:"stream"`
Group *raftGroup `json:"group"`
Sync string `json:"sync"`
Consumers []*consumerAssignment
}
func (js *jetStream) metaSnapshot() []byte {
var streams []writeableStreamAssignment
js.mu.RLock()
cc := js.cluster
for _, asa := range cc.streams {
for _, sa := range asa {
wsa := writeableStreamAssignment{
Client: sa.Client,
Created: sa.Created,
Config: sa.Config,
Group: sa.Group,
Sync: sa.Sync,
}
for _, ca := range sa.consumers {
wsa.Consumers = append(wsa.Consumers, ca)
}
streams = append(streams, wsa)
}
}
if len(streams) == 0 {
js.mu.RUnlock()
return nil
}
b, _ := json.Marshal(streams)
js.mu.RUnlock()
return s2.EncodeBetter(nil, b)
}
func (js *jetStream) applyMetaSnapshot(buf []byte, isRecovering bool) error {
if len(buf) == 0 {
return nil
}
jse, err := s2.Decode(nil, buf)
if err != nil {
return err
}
var wsas []writeableStreamAssignment
if err = json.Unmarshal(jse, &wsas); err != nil {
return err
}
// Build our new version here outside of js.
streams := make(map[string]map[string]*streamAssignment)
for _, wsa := range wsas {
as := streams[wsa.Client.serviceAccount()]
if as == nil {
as = make(map[string]*streamAssignment)
streams[wsa.Client.serviceAccount()] = as
}
sa := &streamAssignment{Client: wsa.Client, Created: wsa.Created, Config: wsa.Config, Group: wsa.Group, Sync: wsa.Sync}
if len(wsa.Consumers) > 0 {
sa.consumers = make(map[string]*consumerAssignment)
for _, ca := range wsa.Consumers {
sa.consumers[ca.Name] = ca
}
}
as[wsa.Config.Name] = sa
}
js.mu.Lock()
cc := js.cluster
var saAdd, saDel, saChk []*streamAssignment
// Walk through the old list to generate the delete list.
for account, asa := range cc.streams {
nasa := streams[account]
for sn, sa := range asa {
if nsa := nasa[sn]; nsa == nil {
saDel = append(saDel, sa)
} else {
saChk = append(saChk, nsa)
}
}
}
// Walk through the new list to generate the add list.
for account, nasa := range streams {
asa := cc.streams[account]
for sn, sa := range nasa {
if asa[sn] == nil {
saAdd = append(saAdd, sa)
}
}
}
// Now walk the ones to check and process consumers.
var caAdd, caDel []*consumerAssignment
for _, sa := range saChk {
if osa := js.streamAssignment(sa.Client.serviceAccount(), sa.Config.Name); osa != nil {
for _, ca := range osa.consumers {
if sa.consumers[ca.Name] == nil {
caDel = append(caDel, ca)
} else {
caAdd = append(caAdd, ca)
}
}
}
}
js.mu.Unlock()
// Do removals first.
for _, sa := range saDel {
if isRecovering {
js.setStreamAssignmentRecovering(sa)
}
js.processStreamRemoval(sa)
}
// Now do add for the streams. Also add in all consumers.
for _, sa := range saAdd {
if isRecovering {
js.setStreamAssignmentRecovering(sa)
}
js.processStreamAssignment(sa)
// We can simply add the consumers.
for _, ca := range sa.consumers {
if isRecovering {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerAssignment(ca)
}
}
// Now do the deltas for existing stream's consumers.
for _, ca := range caDel {
if isRecovering {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerRemoval(ca)
}
for _, ca := range caAdd {
if isRecovering {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerAssignment(ca)
}
return nil
}
// Called on recovery to make sure we do not process like original.
func (js *jetStream) setStreamAssignmentRecovering(sa *streamAssignment) {
js.mu.Lock()
defer js.mu.Unlock()
sa.responded = true
sa.Restore = nil
if sa.Group != nil {
sa.Group.Preferred = _EMPTY_
}
}
// Called on recovery to make sure we do not process like original.
func (js *jetStream) setConsumerAssignmentRecovering(ca *consumerAssignment) {
js.mu.Lock()
defer js.mu.Unlock()
ca.responded = true
if ca.Group != nil {
ca.Group.Preferred = _EMPTY_
}
}
// Just copied over and changes out the group so it can be encoded.
// Lock should be held.
func (sa *streamAssignment) copyGroup() *streamAssignment {
csa, cg := *sa, *sa.Group
csa.Group = &cg
csa.Group.Peers = append(sa.Group.Peers[:0:0], sa.Group.Peers...)
return &csa
}
// Lock should be held.
func (sa *streamAssignment) missingPeers() bool {
return len(sa.Group.Peers) < sa.Config.Replicas
}
// Called when we detect a new peer. Only the leader will process checking
// for any streams, and consequently any consumers.
func (js *jetStream) processAddPeer(peer string) {
js.mu.Lock()
defer js.mu.Unlock()
s, cc := js.srv, js.cluster
isLeader := cc.isLeader()
// Now check if we are meta-leader. We will check for any re-assignments.
if !isLeader {
return
}
sir, ok := s.nodeToInfo.Load(peer)
if !ok || sir == nil {
return
}
si := sir.(nodeInfo)
for _, asa := range cc.streams {
for _, sa := range asa {
if sa.missingPeers() {
// Make sure the right cluster etc.
if si.cluster != sa.Client.Cluster {
continue
}
// If we are here we can add in this peer.
csa := sa.copyGroup()
csa.Group.Peers = append(csa.Group.Peers, peer)
// Send our proposal for this csa. Also use same group definition for all the consumers as well.
cc.meta.Propose(encodeAddStreamAssignment(csa))
for _, ca := range sa.consumers {
// Ephemerals are R=1, so only auto-remap durables, or R>1.
if ca.Config.Durable != _EMPTY_ {
cca := *ca
cca.Group.Peers = csa.Group.Peers
cc.meta.Propose(encodeAddConsumerAssignment(&cca))
}
}
}
}
}
}
func (js *jetStream) processRemovePeer(peer string) {
js.mu.Lock()
s, cc := js.srv, js.cluster
isLeader := cc.isLeader()
// All nodes will check if this is them.
isUs := cc.meta.ID() == peer
disabled := js.disabled
js.mu.Unlock()
// We may be already disabled.
if disabled {
return
}
if isUs {
s.Errorf("JetStream being DISABLED, our server was removed from the cluster")
adv := &JSServerRemovedAdvisory{
TypedEvent: TypedEvent{
Type: JSServerRemovedAdvisoryType,
ID: nuid.Next(),
Time: time.Now().UTC(),
},
Server: s.Name(),
ServerID: s.ID(),
Cluster: s.cachedClusterName(),
Domain: s.getOpts().JetStreamDomain,
}
s.publishAdvisory(nil, JSAdvisoryServerRemoved, adv)
go s.DisableJetStream()
}
// Now check if we are meta-leader. We will attempt re-assignment.
if !isLeader {
return
}
js.mu.Lock()
defer js.mu.Unlock()
for _, asa := range cc.streams {
for _, sa := range asa {
if rg := sa.Group; rg.isMember(peer) {
js.removePeerFromStreamLocked(sa, peer)
}
}
}
}
// Assumes all checks have already been done.
func (js *jetStream) removePeerFromStream(sa *streamAssignment, peer string) bool {
js.mu.Lock()
defer js.mu.Unlock()
return js.removePeerFromStreamLocked(sa, peer)
}
// Lock should be held.
func (js *jetStream) removePeerFromStreamLocked(sa *streamAssignment, peer string) bool {
if rg := sa.Group; !rg.isMember(peer) {
return false
}
s, cc, csa := js.srv, js.cluster, sa.copyGroup()
replaced := cc.remapStreamAssignment(csa, peer)
if !replaced {
s.Warnf("JetStream cluster could not replace peer for stream '%s > %s'", sa.Client.serviceAccount(), sa.Config.Name)
}
// Send our proposal for this csa. Also use same group definition for all the consumers as well.
cc.meta.Propose(encodeAddStreamAssignment(csa))
rg := csa.Group
for _, ca := range sa.consumers {
// Ephemerals are R=1, so only auto-remap durables, or R>1.
if ca.Config.Durable != _EMPTY_ {
cca := *ca
cca.Group.Peers = rg.Peers
cc.meta.Propose(encodeAddConsumerAssignment(&cca))
} else if ca.Group.isMember(peer) {
// These are ephemerals. Check to see if we deleted this peer.
cc.meta.Propose(encodeDeleteConsumerAssignment(ca))
}
}
return replaced
}
// Check if we have peer related entries.
func (js *jetStream) hasPeerEntries(entries []*Entry) bool {
for _, e := range entries {
if e.Type == EntryRemovePeer || e.Type == EntryAddPeer {
return true
}
}
return false
}
func (js *jetStream) applyMetaEntries(entries []*Entry, isRecovering bool) (bool, bool, error) {
var didSnap, didRemove bool
for _, e := range entries {
if e.Type == EntrySnapshot {
js.applyMetaSnapshot(e.Data, isRecovering)
didSnap = true
} else if e.Type == EntryRemovePeer {
if !isRecovering {
js.processRemovePeer(string(e.Data))
}
} else if e.Type == EntryAddPeer {
if !isRecovering {
js.processAddPeer(string(e.Data))
}
} else {
buf := e.Data
switch entryOp(buf[0]) {
case assignStreamOp:
sa, err := decodeStreamAssignment(buf[1:])
if err != nil {
js.srv.Errorf("JetStream cluster failed to decode stream assignment: %q", buf[1:])
return didSnap, didRemove, err
}
if isRecovering {
js.setStreamAssignmentRecovering(sa)
}
didRemove = js.processStreamAssignment(sa)
case removeStreamOp:
sa, err := decodeStreamAssignment(buf[1:])
if err != nil {
js.srv.Errorf("JetStream cluster failed to decode stream assignment: %q", buf[1:])
return didSnap, didRemove, err
}
if isRecovering {
js.setStreamAssignmentRecovering(sa)
}
js.processStreamRemoval(sa)
didRemove = true
case assignConsumerOp:
ca, err := decodeConsumerAssignment(buf[1:])
if err != nil {
js.srv.Errorf("JetStream cluster failed to decode consumer assigment: %q", buf[1:])
return didSnap, didRemove, err
}
if isRecovering {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerAssignment(ca)
case assignCompressedConsumerOp:
ca, err := decodeConsumerAssignmentCompressed(buf[1:])
if err != nil {
js.srv.Errorf("JetStream cluster failed to decode compressed consumer assigment: %q", buf[1:])
return didSnap, didRemove, err
}
if isRecovering {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerAssignment(ca)
case removeConsumerOp:
ca, err := decodeConsumerAssignment(buf[1:])
if err != nil {
js.srv.Errorf("JetStream cluster failed to decode consumer assigment: %q", buf[1:])
return didSnap, didRemove, err
}
if isRecovering {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerRemoval(ca)
didRemove = true
case updateStreamOp:
sa, err := decodeStreamAssignment(buf[1:])
if err != nil {
js.srv.Errorf("JetStream cluster failed to decode stream assignment: %q", buf[1:])
return didSnap, didRemove, err
}
if isRecovering {
js.setStreamAssignmentRecovering(sa)
}
js.processUpdateStreamAssignment(sa)
default:
panic("JetStream Cluster Unknown meta entry op type")
}
}
}
return didSnap, didRemove, nil
}
func (rg *raftGroup) isMember(id string) bool {
if rg == nil {
return false
}
for _, peer := range rg.Peers {
if peer == id {
return true
}
}
return false
}
func (rg *raftGroup) setPreferred() {
if rg == nil || len(rg.Peers) == 0 {
return
}
if len(rg.Peers) == 1 {
rg.Preferred = rg.Peers[0]
} else {
// For now just randomly select a peer for the preferred.
pi := rand.Int31n(int32(len(rg.Peers)))
rg.Preferred = rg.Peers[pi]
}
}
// createRaftGroup is called to spin up this raft group if needed.
func (js *jetStream) createRaftGroup(rg *raftGroup, storage StorageType) error {
js.mu.Lock()
defer js.mu.Unlock()
s, cc := js.srv, js.cluster
if cc == nil || cc.meta == nil {
return NewJSClusterNotActiveError()
}
// If this is a single peer raft group or we are not a member return.
if len(rg.Peers) <= 1 || !rg.isMember(cc.meta.ID()) {
// Nothing to do here.
return nil
}
// Check if we already have this assigned.
if node := s.lookupRaftNode(rg.Name); node != nil {
s.Debugf("JetStream cluster already has raft group %q assigned", rg.Name)
rg.node = node
return nil
}
s.Debugf("JetStream cluster creating raft group:%+v", rg)
sysAcc := s.SystemAccount()
if sysAcc == nil {
s.Debugf("JetStream cluster detected shutdown processing raft group: %+v", rg)
return errors.New("shutting down")
}
storeDir := path.Join(js.config.StoreDir, sysAcc.Name, defaultStoreDirName, rg.Name)
var store StreamStore
if storage == FileStorage {
fs, err := newFileStore(
FileStoreConfig{StoreDir: storeDir, BlockSize: 4_000_000, AsyncFlush: false, SyncInterval: 5 * time.Minute},
StreamConfig{Name: rg.Name, Storage: FileStorage},
)
if err != nil {
s.Errorf("Error creating filestore WAL: %v", err)
return err
}
store = fs
} else {
ms, err := newMemStore(&StreamConfig{Name: rg.Name, Storage: MemoryStorage})
if err != nil {
s.Errorf("Error creating memstore WAL: %v", err)
return err
}
store = ms
}
cfg := &RaftConfig{Name: rg.Name, Store: storeDir, Log: store, Track: true}
if _, err := readPeerState(storeDir); err != nil {
s.bootstrapRaftNode(cfg, rg.Peers, true)
}
n, err := s.startRaftNode(cfg)
if err != nil || n == nil {
s.Debugf("Error creating raft group: %v", err)
return err
}
rg.node = n
// See if we are preferred and should start campaign immediately.
if n.ID() == rg.Preferred {
n.Campaign()
}
return nil
}
func (mset *stream) raftGroup() *raftGroup {
if mset == nil {
return nil
}
mset.mu.RLock()
defer mset.mu.RUnlock()
if mset.sa == nil {
return nil
}
return mset.sa.Group
}
func (mset *stream) raftNode() RaftNode {
if mset == nil {
return nil
}
mset.mu.RLock()
defer mset.mu.RUnlock()
return mset.node
}
// Monitor our stream node for this stream.
func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment) {
s, cc, n := js.server(), js.cluster, sa.Group.node
defer s.grWG.Done()
if n == nil {
s.Warnf("No RAFT group for '%s > %s", sa.Client.serviceAccount(), sa.Config.Name)
return
}
qch, lch, ach := n.QuitC(), n.LeadChangeC(), n.ApplyC()
s.Debugf("Starting stream monitor for '%s > %s'", sa.Client.serviceAccount(), sa.Config.Name)
defer s.Debugf("Exiting stream monitor for '%s > %s'", sa.Client.serviceAccount(), sa.Config.Name)
// Make sure we do not leave the apply channel to fill up and block the raft layer.
defer func() {
if n.State() == Closed {
return
}
if n.Leader() {
n.StepDown()
}
// Drain the commit channel..
for len(ach) > 0 {
select {
case <-ach:
default:
return
}
}
}()
const (
compactInterval = 2 * time.Minute
compactSizeMin = 32 * 1024 * 1024
compactNumMin = 8192
)
t := time.NewTicker(compactInterval)
defer t.Stop()
js.mu.RLock()
isLeader := cc.isStreamLeader(sa.Client.serviceAccount(), sa.Config.Name)
isRestore := sa.Restore != nil
js.mu.RUnlock()
acc, err := s.LookupAccount(sa.Client.serviceAccount())
if err != nil {
s.Warnf("Could not retrieve account for stream '%s > %s", sa.Client.serviceAccount(), sa.Config.Name)
return
}
var lastSnap []byte
// Should only to be called from leader.
doSnapshot := func() {
if mset == nil || isRestore {
return
}
if snap := mset.stateSnapshot(); !bytes.Equal(lastSnap, snap) {
if err := n.InstallSnapshot(snap); err == nil {
lastSnap = snap
}
}
}
// We will establish a restoreDoneCh no matter what. Will never be triggered unless
// we replace with the restore chan.
restoreDoneCh := make(<-chan error)
isRecovering := true
for {
select {
case <-s.quitCh:
return
case <-qch:
return
case ce := <-ach:
// No special processing needed for when we are caught up on restart.
if ce == nil {
isRecovering = false
// Check on startup if we should snapshot/compact.
if _, b := n.Size(); b > compactSizeMin || n.NeedSnapshot() {
doSnapshot()
}
continue
}
// Apply our entries.
if err := js.applyStreamEntries(mset, ce, isRecovering); err == nil {
ne, nb := n.Applied(ce.Index)
// If we have at least min entries to compact, go ahead and snapshot/compact.
if ne >= compactNumMin || nb > compactSizeMin {
doSnapshot()
}
} else {
s.Warnf("Error applying entries to '%s > %s': %v", sa.Client.serviceAccount(), sa.Config.Name, err)
if isClusterResetErr(err) {
if mset.isMirror() && mset.IsLeader() {
mset.retryMirrorConsumer()
continue
}
// We will attempt to reset our cluster state.
if mset.resetClusteredState(err) {
return
}
} else if isOutOfSpaceErr(err) {
// If applicable this will tear all of this down, but don't assume so and return.
s.handleOutOfSpace(mset)
}
}
case isLeader = <-lch:
if isLeader {
if isRestore {
acc, _ := s.LookupAccount(sa.Client.serviceAccount())
restoreDoneCh = s.processStreamRestore(sa.Client, acc, sa.Config, _EMPTY_, sa.Reply, _EMPTY_)
continue
} else if n.NeedSnapshot() {
doSnapshot()
}
} else if n.GroupLeader() != noLeader {
js.setStreamAssignmentRecovering(sa)
}
js.processStreamLeaderChange(mset, isLeader)
case <-t.C:
doSnapshot()
case err := <-restoreDoneCh:
// We have completed a restore from snapshot on this server. The stream assignment has
// already been assigned but the replicas will need to catch up out of band. Consumers
// will need to be assigned by forwarding the proposal and stamping the initial state.
s.Debugf("Stream restore for '%s > %s' completed", sa.Client.serviceAccount(), sa.Config.Name)
if err != nil {
s.Debugf("Stream restore failed: %v", err)
}
isRestore = false
sa.Restore = nil
// If we were successful lookup up our stream now.
if err == nil {
mset, err = acc.lookupStream(sa.Config.Name)
if mset != nil {
mset.setStreamAssignment(sa)
}
}
if err != nil {
if mset != nil {
mset.delete()
}
js.mu.Lock()
sa.err = err
if n != nil {
n.Delete()
}
result := &streamAssignmentResult{
Account: sa.Client.serviceAccount(),
Stream: sa.Config.Name,
Restore: &JSApiStreamRestoreResponse{ApiResponse: ApiResponse{Type: JSApiStreamRestoreResponseType}},
}
result.Restore.Error = NewJSStreamAssignmentError(err, Unless(err))
js.mu.Unlock()
// Send response to the metadata leader. They will forward to the user as needed.
s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, result)
return
}
if !isLeader {
panic("Finished restore but not leader")
}
// Trigger the stream followers to catchup.
if n := mset.raftNode(); n != nil {
n.SendSnapshot(mset.stateSnapshot())
}
js.processStreamLeaderChange(mset, isLeader)
// Check to see if we have restored consumers here.
// These are not currently assigned so we will need to do so here.
if consumers := mset.getPublicConsumers(); len(consumers) > 0 {
for _, o := range consumers {
rg := cc.createGroupForConsumer(sa)
// Pick a preferred leader.
rg.setPreferred()
name, cfg := o.String(), o.config()
// Place our initial state here as well for assignment distribution.
ca := &consumerAssignment{
Group: rg,
Stream: sa.Config.Name,
Name: name,
Config: &cfg,
Client: sa.Client,
Created: o.createdTime(),
State: o.readStoreState(),
}
// We make these compressed in case state is complex.
addEntry := encodeAddConsumerAssignmentCompressed(ca)
cc.meta.ForwardProposal(addEntry)
// Check to make sure we see the assignment.
go func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for range ticker.C {
js.mu.RLock()
ca, meta := js.consumerAssignment(ca.Client.serviceAccount(), sa.Config.Name, name), cc.meta
js.mu.RUnlock()
if ca == nil {
s.Warnf("Consumer assignment has not been assigned, retrying")
if meta != nil {
meta.ForwardProposal(addEntry)
} else {
return
}
} else {
return
}
}
}()
}
}
}
}
}
// resetClusteredState is called when a clustered stream had a sequence mismatch and needs to be reset.
func (mset *stream) resetClusteredState(err error) bool {
mset.mu.RLock()
s, js, jsa, sa, acc, node := mset.srv, mset.js, mset.jsa, mset.sa, mset.acc, mset.node
stype, isLeader := mset.cfg.Storage, mset.isLeader()
mset.mu.RUnlock()
// Stepdown regardless if we are the leader here.
if isLeader && node != nil {
node.StepDown()
}
// Server
if js.limitsExceeded(stype) {
s.Debugf("Will not reset stream, server resources exceeded")
return false
}
// Account
if jsa.limitsExceeded(stype) {
s.Warnf("stream '%s > %s' errored, account resources exceeded", acc, mset.name())
return false
}
// We delete our raft state. Will recreate.
if node != nil {
node.Delete()
}
// Preserve our current state and messages unless we have a first sequence mismatch.
shouldDelete := err == errFirstSequenceMismatch
mset.stop(shouldDelete, false)
if sa != nil {
s.Warnf("Resetting stream cluster state for '%s > %s'", sa.Client.serviceAccount(), sa.Config.Name)
js.mu.Lock()
sa.Group.node = nil
js.mu.Unlock()
go js.restartClustered(acc, sa)
}
return true
}
// This will reset the stream and consumers.
// Should be done in separate go routine.
func (js *jetStream) restartClustered(acc *Account, sa *streamAssignment) {
js.processClusterCreateStream(acc, sa)
// Check consumers.
js.mu.Lock()
var consumers []*consumerAssignment
if cc := js.cluster; cc != nil && cc.meta != nil {
ourID := cc.meta.ID()
for _, ca := range sa.consumers {
if rg := ca.Group; rg != nil && rg.isMember(ourID) {
rg.node = nil // Erase group raft/node state.
consumers = append(consumers, ca)
}
}
}
js.mu.Unlock()
for _, ca := range consumers {
js.processClusterCreateConsumer(ca, nil)
}
}
func isControlHdr(hdr []byte) bool {
return bytes.HasPrefix(hdr, []byte("NATS/1.0 100 "))
}
// Apply our stream entries.
func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isRecovering bool) error {
for _, e := range ce.Entries {
if e.Type == EntryNormal {
buf := e.Data
switch entryOp(buf[0]) {
case streamMsgOp:
if mset == nil {
continue
}
s := js.srv
subject, reply, hdr, msg, lseq, ts, err := decodeStreamMsg(buf[1:])
if err != nil {
panic(err.Error())
}
// Check for flowcontrol here.
if !isRecovering && len(msg) == 0 && len(hdr) > 0 && reply != _EMPTY_ && isControlHdr(hdr) {
mset.sendFlowControlReply(reply)
continue
}
// Grab last sequence.
last := mset.lastSeq()
// We can skip if we know this is less than what we already have.
if lseq < last {
s.Debugf("Apply stream entries skipping message with sequence %d with last of %d", lseq, last)
continue
}
// Skip by hand here since first msg special case.
// Reason is sequence is unsigned and for lseq being 0
// the lseq under stream would have to be -1.
if lseq == 0 && last != 0 {
continue
}
// Messages to be skipped have no subject or timestamp or msg or hdr.
if subject == _EMPTY_ && ts == 0 && len(msg) == 0 && len(hdr) == 0 {
// Skip and update our lseq.
mset.setLastSeq(mset.store.SkipMsg())
continue
}
// Process the actual message here.
if err := mset.processJetStreamMsg(subject, reply, hdr, msg, lseq, ts); err != nil {
return err
}
case deleteMsgOp:
md, err := decodeMsgDelete(buf[1:])
if err != nil {
panic(err.Error())
}
s, cc := js.server(), js.cluster
var removed bool
if md.NoErase {
removed, err = mset.removeMsg(md.Seq)
} else {
removed, err = mset.eraseMsg(md.Seq)
}
// Cluster reset error.
if err == ErrStoreEOF {
return err
}
if err != nil && !isRecovering {
s.Debugf("JetStream cluster failed to delete msg %d from stream %q for account %q: %v",
md.Seq, md.Stream, md.Client.serviceAccount(), err)
}
js.mu.RLock()
isLeader := cc.isStreamLeader(md.Client.serviceAccount(), md.Stream)
js.mu.RUnlock()
if isLeader && !isRecovering {
var resp = JSApiMsgDeleteResponse{ApiResponse: ApiResponse{Type: JSApiMsgDeleteResponseType}}
if err != nil {
resp.Error = NewJSStreamMsgDeleteFailedError(err, Unless(err))
s.sendAPIErrResponse(md.Client, mset.account(), md.Subject, md.Reply, _EMPTY_, s.jsonResponse(resp))
} else if !removed {
resp.Error = NewJSSequenceNotFoundError(md.Seq)
s.sendAPIErrResponse(md.Client, mset.account(), md.Subject, md.Reply, _EMPTY_, s.jsonResponse(resp))
} else {
resp.Success = true
s.sendAPIResponse(md.Client, mset.account(), md.Subject, md.Reply, _EMPTY_, s.jsonResponse(resp))
}
}
case purgeStreamOp:
sp, err := decodeStreamPurge(buf[1:])
if err != nil {
panic(err.Error())
}
// Ignore if we are recovering and we have already processed.
if isRecovering {
if mset.state().FirstSeq <= sp.LastSeq {
// Make sure all messages from the purge are gone.
mset.store.Compact(sp.LastSeq + 1)
}
continue
}
s := js.server()
purged, err := mset.purge(sp.Request)
if err != nil {
s.Warnf("JetStream cluster failed to purge stream %q for account %q: %v", sp.Stream, sp.Client.serviceAccount(), err)
}
js.mu.RLock()
isLeader := js.cluster.isStreamLeader(sp.Client.serviceAccount(), sp.Stream)
js.mu.RUnlock()
if isLeader && !isRecovering {
var resp = JSApiStreamPurgeResponse{ApiResponse: ApiResponse{Type: JSApiStreamPurgeResponseType}}
if err != nil {
resp.Error = NewJSStreamGeneralError(err, Unless(err))
s.sendAPIErrResponse(sp.Client, mset.account(), sp.Subject, sp.Reply, _EMPTY_, s.jsonResponse(resp))
} else {
resp.Purged = purged
resp.Success = true
s.sendAPIResponse(sp.Client, mset.account(), sp.Subject, sp.Reply, _EMPTY_, s.jsonResponse(resp))
}
}
default:
panic("JetStream Cluster Unknown group entry op type!")
}
} else if e.Type == EntrySnapshot {
if !isRecovering && mset != nil {
var snap streamSnapshot
if err := json.Unmarshal(e.Data, &snap); err != nil {
return err
}
if err := mset.processSnapshot(&snap); err != nil {
return err
}
}
} else if e.Type == EntryRemovePeer {
js.mu.RLock()
var ourID string
if js.cluster != nil && js.cluster.meta != nil {
ourID = js.cluster.meta.ID()
}
js.mu.RUnlock()
// We only need to do processing if this is us.
if peer := string(e.Data); peer == ourID {
mset.stop(true, false)
}
return nil
}
}
return nil
}
// Returns the PeerInfo for all replicas of a raft node. This is different than node.Peers()
// and is used for external facing advisories.
func (s *Server) replicas(node RaftNode) []*PeerInfo {
now := time.Now()
var replicas []*PeerInfo
for _, rp := range node.Peers() {
if sir, ok := s.nodeToInfo.Load(rp.ID); ok && sir != nil {
si := sir.(nodeInfo)
pi := &PeerInfo{Name: si.name, Current: rp.Current, Active: now.Sub(rp.Last), Offline: si.offline, Lag: rp.Lag}
replicas = append(replicas, pi)
}
}
return replicas
}
// Will check our node peers and see if we should remove a peer.
func (js *jetStream) checkPeers(rg *raftGroup) {
js.mu.Lock()
defer js.mu.Unlock()
// FIXME(dlc) - Single replicas?
if rg == nil || rg.node == nil {
return
}
for _, peer := range rg.node.Peers() {
if !rg.isMember(peer.ID) {
rg.node.ProposeRemovePeer(peer.ID)
}
}
}
// Process a leader change for the clustered stream.
func (js *jetStream) processStreamLeaderChange(mset *stream, isLeader bool) {
if mset == nil {
return
}
sa := mset.streamAssignment()
if sa == nil {
return
}
js.mu.Lock()
s, account, err := js.srv, sa.Client.serviceAccount(), sa.err
client, subject, reply := sa.Client, sa.Subject, sa.Reply
hasResponded := sa.responded
sa.responded = true
js.mu.Unlock()
streamName := mset.name()
if isLeader {
s.Noticef("JetStream cluster new stream leader for '%s > %s'", sa.Client.serviceAccount(), streamName)
s.sendStreamLeaderElectAdvisory(mset)
// Check for peer removal and process here if needed.
js.checkPeers(sa.Group)
} else {
// We are stepping down.
// Make sure if we are doing so because we have lost quorum that we send the appropriate advisories.
if node := mset.raftNode(); node != nil && !node.Quorum() && time.Since(node.Created()) > 5*time.Second {
s.sendStreamLostQuorumAdvisory(mset)
}
}
// Tell stream to switch leader status.
mset.setLeader(isLeader)
if !isLeader || hasResponded {
return
}
acc, _ := s.LookupAccount(account)
if acc == nil {
return
}
// Send our response.
var resp = JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}}
if err != nil {
resp.Error = NewJSStreamCreateError(err, Unless(err))
s.sendAPIErrResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
} else {
resp.StreamInfo = &StreamInfo{
Created: mset.createdTime(),
State: mset.state(),
Config: mset.config(),
Cluster: js.clusterInfo(mset.raftGroup()),
Sources: mset.sourcesInfo(),
Mirror: mset.mirrorInfo(),
}
resp.DidCreate = true
s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
if node := mset.raftNode(); node != nil {
mset.sendCreateAdvisory()
}
}
}
// Fixed value ok for now.
const lostQuorumAdvInterval = 10 * time.Second
// Determines if we should send lost quorum advisory. We throttle these after first one.
func (mset *stream) shouldSendLostQuorum() bool {
mset.mu.Lock()
defer mset.mu.Unlock()
if time.Since(mset.lqsent) >= lostQuorumAdvInterval {
mset.lqsent = time.Now()
return true
}
return false
}
func (s *Server) sendStreamLostQuorumAdvisory(mset *stream) {
if mset == nil {
return
}
node, stream, acc := mset.raftNode(), mset.name(), mset.account()
if node == nil {
return
}
if !mset.shouldSendLostQuorum() {
return
}
s.Warnf("JetStream cluster stream '%s > %s' has NO quorum, stalled.", acc.GetName(), stream)
subj := JSAdvisoryStreamQuorumLostPre + "." + stream
adv := &JSStreamQuorumLostAdvisory{
TypedEvent: TypedEvent{
Type: JSStreamQuorumLostAdvisoryType,
ID: nuid.Next(),
Time: time.Now().UTC(),
},
Stream: stream,
Replicas: s.replicas(node),
Domain: s.getOpts().JetStreamDomain,
}
// Send to the user's account if not the system account.
if acc != s.SystemAccount() {
s.publishAdvisory(acc, subj, adv)
}
// Now do system level one. Place account info in adv, and nil account means system.
adv.Account = acc.GetName()
s.publishAdvisory(nil, subj, adv)
}
func (s *Server) sendStreamLeaderElectAdvisory(mset *stream) {
if mset == nil {
return
}
node, stream, acc := mset.raftNode(), mset.name(), mset.account()
if node == nil {
return
}
subj := JSAdvisoryStreamLeaderElectedPre + "." + stream
adv := &JSStreamLeaderElectedAdvisory{
TypedEvent: TypedEvent{
Type: JSStreamLeaderElectedAdvisoryType,
ID: nuid.Next(),
Time: time.Now().UTC(),
},
Stream: stream,
Leader: s.serverNameForNode(node.GroupLeader()),
Replicas: s.replicas(node),
Domain: s.getOpts().JetStreamDomain,
}
// Send to the user's account if not the system account.
if acc != s.SystemAccount() {
s.publishAdvisory(acc, subj, adv)
}
// Now do system level one. Place account info in adv, and nil account means system.
adv.Account = acc.GetName()
s.publishAdvisory(nil, subj, adv)
}
// Will lookup a stream assignment.
// Lock should be held.
func (js *jetStream) streamAssignment(account, stream string) (sa *streamAssignment) {
cc := js.cluster
if cc == nil {
return nil
}
if as := cc.streams[account]; as != nil {
sa = as[stream]
}
return sa
}
// processStreamAssignment is called when followers have replicated an assignment.
func (js *jetStream) processStreamAssignment(sa *streamAssignment) bool {
js.mu.RLock()
s, cc := js.srv, js.cluster
accName, stream := sa.Client.serviceAccount(), sa.Config.Name
noMeta := cc == nil || cc.meta == nil
var ourID string
if !noMeta {
ourID = cc.meta.ID()
}
var isMember bool
if sa.Group != nil && ourID != _EMPTY_ {
isMember = sa.Group.isMember(ourID)
}
js.mu.RUnlock()
if s == nil || noMeta {
return false
}
acc, err := s.LookupAccount(accName)
if err != nil {
ll := fmt.Sprintf("Account [%s] lookup for stream create failed: %v", accName, err)
if isMember {
// If we can not lookup the account and we are a member, send this result back to the metacontroller leader.
result := &streamAssignmentResult{
Account: accName,
Stream: stream,
Response: &JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}},
}
result.Response.Error = NewJSNoAccountError()
s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, result)
s.Warnf(ll)
} else {
s.Debugf(ll)
}
return false
}
js.mu.Lock()
accStreams := cc.streams[acc.Name]
if accStreams == nil {
accStreams = make(map[string]*streamAssignment)
} else if osa := accStreams[stream]; osa != nil {
// Copy over private existing state from former SA.
sa.Group.node = osa.Group.node
sa.consumers = osa.consumers
sa.responded = osa.responded
sa.err = osa.err
}
// Update our state.
accStreams[stream] = sa
cc.streams[acc.Name] = accStreams
js.mu.Unlock()
var didRemove bool
// Check if this is for us..
if isMember {
js.processClusterCreateStream(acc, sa)
} else {
// Check if we have a raft node running, meaning we are no longer part of the group but were.
js.mu.Lock()
if node := sa.Group.node; node != nil {
node.ProposeRemovePeer(ourID)
}
sa.Group.node = nil
sa.err = nil
js.mu.Unlock()
}
// If this stream assignment does not have a sync subject (bug) set that the meta-leader should check when elected.
if sa.Sync == _EMPTY_ {
js.mu.Lock()
cc.streamsCheck = true
js.mu.Unlock()
return false
}
return didRemove
}
// processUpdateStreamAssignment is called when followers have replicated an updated assignment.
func (js *jetStream) processUpdateStreamAssignment(sa *streamAssignment) {
js.mu.RLock()
s, cc := js.srv, js.cluster
js.mu.RUnlock()
if s == nil || cc == nil {
// TODO(dlc) - debug at least
return
}
acc, err := s.LookupAccount(sa.Client.serviceAccount())
if err != nil {
// TODO(dlc) - log error
return
}
stream := sa.Config.Name
js.mu.Lock()
if cc.meta == nil {
js.mu.Unlock()
return
}
ourID := cc.meta.ID()
var isMember bool
if sa.Group != nil {
isMember = sa.Group.isMember(ourID)
}
accStreams := cc.streams[acc.Name]
if accStreams == nil {
js.mu.Unlock()
return
}
osa := accStreams[stream]
if osa == nil {
js.mu.Unlock()
return
}
// Copy over private existing state from former SA.
sa.Group.node = osa.Group.node
sa.consumers = osa.consumers
sa.err = osa.err
// Update our state.
accStreams[stream] = sa
cc.streams[acc.Name] = accStreams
// Make sure we respond.
if isMember {
sa.responded = false
}
js.mu.Unlock()
// Check if this is for us..
if isMember {
js.processClusterUpdateStream(acc, osa, sa)
} else if mset, _ := acc.lookupStream(sa.Config.Name); mset != nil {
// We have one here even though we are not a member. This can happen on re-assignment.
s.Debugf("JetStream removing stream '%s > %s' from this server, re-assigned", sa.Client.serviceAccount(), sa.Config.Name)
if node := mset.raftNode(); node != nil {
node.ProposeRemovePeer(ourID)
}
mset.stop(true, false)
}
}
// processClusterUpdateStream is called when we have a stream assignment that
// has been updated for an existing assignment.
func (js *jetStream) processClusterUpdateStream(acc *Account, osa, sa *streamAssignment) {
if sa == nil {
return
}
js.mu.Lock()
s, rg := js.srv, sa.Group
client, subject, reply := sa.Client, sa.Subject, sa.Reply
alreadyRunning := rg.node != nil
hasResponded := sa.responded
sa.responded = true
js.mu.Unlock()
mset, err := acc.lookupStream(sa.Config.Name)
if err == nil && mset != nil {
if !alreadyRunning {
s.startGoRoutine(func() { js.monitorStream(mset, sa) })
}
mset.setStreamAssignment(sa)
if err = mset.update(sa.Config); err != nil {
s.Warnf("JetStream cluster error updating stream %q for account %q: %v", sa.Config.Name, acc.Name, err)
mset.setStreamAssignment(osa)
}
}
if err != nil {
js.mu.Lock()
sa.err = err
result := &streamAssignmentResult{
Account: sa.Client.serviceAccount(),
Stream: sa.Config.Name,
Response: &JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}},
Update: true,
}
result.Response.Error = NewJSStreamGeneralError(err, Unless(err))
js.mu.Unlock()
// Send response to the metadata leader. They will forward to the user as needed.
s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, result)
return
}
mset.mu.RLock()
isLeader := mset.isLeader()
mset.mu.RUnlock()
// Check for missing syncSubject bug.
if isLeader && osa != nil && osa.Sync == _EMPTY_ {
if node := mset.raftNode(); node != nil {
node.StepDown()
}
return
}
if !isLeader || hasResponded {
return
}
// Send our response.
var resp = JSApiStreamUpdateResponse{ApiResponse: ApiResponse{Type: JSApiStreamUpdateResponseType}}
resp.StreamInfo = &StreamInfo{
Created: mset.createdTime(),
State: mset.state(),
Config: mset.config(),
Cluster: js.clusterInfo(mset.raftGroup()),
Mirror: mset.mirrorInfo(),
Sources: mset.sourcesInfo(),
}
s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
}
// processClusterCreateStream is called when we have a stream assignment that
// has been committed and this server is a member of the peer group.
func (js *jetStream) processClusterCreateStream(acc *Account, sa *streamAssignment) {
if sa == nil {
return
}
js.mu.RLock()
s, rg := js.srv, sa.Group
alreadyRunning := rg.node != nil
storage := sa.Config.Storage
js.mu.RUnlock()
// Process the raft group and make sure it's running if needed.
err := js.createRaftGroup(rg, storage)
// If we are restoring, create the stream if we are R>1 and not the preferred who handles the
// receipt of the snapshot itself.
shouldCreate := true
if sa.Restore != nil {
if len(rg.Peers) == 1 || rg.node != nil && rg.node.ID() == rg.Preferred {
shouldCreate = false
} else {
sa.Restore = nil
}
}
// Our stream.
var mset *stream
// Process here if not restoring or not the leader.
if shouldCreate && err == nil {
// Go ahead and create or update the stream.
mset, err = acc.lookupStream(sa.Config.Name)
if err == nil && mset != nil {
osa := mset.streamAssignment()
mset.setStreamAssignment(sa)
if err = mset.update(sa.Config); err != nil {
s.Warnf("JetStream cluster error updating stream %q for account %q: %v", sa.Config.Name, acc.Name, err)
mset.setStreamAssignment(osa)
}
} else if err == NewJSStreamNotFoundError() {
// Add in the stream here.
mset, err = acc.addStreamWithAssignment(sa.Config, nil, sa)
}
if mset != nil {
mset.setCreatedTime(sa.Created)
}
}
// This is an error condition.
if err != nil {
s.Warnf("Stream create failed for '%s > %s': %v", sa.Client.serviceAccount(), sa.Config.Name, err)
js.mu.Lock()
sa.err = err
hasResponded := sa.responded
// If out of space do nothing for now.
if isOutOfSpaceErr(err) {
hasResponded = true
}
if rg.node != nil {
rg.node.Delete()
}
var result *streamAssignmentResult
if !hasResponded {
result = &streamAssignmentResult{
Account: sa.Client.serviceAccount(),
Stream: sa.Config.Name,
Response: &JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}},
}
result.Response.Error = NewJSStreamCreateError(err, Unless(err))
}
js.mu.Unlock()
// Send response to the metadata leader. They will forward to the user as needed.
if result != nil {
s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, result)
}
return
}
// Start our monitoring routine.
if rg.node != nil {
if !alreadyRunning {
s.startGoRoutine(func() { js.monitorStream(mset, sa) })
}
} else {
// Single replica stream, process manually here.
// If we are restoring, process that first.
if sa.Restore != nil {
// We are restoring a stream here.
restoreDoneCh := s.processStreamRestore(sa.Client, acc, sa.Config, _EMPTY_, sa.Reply, _EMPTY_)
s.startGoRoutine(func() {
defer s.grWG.Done()
select {
case err := <-restoreDoneCh:
if err == nil {
mset, err = acc.lookupStream(sa.Config.Name)
if mset != nil {
mset.setStreamAssignment(sa)
mset.setCreatedTime(sa.Created)
}
}
if err != nil {
if mset != nil {
mset.delete()
}
js.mu.Lock()
sa.err = err
result := &streamAssignmentResult{
Account: sa.Client.serviceAccount(),
Stream: sa.Config.Name,
Restore: &JSApiStreamRestoreResponse{ApiResponse: ApiResponse{Type: JSApiStreamRestoreResponseType}},
}
result.Restore.Error = NewJSStreamRestoreError(err, Unless(err))
js.mu.Unlock()
// Send response to the metadata leader. They will forward to the user as needed.
b, _ := json.Marshal(result) // Avoids auto-processing and doing fancy json with newlines.
s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, b)
return
}
js.processStreamLeaderChange(mset, true)
// Check to see if we have restored consumers here.
// These are not currently assigned so we will need to do so here.
if consumers := mset.getPublicConsumers(); len(consumers) > 0 {
js.mu.RLock()
cc := js.cluster
js.mu.RUnlock()
for _, o := range consumers {
rg := cc.createGroupForConsumer(sa)
name, cfg := o.String(), o.config()
// Place our initial state here as well for assignment distribution.
ca := &consumerAssignment{
Group: rg,
Stream: sa.Config.Name,
Name: name,
Config: &cfg,
Client: sa.Client,
Created: o.createdTime(),
}
addEntry := encodeAddConsumerAssignment(ca)
cc.meta.ForwardProposal(addEntry)
// Check to make sure we see the assignment.
go func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for range ticker.C {
js.mu.RLock()
ca, meta := js.consumerAssignment(ca.Client.serviceAccount(), sa.Config.Name, name), cc.meta
js.mu.RUnlock()
if ca == nil {
s.Warnf("Consumer assignment has not been assigned, retrying")
if meta != nil {
meta.ForwardProposal(addEntry)
} else {
return
}
} else {
return
}
}
}()
}
}
case <-s.quitCh:
return
}
})
} else {
js.processStreamLeaderChange(mset, true)
}
}
}
// processStreamRemoval is called when followers have replicated an assignment.
func (js *jetStream) processStreamRemoval(sa *streamAssignment) {
js.mu.Lock()
s, cc := js.srv, js.cluster
if s == nil || cc == nil || cc.meta == nil {
// TODO(dlc) - debug at least
js.mu.Unlock()
return
}
stream := sa.Config.Name
isMember := sa.Group.isMember(cc.meta.ID())
wasLeader := cc.isStreamLeader(sa.Client.serviceAccount(), stream)
// Check if we already have this assigned.
accStreams := cc.streams[sa.Client.serviceAccount()]
needDelete := accStreams != nil && accStreams[stream] != nil
if needDelete {
delete(accStreams, stream)
if len(accStreams) == 0 {
delete(cc.streams, sa.Client.serviceAccount())
}
}
js.mu.Unlock()
if needDelete {
js.processClusterDeleteStream(sa, isMember, wasLeader)
}
}
func (js *jetStream) processClusterDeleteStream(sa *streamAssignment, isMember, wasLeader bool) {
if sa == nil {
return
}
js.mu.RLock()
s := js.srv
hadLeader := sa.Group.node == nil || sa.Group.node.GroupLeader() != noLeader
js.mu.RUnlock()
acc, err := s.LookupAccount(sa.Client.serviceAccount())
if err != nil {
s.Debugf("JetStream cluster failed to lookup account %q: %v", sa.Client.serviceAccount(), err)
return
}
var resp = JSApiStreamDeleteResponse{ApiResponse: ApiResponse{Type: JSApiStreamDeleteResponseType}}
// Go ahead and delete the stream.
mset, err := acc.lookupStream(sa.Config.Name)
if err != nil {
resp.Error = NewJSStreamNotFoundError(Unless(err))
} else if mset != nil {
err = mset.stop(true, wasLeader)
}
if sa.Group.node != nil {
sa.Group.node.Delete()
}
if !isMember || !wasLeader && hadLeader {
return
}
if err != nil {
if resp.Error == nil {
resp.Error = NewJSStreamGeneralError(err, Unless(err))
}
s.sendAPIErrResponse(sa.Client, acc, sa.Subject, sa.Reply, _EMPTY_, s.jsonResponse(resp))
} else {
resp.Success = true
s.sendAPIResponse(sa.Client, acc, sa.Subject, sa.Reply, _EMPTY_, s.jsonResponse(resp))
}
}
// processConsumerAssignment is called when followers have replicated an assignment for a consumer.
func (js *jetStream) processConsumerAssignment(ca *consumerAssignment) {
js.mu.RLock()
s, cc := js.srv, js.cluster
accName, stream, consumer := ca.Client.serviceAccount(), ca.Stream, ca.Name
noMeta := cc == nil || cc.meta == nil
var ourID string
if !noMeta {
ourID = cc.meta.ID()
}
var isMember bool
if ca.Group != nil && ourID != _EMPTY_ {
isMember = ca.Group.isMember(ourID)
}
js.mu.RUnlock()
if s == nil || noMeta {
return
}
if _, err := s.LookupAccount(accName); err != nil {
ll := fmt.Sprintf("Account [%s] lookup for consumer create failed: %v", accName, err)
if isMember {
// If we can not lookup the account and we are a member, send this result back to the metacontroller leader.
result := &consumerAssignmentResult{
Account: accName,
Stream: stream,
Consumer: consumer,
Response: &JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}},
}
result.Response.Error = NewJSNoAccountError()
s.sendInternalMsgLocked(consumerAssignmentSubj, _EMPTY_, nil, result)
s.Warnf(ll)
} else {
s.Debugf(ll)
}
return
}
sa := js.streamAssignment(accName, stream)
if sa == nil {
s.Debugf("Consumer create failed, could not locate stream '%s > %s'", accName, stream)
return
}
// Check if we have an existing consumer assignment.
js.mu.Lock()
if sa.consumers == nil {
sa.consumers = make(map[string]*consumerAssignment)
} else if oca := sa.consumers[ca.Name]; oca != nil && !oca.pending {
// Copy over private existing state from former CA.
ca.Group.node = oca.Group.node
ca.responded = oca.responded
ca.err = oca.err
}
// Capture the optional state. We will pass it along if we are a member to apply.
// This is only applicable when restoring a stream with consumers.
state := ca.State
ca.State = nil
// Place into our internal map under the stream assignment.
// Ok to replace an existing one, we check on process call below.
sa.consumers[ca.Name] = ca
js.mu.Unlock()
// Check if this is for us..
if isMember {
js.processClusterCreateConsumer(ca, state)
} else {
// Check if we have a raft node running, meaning we are no longer part of the group but were.
js.mu.Lock()
if node := ca.Group.node; node != nil {
node.ProposeRemovePeer(ourID)
}
ca.Group.node = nil
ca.err = nil
js.mu.Unlock()
}
}
func (js *jetStream) processConsumerRemoval(ca *consumerAssignment) {
js.mu.Lock()
s, cc := js.srv, js.cluster
if s == nil || cc == nil || cc.meta == nil {
// TODO(dlc) - debug at least
js.mu.Unlock()
return
}
isMember := ca.Group.isMember(cc.meta.ID())
wasLeader := cc.isConsumerLeader(ca.Client.serviceAccount(), ca.Stream, ca.Name)
// Delete from our state.
var needDelete bool
if accStreams := cc.streams[ca.Client.serviceAccount()]; accStreams != nil {
if sa := accStreams[ca.Stream]; sa != nil && sa.consumers != nil && sa.consumers[ca.Name] != nil {
needDelete = true
delete(sa.consumers, ca.Name)
}
}
js.mu.Unlock()
if needDelete {
js.processClusterDeleteConsumer(ca, isMember, wasLeader)
}
}
type consumerAssignmentResult struct {
Account string `json:"account"`
Stream string `json:"stream"`
Consumer string `json:"consumer"`
Response *JSApiConsumerCreateResponse `json:"response,omitempty"`
}
// processClusterCreateConsumer is when we are a member of the group and need to create the consumer.
func (js *jetStream) processClusterCreateConsumer(ca *consumerAssignment, state *ConsumerState) {
if ca == nil {
return
}
js.mu.RLock()
s := js.srv
acc, err := s.LookupAccount(ca.Client.serviceAccount())
if err != nil {
s.Warnf("JetStream cluster failed to lookup account %q: %v", ca.Client.serviceAccount(), err)
js.mu.RUnlock()
return
}
rg := ca.Group
alreadyRunning := rg.node != nil
js.mu.RUnlock()
// Go ahead and create or update the consumer.
mset, err := acc.lookupStream(ca.Stream)
if err != nil {
js.mu.Lock()
s.Debugf("Consumer create failed, could not locate stream '%s > %s'", ca.Client.serviceAccount(), ca.Stream)
ca.err = NewJSStreamNotFoundError()
result := &consumerAssignmentResult{
Account: ca.Client.serviceAccount(),
Stream: ca.Stream,
Consumer: ca.Name,
Response: &JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}},
}
result.Response.Error = NewJSStreamNotFoundError()
s.sendInternalMsgLocked(consumerAssignmentSubj, _EMPTY_, nil, result)
js.mu.Unlock()
return
}
// Process the raft group and make sure its running if needed.
js.createRaftGroup(rg, mset.config().Storage)
// Check if we already have this consumer running.
o := mset.lookupConsumer(ca.Name)
if o != nil {
if o.isDurable() && o.isPushMode() {
ocfg := o.config()
if ocfg == *ca.Config || (configsEqualSansDelivery(ocfg, *ca.Config) && o.hasNoLocalInterest()) {
o.updateDeliverSubject(ca.Config.DeliverSubject)
} else {
// This is essentially and update that has failed.
js.mu.Lock()
result := &consumerAssignmentResult{
Account: ca.Client.serviceAccount(),
Stream: ca.Stream,
Consumer: ca.Name,
Response: &JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}},
}
result.Response.Error = NewJSConsumerNameExistError()
s.sendInternalMsgLocked(consumerAssignmentSubj, _EMPTY_, nil, result)
js.mu.Unlock()
return
}
}
o.setConsumerAssignment(ca)
s.Debugf("JetStream cluster, consumer was already running")
}
// Add in the consumer if needed.
if o == nil {
o, err = mset.addConsumerWithAssignment(ca.Config, ca.Name, ca)
}
// If we have an initial state set apply that now.
if state != nil && o != nil {
err = o.setStoreState(state)
}
if err != nil {
if IsNatsErr(err, JSConsumerStoreFailedErrF) {
s.Warnf("Consumer create failed for '%s > %s > %s': %v", ca.Client.serviceAccount(), ca.Stream, ca.Name, err)
}
js.mu.Lock()
ca.err = err
hasResponded := ca.responded
// If out of space do nothing for now.
if isOutOfSpaceErr(err) {
hasResponded = true
}
if rg.node != nil {
rg.node.Delete()
}
var result *consumerAssignmentResult
if !hasResponded {
result = &consumerAssignmentResult{
Account: ca.Client.serviceAccount(),
Stream: ca.Stream,
Consumer: ca.Name,
Response: &JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}},
}
result.Response.Error = NewJSConsumerCreateError(err, Unless(err))
} else if err == errNoInterest {
// This is a stranded ephemeral, let's clean this one up.
subject := fmt.Sprintf(JSApiConsumerDeleteT, ca.Stream, ca.Name)
mset.outq.send(&jsPubMsg{subject, _EMPTY_, _EMPTY_, nil, nil, nil, 0, nil})
}
js.mu.Unlock()
if result != nil {
// Send response to the metadata leader. They will forward to the user as needed.
b, _ := json.Marshal(result) // Avoids auto-processing and doing fancy json with newlines.
s.sendInternalMsgLocked(consumerAssignmentSubj, _EMPTY_, nil, b)
}
} else {
o.setCreatedTime(ca.Created)
// Start our monitoring routine.
if rg.node != nil {
if !alreadyRunning {
s.startGoRoutine(func() { js.monitorConsumer(o, ca) })
}
} else {
// Single replica consumer, process manually here.
js.processConsumerLeaderChange(o, true)
}
}
}
func (js *jetStream) processClusterDeleteConsumer(ca *consumerAssignment, isMember, wasLeader bool) {
if ca == nil {
return
}
js.mu.RLock()
s := js.srv
js.mu.RUnlock()
acc, err := s.LookupAccount(ca.Client.serviceAccount())
if err != nil {
s.Warnf("JetStream cluster failed to lookup account %q: %v", ca.Client.serviceAccount(), err)
return
}
var resp = JSApiConsumerDeleteResponse{ApiResponse: ApiResponse{Type: JSApiConsumerDeleteResponseType}}
// Go ahead and delete the consumer.
mset, err := acc.lookupStream(ca.Stream)
if err != nil {
resp.Error = NewJSStreamNotFoundError(Unless(err))
} else if mset != nil {
if o := mset.lookupConsumer(ca.Name); o != nil {
err = o.stopWithFlags(true, false, true, wasLeader)
} else {
resp.Error = NewJSConsumerNotFoundError()
}
}
if ca.Group.node != nil {
ca.Group.node.Delete()
}
if !wasLeader || ca.Reply == _EMPTY_ {
return
}
if err != nil {
if resp.Error == nil {
resp.Error = NewJSStreamNotFoundError(Unless(err))
}
s.sendAPIErrResponse(ca.Client, acc, ca.Subject, ca.Reply, _EMPTY_, s.jsonResponse(resp))
} else {
resp.Success = true
s.sendAPIResponse(ca.Client, acc, ca.Subject, ca.Reply, _EMPTY_, s.jsonResponse(resp))
}
}
// Returns the consumer assignment, or nil if not present.
// Lock should be held.
func (js *jetStream) consumerAssignment(account, stream, consumer string) *consumerAssignment {
if sa := js.streamAssignment(account, stream); sa != nil {
return sa.consumers[consumer]
}
return nil
}
// consumerAssigned informs us if this server has this consumer assigned.
func (jsa *jsAccount) consumerAssigned(stream, consumer string) bool {
jsa.mu.RLock()
js, acc := jsa.js, jsa.account
jsa.mu.RUnlock()
if js == nil {
return false
}
js.mu.RLock()
defer js.mu.RUnlock()
return js.cluster.isConsumerAssigned(acc, stream, consumer)
}
// Read lock should be held.
func (cc *jetStreamCluster) isConsumerAssigned(a *Account, stream, consumer string) bool {
// Non-clustered mode always return true.
if cc == nil {
return true
}
var sa *streamAssignment
accStreams := cc.streams[a.Name]
if accStreams != nil {
sa = accStreams[stream]
}
if sa == nil {
// TODO(dlc) - This should not happen.
return false
}
ca := sa.consumers[consumer]
if ca == nil {
return false
}
rg := ca.Group
// Check if we are the leader of this raftGroup assigned to the stream.
ourID := cc.meta.ID()
for _, peer := range rg.Peers {
if peer == ourID {
return true
}
}
return false
}
func (o *consumer) raftGroup() *raftGroup {
if o == nil {
return nil
}
o.mu.RLock()
defer o.mu.RUnlock()
if o.ca == nil {
return nil
}
return o.ca.Group
}
func (o *consumer) raftNode() RaftNode {
if o == nil {
return nil
}
o.mu.RLock()
defer o.mu.RUnlock()
return o.node
}
func (js *jetStream) monitorConsumer(o *consumer, ca *consumerAssignment) {
s, n := js.server(), o.raftNode()
defer s.grWG.Done()
if n == nil {
s.Warnf("No RAFT group for consumer")
return
}
qch, lch, ach := n.QuitC(), n.LeadChangeC(), n.ApplyC()
s.Debugf("Starting consumer monitor for '%s > %s > %s", o.acc.Name, ca.Stream, ca.Name)
defer s.Debugf("Exiting consumer monitor for '%s > %s > %s'", o.acc.Name, ca.Stream, ca.Name)
const (
compactInterval = 2 * time.Minute
compactSizeMin = 8 * 1024 * 1024
compactNumMin = 8192
)
t := time.NewTicker(compactInterval)
defer t.Stop()
st := o.store.Type()
var lastSnap []byte
doSnapshot := func() {
// Memory store consumers do not keep state in the store itself.
// Just compact to our applied index.
if st == MemoryStorage {
_, _, applied := n.Progress()
n.Compact(applied)
} else if state, err := o.store.State(); err == nil && state != nil {
// FileStore version.
if snap := encodeConsumerState(state); !bytes.Equal(lastSnap, snap) {
if err := n.InstallSnapshot(snap); err == nil {
lastSnap = snap
}
}
}
}
// Track if we are leader.
var isLeader bool
for {
select {
case <-s.quitCh:
return
case <-qch:
return
case ce := <-ach:
// No special processing needed for when we are caught up on restart.
if ce == nil {
if n.NeedSnapshot() {
doSnapshot()
}
continue
}
if err := js.applyConsumerEntries(o, ce, isLeader); err == nil {
ne, nb := n.Applied(ce.Index)
// If we have at least min entries to compact, go ahead and snapshot/compact.
if nb > 0 && ne >= compactNumMin || nb > compactSizeMin {
doSnapshot()
}
} else {
s.Warnf("Error applying consumer entries to '%s > %s'", ca.Client.serviceAccount(), ca.Name)
}
case isLeader = <-lch:
if !isLeader && n.GroupLeader() != noLeader {
js.setConsumerAssignmentRecovering(ca)
}
js.processConsumerLeaderChange(o, isLeader)
case <-t.C:
doSnapshot()
}
}
}
func (js *jetStream) applyConsumerEntries(o *consumer, ce *CommittedEntry, isLeader bool) error {
for _, e := range ce.Entries {
if e.Type == EntrySnapshot {
// No-op needed?
state, err := decodeConsumerState(e.Data)
if err != nil {
panic(err.Error())
}
o.store.Update(state)
} else if e.Type == EntryRemovePeer {
js.mu.RLock()
var ourID string
if js.cluster != nil && js.cluster.meta != nil {
ourID = js.cluster.meta.ID()
}
js.mu.RUnlock()
if peer := string(e.Data); peer == ourID {
o.stopWithFlags(true, false, false, false)
}
return nil
} else if e.Type == EntryAddPeer {
// Ignore for now.
} else {
buf := e.Data
switch entryOp(buf[0]) {
case updateDeliveredOp:
// These are handled in place in leaders.
if !isLeader {
dseq, sseq, dc, ts, err := decodeDeliveredUpdate(buf[1:])
if err != nil {
panic(err.Error())
}
if err := o.store.UpdateDelivered(dseq, sseq, dc, ts); err != nil {
panic(err.Error())
}
// Update activity.
o.mu.Lock()
o.ldt = time.Now()
o.mu.Unlock()
}
case updateAcksOp:
dseq, sseq, err := decodeAckUpdate(buf[1:])
if err != nil {
panic(err.Error())
}
o.processReplicatedAck(dseq, sseq)
case updateSkipOp:
o.mu.Lock()
if !o.isLeader() {
var le = binary.LittleEndian
o.sseq = le.Uint64(buf[1:])
}
o.mu.Unlock()
default:
panic(fmt.Sprintf("JetStream Cluster Unknown group entry op type! %v", entryOp(buf[0])))
}
}
}
return nil
}
func (o *consumer) processReplicatedAck(dseq, sseq uint64) {
o.mu.Lock()
// Update activity.
o.lat = time.Now()
// Do actual ack update to store.
o.store.UpdateAcks(dseq, sseq)
mset := o.mset
if mset == nil || mset.cfg.Retention == LimitsPolicy {
o.mu.Unlock()
return
}
var sagap uint64
if o.cfg.AckPolicy == AckAll {
if o.isLeader() {
sagap = sseq - o.asflr
} else {
// We are a follower so only have the store state, so read that in.
state, err := o.store.State()
if err != nil {
o.mu.Unlock()
return
}
sagap = sseq - state.AckFloor.Stream
}
}
o.mu.Unlock()
if sagap > 1 {
// FIXME(dlc) - This is very inefficient, will need to fix.
for seq := sseq; seq > sseq-sagap; seq-- {
mset.ackMsg(o, seq)
}
} else {
mset.ackMsg(o, sseq)
}
}
var errBadAckUpdate = errors.New("jetstream cluster bad replicated ack update")
var errBadDeliveredUpdate = errors.New("jetstream cluster bad replicated delivered update")
func decodeAckUpdate(buf []byte) (dseq, sseq uint64, err error) {
var bi, n int
if dseq, n = binary.Uvarint(buf); n < 0 {
return 0, 0, errBadAckUpdate
}
bi += n
if sseq, n = binary.Uvarint(buf[bi:]); n < 0 {
return 0, 0, errBadAckUpdate
}
return dseq, sseq, nil
}
func decodeDeliveredUpdate(buf []byte) (dseq, sseq, dc uint64, ts int64, err error) {
var bi, n int
if dseq, n = binary.Uvarint(buf); n < 0 {
return 0, 0, 0, 0, errBadDeliveredUpdate
}
bi += n
if sseq, n = binary.Uvarint(buf[bi:]); n < 0 {
return 0, 0, 0, 0, errBadDeliveredUpdate
}
bi += n
if dc, n = binary.Uvarint(buf[bi:]); n < 0 {
return 0, 0, 0, 0, errBadDeliveredUpdate
}
bi += n
if ts, n = binary.Varint(buf[bi:]); n < 0 {
return 0, 0, 0, 0, errBadDeliveredUpdate
}
return dseq, sseq, dc, ts, nil
}
func (js *jetStream) processConsumerLeaderChange(o *consumer, isLeader bool) {
ca := o.consumerAssignment()
if ca == nil {
return
}
js.mu.Lock()
s, account, err := js.srv, ca.Client.serviceAccount(), ca.err
client, subject, reply := ca.Client, ca.Subject, ca.Reply
hasResponded := ca.responded
ca.responded = true
js.mu.Unlock()
streamName := o.streamName()
consumerName := o.String()
acc, _ := s.LookupAccount(account)
if acc == nil {
return
}
if isLeader {
s.Noticef("JetStream cluster new consumer leader for '%s > %s > %s'", ca.Client.serviceAccount(), streamName, consumerName)
s.sendConsumerLeaderElectAdvisory(o)
// Check for peer removal and process here if needed.
js.checkPeers(ca.Group)
} else {
// We are stepping down.
// Make sure if we are doing so because we have lost quorum that we send the appropriate advisories.
if node := o.raftNode(); node != nil && !node.Quorum() && time.Since(node.Created()) > 5*time.Second {
s.sendConsumerLostQuorumAdvisory(o)
}
}
// Tell consumer to switch leader status.
o.setLeader(isLeader)
// Synchronize others to our version of state.
if isLeader {
if n := o.raftNode(); n != nil {
if state, err := o.store.State(); err == nil && state != nil {
if snap := encodeConsumerState(state); len(snap) > 0 {
n.SendSnapshot(snap)
}
}
}
}
if !isLeader || hasResponded {
return
}
var resp = JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}}
if err != nil {
resp.Error = NewJSConsumerCreateError(err, Unless(err))
s.sendAPIErrResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
} else {
resp.ConsumerInfo = o.info()
s.sendAPIResponse(client, acc, subject, reply, _EMPTY_, s.jsonResponse(&resp))
if node := o.raftNode(); node != nil {
o.sendCreateAdvisory()
}
}
}
// Determines if we should send lost quorum advisory. We throttle these after first one.
func (o *consumer) shouldSendLostQuorum() bool {
o.mu.Lock()
defer o.mu.Unlock()
if time.Since(o.lqsent) >= lostQuorumAdvInterval {
o.lqsent = time.Now()
return true
}
return false
}
func (s *Server) sendConsumerLostQuorumAdvisory(o *consumer) {
if o == nil {
return
}
node, stream, consumer, acc := o.raftNode(), o.streamName(), o.String(), o.account()
if node == nil {
return
}
if !o.shouldSendLostQuorum() {
return
}
s.Warnf("JetStream cluster consumer '%s > %s > %s' has NO quorum, stalled.", acc.GetName(), stream, consumer)
subj := JSAdvisoryConsumerQuorumLostPre + "." + stream + "." + consumer
adv := &JSConsumerQuorumLostAdvisory{
TypedEvent: TypedEvent{
Type: JSConsumerQuorumLostAdvisoryType,
ID: nuid.Next(),
Time: time.Now().UTC(),
},
Stream: stream,
Consumer: consumer,
Replicas: s.replicas(node),
Domain: s.getOpts().JetStreamDomain,
}
// Send to the user's account if not the system account.
if acc != s.SystemAccount() {
s.publishAdvisory(acc, subj, adv)
}
// Now do system level one. Place account info in adv, and nil account means system.
adv.Account = acc.GetName()
s.publishAdvisory(nil, subj, adv)
}
func (s *Server) sendConsumerLeaderElectAdvisory(o *consumer) {
if o == nil {
return
}
node, stream, consumer, acc := o.raftNode(), o.streamName(), o.String(), o.account()
if node == nil {
return
}
subj := JSAdvisoryConsumerLeaderElectedPre + "." + stream + "." + consumer
adv := &JSConsumerLeaderElectedAdvisory{
TypedEvent: TypedEvent{
Type: JSConsumerLeaderElectedAdvisoryType,
ID: nuid.Next(),
Time: time.Now().UTC(),
},
Stream: stream,
Consumer: consumer,
Leader: s.serverNameForNode(node.GroupLeader()),
Replicas: s.replicas(node),
Domain: s.getOpts().JetStreamDomain,
}
// Send to the user's account if not the system account.
if acc != s.SystemAccount() {
s.publishAdvisory(acc, subj, adv)
}
// Now do system level one. Place account info in adv, and nil account means system.
adv.Account = acc.GetName()
s.publishAdvisory(nil, subj, adv)
}
type streamAssignmentResult struct {
Account string `json:"account"`
Stream string `json:"stream"`
Response *JSApiStreamCreateResponse `json:"create_response,omitempty"`
Restore *JSApiStreamRestoreResponse `json:"restore_response,omitempty"`
Update bool `json:"is_update,omitempty"`
}
// Process error results of stream and consumer assignments.
// Success will be handled by stream leader.
func (js *jetStream) processStreamAssignmentResults(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) {
var result streamAssignmentResult
if err := json.Unmarshal(msg, &result); err != nil {
// TODO(dlc) - log
return
}
acc, _ := js.srv.LookupAccount(result.Account)
if acc == nil {
// TODO(dlc) - log
return
}
js.mu.Lock()
defer js.mu.Unlock()
s, cc := js.srv, js.cluster
// FIXME(dlc) - suppress duplicates?
if sa := js.streamAssignment(result.Account, result.Stream); sa != nil {
var resp string
if result.Response != nil {
resp = s.jsonResponse(result.Response)
} else if result.Restore != nil {
resp = s.jsonResponse(result.Restore)
}
if !sa.responded || result.Update {
sa.responded = true
js.srv.sendAPIErrResponse(sa.Client, acc, sa.Subject, sa.Reply, _EMPTY_, resp)
}
// Here we will remove this assignment, so this needs to only execute when we are sure
// this is what we want to do.
// TODO(dlc) - Could have mixed results, should track per peer.
// Set sa.err while we are deleting so we will not respond to list/names requests.
if !result.Update && time.Since(sa.Created) < 5*time.Second {
sa.err = NewJSClusterNotAssignedError()
cc.meta.Propose(encodeDeleteStreamAssignment(sa))
}
}
}
func (js *jetStream) processConsumerAssignmentResults(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) {
var result consumerAssignmentResult
if err := json.Unmarshal(msg, &result); err != nil {
// TODO(dlc) - log
return
}
acc, _ := js.srv.LookupAccount(result.Account)
if acc == nil {
// TODO(dlc) - log
return
}
js.mu.Lock()
defer js.mu.Unlock()
s, cc := js.srv, js.cluster
if sa := js.streamAssignment(result.Account, result.Stream); sa != nil && sa.consumers != nil {
if ca := sa.consumers[result.Consumer]; ca != nil && !ca.responded {
js.srv.sendAPIErrResponse(ca.Client, acc, ca.Subject, ca.Reply, _EMPTY_, s.jsonResponse(result.Response))
ca.responded = true
// Check if this failed.
// TODO(dlc) - Could have mixed results, should track per peer.
if result.Response.Error != nil {
// So while we are deleting we will not respond to list/names requests.
ca.err = NewJSClusterNotAssignedError()
cc.meta.Propose(encodeDeleteConsumerAssignment(ca))
}
}
}
}
const (
streamAssignmentSubj = "$SYS.JSC.STREAM.ASSIGNMENT.RESULT"
consumerAssignmentSubj = "$SYS.JSC.CONSUMER.ASSIGNMENT.RESULT"
)
// Lock should be held.
func (js *jetStream) startUpdatesSub() {
cc, s, c := js.cluster, js.srv, js.cluster.c
if cc.streamResults == nil {
cc.streamResults, _ = s.systemSubscribe(streamAssignmentSubj, _EMPTY_, false, c, js.processStreamAssignmentResults)
}
if cc.consumerResults == nil {
cc.consumerResults, _ = s.systemSubscribe(consumerAssignmentSubj, _EMPTY_, false, c, js.processConsumerAssignmentResults)
}
if cc.stepdown == nil {
cc.stepdown, _ = s.systemSubscribe(JSApiLeaderStepDown, _EMPTY_, false, c, s.jsLeaderStepDownRequest)
}
if cc.peerRemove == nil {
cc.peerRemove, _ = s.systemSubscribe(JSApiRemoveServer, _EMPTY_, false, c, s.jsLeaderServerRemoveRequest)
}
}
// Lock should be held.
func (js *jetStream) stopUpdatesSub() {
cc := js.cluster
if cc.streamResults != nil {
cc.s.sysUnsubscribe(cc.streamResults)
cc.streamResults = nil
}
if cc.consumerResults != nil {
cc.s.sysUnsubscribe(cc.consumerResults)
cc.consumerResults = nil
}
if cc.stepdown != nil {
cc.s.sysUnsubscribe(cc.stepdown)
cc.stepdown = nil
}
if cc.peerRemove != nil {
cc.s.sysUnsubscribe(cc.peerRemove)
cc.peerRemove = nil
}
}
func (js *jetStream) processLeaderChange(isLeader bool) {
if isLeader {
js.srv.Noticef("JetStream cluster new metadata leader")
}
js.mu.Lock()
defer js.mu.Unlock()
if isLeader {
js.startUpdatesSub()
} else {
js.stopUpdatesSub()
// TODO(dlc) - stepdown.
}
// If we have been signaled to check the streams, this is for a bug that left stream
// assignments with no sync subject after and update and no way to sync/catchup outside of the RAFT layer.
if isLeader && js.cluster.streamsCheck {
cc := js.cluster
for acc, asa := range cc.streams {
for _, sa := range asa {
if sa.Sync == _EMPTY_ {
js.srv.Warnf("Stream assigment corrupt for stream '%s > %s'", acc, sa.Config.Name)
nsa := &streamAssignment{Group: sa.Group, Config: sa.Config, Subject: sa.Subject, Reply: sa.Reply, Client: sa.Client}
nsa.Sync = syncSubjForStream()
cc.meta.Propose(encodeUpdateStreamAssignment(nsa))
}
}
}
// Clear check.
cc.streamsCheck = false
}
}
// Lock should be held.
func (cc *jetStreamCluster) remapStreamAssignment(sa *streamAssignment, removePeer string) bool {
// Need to select a replacement peer
s, now, cluster := cc.s, time.Now(), sa.Client.Cluster
if sa.Config.Placement != nil && sa.Config.Placement.Cluster != _EMPTY_ {
cluster = sa.Config.Placement.Cluster
}
ourID := cc.meta.ID()
for _, p := range cc.meta.Peers() {
// If it is not in our list it's probably shutdown, so don't consider.
if si, ok := s.nodeToInfo.Load(p.ID); !ok || si.(nodeInfo).offline {
continue
}
// Make sure they are active and current and not already part of our group.
current, lastSeen := p.Current, now.Sub(p.Last)
// We do not track activity of ourselves so ignore.
if p.ID == ourID {
lastSeen = 0
}
if !current || lastSeen > lostQuorumInterval || sa.Group.isMember(p.ID) {
continue
}
// Make sure the correct cluster.
if s.clusterNameForNode(p.ID) != cluster {
continue
}
// If we are here we have our candidate replacement, swap out the old one.
for i, peer := range sa.Group.Peers {
if peer == removePeer {
sa.Group.Peers[i] = p.ID
// Don't influence preferred leader.
sa.Group.Preferred = _EMPTY_
return true
}
}
}
// If we are here let's remove the peer at least.
for i, peer := range sa.Group.Peers {
if peer == removePeer {
sa.Group.Peers[i] = sa.Group.Peers[len(sa.Group.Peers)-1]
sa.Group.Peers = sa.Group.Peers[:len(sa.Group.Peers)-1]
break
}
}
return false
}
// selectPeerGroup will select a group of peers to start a raft group.
// TODO(dlc) - For now randomly select. Can be way smarter.
func (cc *jetStreamCluster) selectPeerGroup(r int, cluster string) []string {
var nodes []string
peers := cc.meta.Peers()
s := cc.s
for _, p := range peers {
// If we know its offline or it is not in our list it probably shutdown, so don't consider.
if si, ok := s.nodeToInfo.Load(p.ID); !ok || si.(nodeInfo).offline {
continue
}
if cluster != _EMPTY_ {
if s.clusterNameForNode(p.ID) == cluster {
nodes = append(nodes, p.ID)
}
} else {
nodes = append(nodes, p.ID)
}
}
if len(nodes) < r {
return nil
}
// Don't depend on range to randomize.
rand.Shuffle(len(nodes), func(i, j int) { nodes[i], nodes[j] = nodes[j], nodes[i] })
return nodes[:r]
}
func groupNameForStream(peers []string, storage StorageType) string {
return groupName("S", peers, storage)
}
func groupNameForConsumer(peers []string, storage StorageType) string {
return groupName("C", peers, storage)
}
func groupName(prefix string, peers []string, storage StorageType) string {
var gns string
if len(peers) == 1 {
gns = peers[0]
} else {
gns = string(getHash(nuid.Next()))
}
return fmt.Sprintf("%s-R%d%s-%s", prefix, len(peers), storage.String()[:1], gns)
}
// createGroupForStream will create a group for assignment for the stream.
// Lock should be held.
func (cc *jetStreamCluster) createGroupForStream(ci *ClientInfo, cfg *StreamConfig) *raftGroup {
replicas := cfg.Replicas
if replicas == 0 {
replicas = 1
}
cluster := ci.Cluster
if cfg.Placement != nil && cfg.Placement.Cluster != _EMPTY_ {
cluster = cfg.Placement.Cluster
}
// Need to create a group here.
// TODO(dlc) - Can be way smarter here.
peers := cc.selectPeerGroup(replicas, cluster)
if len(peers) == 0 {
return nil
}
return &raftGroup{Name: groupNameForStream(peers, cfg.Storage), Storage: cfg.Storage, Peers: peers}
}
func (s *Server) jsClusteredStreamRequest(ci *ClientInfo, acc *Account, subject, reply string, rmsg []byte, config *StreamConfig) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
var resp = JSApiStreamCreateResponse{ApiResponse: ApiResponse{Type: JSApiStreamCreateResponseType}}
// Grab our jetstream account info.
acc.mu.RLock()
jsa := acc.js
acc.mu.RUnlock()
if jsa == nil {
resp.Error = NewJSNotEnabledForAccountError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
ccfg, err := checkStreamCfg(config)
if err != nil {
resp.Error = NewJSStreamInvalidConfigError(err, Unless(err))
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
cfg := &ccfg
// Check for stream limits here before proposing. These need to be tracked from meta layer, not jsa.
js.mu.RLock()
asa := cc.streams[acc.Name]
numStreams := len(asa)
js.mu.RUnlock()
jsa.mu.RLock()
exceeded := jsa.limits.MaxStreams > 0 && numStreams >= jsa.limits.MaxStreams
jsa.mu.RUnlock()
if exceeded {
resp.Error = NewJSMaximumStreamsLimitError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Check for stream limits here before proposing.
if err := jsa.checkLimits(cfg); err != nil {
resp.Error = NewJSStreamLimitsError(err, Unless(err))
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Now process the request and proposal.
js.mu.Lock()
defer js.mu.Unlock()
if sa := js.streamAssignment(acc.Name, cfg.Name); sa != nil {
// If they are the same then we will forward on as a stream info request.
// This now matches single server behavior.
if reflect.DeepEqual(sa.Config, cfg) {
isubj := fmt.Sprintf(JSApiStreamInfoT, cfg.Name)
// We want to make sure we send along the client info.
cij, _ := json.Marshal(ci)
hdr := map[string]string{ClientInfoHdr: string(cij)}
// Send this as system account, but include client info header.
s.sendInternalAccountMsgWithReply(nil, isubj, reply, hdr, nil, true)
return
}
resp.Error = NewJSStreamNameExistError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
} else if cfg.Sealed {
resp.Error = NewJSStreamInvalidConfigError(fmt.Errorf("stream configuration for create can not be sealed"))
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Check for subject collisions here.
for _, sa := range asa {
for _, subj := range sa.Config.Subjects {
for _, tsubj := range cfg.Subjects {
if SubjectsCollide(tsubj, subj) {
resp.Error = NewJSStreamSubjectOverlapError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
}
}
}
// Raft group selection and placement.
rg := cc.createGroupForStream(ci, cfg)
if rg == nil {
resp.Error = NewJSInsufficientResourcesError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Pick a preferred leader.
rg.setPreferred()
// Sync subject for post snapshot sync.
sa := &streamAssignment{Group: rg, Sync: syncSubjForStream(), Config: cfg, Subject: subject, Reply: reply, Client: ci, Created: time.Now().UTC()}
cc.meta.Propose(encodeAddStreamAssignment(sa))
}
func (s *Server) jsClusteredStreamUpdateRequest(ci *ClientInfo, acc *Account, subject, reply string, rmsg []byte, cfg *StreamConfig) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
// Now process the request and proposal.
js.mu.Lock()
defer js.mu.Unlock()
var resp = JSApiStreamUpdateResponse{ApiResponse: ApiResponse{Type: JSApiStreamUpdateResponseType}}
osa := js.streamAssignment(acc.Name, cfg.Name)
if osa == nil {
resp.Error = NewJSStreamNotFoundError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
var newCfg *StreamConfig
if jsa := js.accounts[acc.Name]; jsa != nil {
if ncfg, err := jsa.configUpdateCheck(osa.Config, cfg); err != nil {
resp.Error = NewJSStreamUpdateError(err, Unless(err))
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
} else {
newCfg = ncfg
}
} else {
resp.Error = NewJSNotEnabledForAccountError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Check for cluster changes that we want to error on.
if newCfg.Replicas != len(osa.Group.Peers) {
resp.Error = NewJSStreamReplicasNotUpdatableError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
if !reflect.DeepEqual(newCfg.Mirror, osa.Config.Mirror) {
resp.Error = NewJSStreamMirrorNotUpdatableError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Check for subject collisions here.
for _, sa := range cc.streams[acc.Name] {
if sa == osa {
continue
}
for _, subj := range sa.Config.Subjects {
for _, tsubj := range newCfg.Subjects {
if SubjectsCollide(tsubj, subj) {
resp.Error = NewJSStreamSubjectOverlapError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
}
}
}
sa := &streamAssignment{Group: osa.Group, Sync: osa.Sync, Config: newCfg, Subject: subject, Reply: reply, Client: ci}
cc.meta.Propose(encodeUpdateStreamAssignment(sa))
}
func (s *Server) jsClusteredStreamDeleteRequest(ci *ClientInfo, acc *Account, stream, subject, reply string, rmsg []byte) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
defer js.mu.Unlock()
osa := js.streamAssignment(acc.Name, stream)
if osa == nil {
var resp = JSApiStreamDeleteResponse{ApiResponse: ApiResponse{Type: JSApiStreamDeleteResponseType}}
resp.Error = NewJSStreamNotFoundError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Remove any remaining consumers as well.
for _, ca := range osa.consumers {
ca.Reply, ca.State = _EMPTY_, nil
cc.meta.Propose(encodeDeleteConsumerAssignment(ca))
}
sa := &streamAssignment{Group: osa.Group, Config: osa.Config, Subject: subject, Reply: reply, Client: ci}
cc.meta.Propose(encodeDeleteStreamAssignment(sa))
}
// Process a clustered purge request.
func (s *Server) jsClusteredStreamPurgeRequest(
ci *ClientInfo,
acc *Account,
mset *stream,
stream, subject, reply string,
rmsg []byte,
preq *JSApiStreamPurgeRequest,
) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
defer js.mu.Unlock()
sa := js.streamAssignment(acc.Name, stream)
if sa == nil {
resp := JSApiStreamPurgeResponse{ApiResponse: ApiResponse{Type: JSApiStreamPurgeResponseType}}
resp.Error = NewJSStreamNotFoundError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
if n := sa.Group.node; n != nil {
sp := &streamPurge{Stream: stream, LastSeq: mset.state().LastSeq, Subject: subject, Reply: reply, Client: ci, Request: preq}
n.Propose(encodeStreamPurge(sp))
} else if mset != nil {
var resp = JSApiStreamPurgeResponse{ApiResponse: ApiResponse{Type: JSApiStreamPurgeResponseType}}
purged, err := mset.purge(preq)
if err != nil {
resp.Error = NewJSStreamGeneralError(err, Unless(err))
} else {
resp.Purged = purged
resp.Success = true
}
s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
}
}
func (s *Server) jsClusteredStreamRestoreRequest(ci *ClientInfo, acc *Account, req *JSApiStreamRestoreRequest, stream, subject, reply string, rmsg []byte) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
defer js.mu.Unlock()
cfg := &req.Config
resp := JSApiStreamRestoreResponse{ApiResponse: ApiResponse{Type: JSApiStreamRestoreResponseType}}
if sa := js.streamAssignment(ci.serviceAccount(), cfg.Name); sa != nil {
resp.Error = NewJSStreamNameExistError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Raft group selection and placement.
rg := cc.createGroupForStream(ci, cfg)
if rg == nil {
resp.Error = NewJSInsufficientResourcesError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Pick a preferred leader.
rg.setPreferred()
sa := &streamAssignment{Group: rg, Sync: syncSubjForStream(), Config: cfg, Subject: subject, Reply: reply, Client: ci, Created: time.Now().UTC()}
// Now add in our restore state and pre-select a peer to handle the actual receipt of the snapshot.
sa.Restore = &req.State
cc.meta.Propose(encodeAddStreamAssignment(sa))
}
func (s *Server) allPeersOffline(rg *raftGroup) bool {
if rg == nil {
return false
}
// Check to see if this stream has any servers online to respond.
for _, peer := range rg.Peers {
if si, ok := s.nodeToInfo.Load(peer); ok && si != nil {
if !si.(nodeInfo).offline {
return false
}
}
}
return true
}
// This will do a scatter and gather operation for all streams for this account. This is only called from metadata leader.
// This will be running in a separate Go routine.
func (s *Server) jsClusteredStreamListRequest(acc *Account, ci *ClientInfo, offset int, subject, reply string, rmsg []byte) {
defer s.grWG.Done()
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
var streams []*streamAssignment
for _, sa := range cc.streams[acc.Name] {
streams = append(streams, sa)
}
// Needs to be sorted for offsets etc.
if len(streams) > 1 {
sort.Slice(streams, func(i, j int) bool {
return strings.Compare(streams[i].Config.Name, streams[j].Config.Name) < 0
})
}
scnt := len(streams)
if offset > scnt {
offset = scnt
}
if offset > 0 {
streams = streams[offset:]
}
if len(streams) > JSApiListLimit {
streams = streams[:JSApiListLimit]
}
var resp = JSApiStreamListResponse{
ApiResponse: ApiResponse{Type: JSApiStreamListResponseType},
Streams: make([]*StreamInfo, 0, len(streams)),
}
if len(streams) == 0 {
js.mu.Unlock()
resp.Limit = JSApiListLimit
resp.Offset = offset
s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
return
}
// Create an inbox for our responses and send out our requests.
s.mu.Lock()
inbox := s.newRespInbox()
rc := make(chan *StreamInfo, len(streams))
// Store our handler.
s.sys.replies[inbox] = func(sub *subscription, _ *client, _ *Account, subject, _ string, msg []byte) {
var si StreamInfo
if err := json.Unmarshal(msg, &si); err != nil {
s.Warnf("Error unmarshaling clustered stream info response:%v", err)
return
}
select {
case rc <- &si:
default:
s.Warnf("Failed placing remote stream info result on internal channel")
}
}
s.mu.Unlock()
// Cleanup after.
defer func() {
s.mu.Lock()
if s.sys != nil && s.sys.replies != nil {
delete(s.sys.replies, inbox)
}
s.mu.Unlock()
}()
// Send out our requests here.
for _, sa := range streams {
if s.allPeersOffline(sa.Group) {
// Place offline onto our results by hand here.
si := &StreamInfo{Config: *sa.Config, Created: sa.Created, Cluster: js.offlineClusterInfo(sa.Group)}
resp.Streams = append(resp.Streams, si)
} else {
isubj := fmt.Sprintf(clusterStreamInfoT, sa.Client.serviceAccount(), sa.Config.Name)
s.sendInternalMsgLocked(isubj, inbox, nil, nil)
}
}
// Don't hold lock.
js.mu.Unlock()
const timeout = 5 * time.Second
notActive := time.NewTimer(timeout)
defer notActive.Stop()
LOOP:
for {
select {
case <-s.quitCh:
return
case <-notActive.C:
s.Warnf("Did not receive all stream info results for %q", acc)
resp.Error = NewJSClusterIncompleteError()
break LOOP
case si := <-rc:
resp.Streams = append(resp.Streams, si)
// Check to see if we are done.
if len(resp.Streams) == len(streams) {
break LOOP
}
}
}
// Needs to be sorted as well.
if len(resp.Streams) > 1 {
sort.Slice(resp.Streams, func(i, j int) bool {
return strings.Compare(resp.Streams[i].Config.Name, resp.Streams[j].Config.Name) < 0
})
}
resp.Total = len(resp.Streams)
resp.Limit = JSApiListLimit
resp.Offset = offset
s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
}
// This will do a scatter and gather operation for all consumers for this stream and account.
// This will be running in a separate Go routine.
func (s *Server) jsClusteredConsumerListRequest(acc *Account, ci *ClientInfo, offset int, stream, subject, reply string, rmsg []byte) {
defer s.grWG.Done()
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
var consumers []*consumerAssignment
if sas := cc.streams[acc.Name]; sas != nil {
if sa := sas[stream]; sa != nil {
// Copy over since we need to sort etc.
for _, ca := range sa.consumers {
consumers = append(consumers, ca)
}
}
}
// Needs to be sorted.
if len(consumers) > 1 {
sort.Slice(consumers, func(i, j int) bool {
return strings.Compare(consumers[i].Name, consumers[j].Name) < 0
})
}
ocnt := len(consumers)
if offset > ocnt {
offset = ocnt
}
if offset > 0 {
consumers = consumers[offset:]
}
if len(consumers) > JSApiListLimit {
consumers = consumers[:JSApiListLimit]
}
// Send out our requests here.
var resp = JSApiConsumerListResponse{
ApiResponse: ApiResponse{Type: JSApiConsumerListResponseType},
Consumers: []*ConsumerInfo{},
}
if len(consumers) == 0 {
js.mu.Unlock()
resp.Limit = JSApiListLimit
resp.Offset = offset
s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
return
}
// Create an inbox for our responses and send out requests.
s.mu.Lock()
inbox := s.newRespInbox()
rc := make(chan *ConsumerInfo, len(consumers))
// Store our handler.
s.sys.replies[inbox] = func(sub *subscription, _ *client, _ *Account, subject, _ string, msg []byte) {
var ci ConsumerInfo
if err := json.Unmarshal(msg, &ci); err != nil {
s.Warnf("Error unmarshaling clustered consumer info response:%v", err)
return
}
select {
case rc <- &ci:
default:
s.Warnf("Failed placing consumer info result on internal chan")
}
}
s.mu.Unlock()
// Cleanup after.
defer func() {
s.mu.Lock()
if s.sys != nil && s.sys.replies != nil {
delete(s.sys.replies, inbox)
}
s.mu.Unlock()
}()
for _, ca := range consumers {
if s.allPeersOffline(ca.Group) {
// Place offline onto our results by hand here.
ci := &ConsumerInfo{Config: ca.Config, Created: ca.Created, Cluster: js.offlineClusterInfo(ca.Group)}
resp.Consumers = append(resp.Consumers, ci)
} else {
isubj := fmt.Sprintf(clusterConsumerInfoT, ca.Client.serviceAccount(), stream, ca.Name)
s.sendInternalMsgLocked(isubj, inbox, nil, nil)
}
}
js.mu.Unlock()
const timeout = 2 * time.Second
notActive := time.NewTimer(timeout)
defer notActive.Stop()
LOOP:
for {
select {
case <-s.quitCh:
return
case <-notActive.C:
s.Warnf("Did not receive all stream info results for %q", acc)
break LOOP
case ci := <-rc:
resp.Consumers = append(resp.Consumers, ci)
// Check to see if we are done.
if len(resp.Consumers) == len(consumers) {
break LOOP
}
}
}
// Needs to be sorted as well.
if len(resp.Consumers) > 1 {
sort.Slice(resp.Consumers, func(i, j int) bool {
return strings.Compare(resp.Consumers[i].Name, resp.Consumers[j].Name) < 0
})
}
resp.Total = len(resp.Consumers)
resp.Limit = JSApiListLimit
resp.Offset = offset
s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
}
func encodeStreamPurge(sp *streamPurge) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(purgeStreamOp))
json.NewEncoder(&bb).Encode(sp)
return bb.Bytes()
}
func decodeStreamPurge(buf []byte) (*streamPurge, error) {
var sp streamPurge
err := json.Unmarshal(buf, &sp)
return &sp, err
}
func (s *Server) jsClusteredConsumerDeleteRequest(ci *ClientInfo, acc *Account, stream, consumer, subject, reply string, rmsg []byte) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
defer js.mu.Unlock()
var resp = JSApiConsumerDeleteResponse{ApiResponse: ApiResponse{Type: JSApiConsumerDeleteResponseType}}
sa := js.streamAssignment(acc.Name, stream)
if sa == nil {
resp.Error = NewJSStreamNotFoundError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
if sa.consumers == nil {
resp.Error = NewJSConsumerNotFoundError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
oca := sa.consumers[consumer]
if oca == nil {
resp.Error = NewJSConsumerNotFoundError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
oca.deleted = true
ca := &consumerAssignment{Group: oca.Group, Stream: stream, Name: consumer, Config: oca.Config, Subject: subject, Reply: reply, Client: ci}
cc.meta.Propose(encodeDeleteConsumerAssignment(ca))
}
func encodeMsgDelete(md *streamMsgDelete) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(deleteMsgOp))
json.NewEncoder(&bb).Encode(md)
return bb.Bytes()
}
func decodeMsgDelete(buf []byte) (*streamMsgDelete, error) {
var md streamMsgDelete
err := json.Unmarshal(buf, &md)
return &md, err
}
func (s *Server) jsClusteredMsgDeleteRequest(ci *ClientInfo, acc *Account, mset *stream, stream, subject, reply string, req *JSApiMsgDeleteRequest, rmsg []byte) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
defer js.mu.Unlock()
sa := js.streamAssignment(acc.Name, stream)
if sa == nil {
s.Debugf("Message delete failed, could not locate stream '%s > %s'", acc.Name, stream)
return
}
// Check for single replica items.
if n := sa.Group.node; n != nil {
md := streamMsgDelete{Seq: req.Seq, NoErase: req.NoErase, Stream: stream, Subject: subject, Reply: reply, Client: ci}
n.Propose(encodeMsgDelete(&md))
} else if mset != nil {
var err error
var removed bool
if req.NoErase {
removed, err = mset.removeMsg(req.Seq)
} else {
removed, err = mset.eraseMsg(req.Seq)
}
var resp = JSApiMsgDeleteResponse{ApiResponse: ApiResponse{Type: JSApiMsgDeleteResponseType}}
if err != nil {
resp.Error = NewJSStreamMsgDeleteFailedError(err, Unless(err))
} else if !removed {
resp.Error = NewJSSequenceNotFoundError(req.Seq)
} else {
resp.Success = true
}
s.sendAPIResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(resp))
}
}
func encodeAddStreamAssignment(sa *streamAssignment) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(assignStreamOp))
json.NewEncoder(&bb).Encode(sa)
return bb.Bytes()
}
func encodeUpdateStreamAssignment(sa *streamAssignment) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(updateStreamOp))
json.NewEncoder(&bb).Encode(sa)
return bb.Bytes()
}
func encodeDeleteStreamAssignment(sa *streamAssignment) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(removeStreamOp))
json.NewEncoder(&bb).Encode(sa)
return bb.Bytes()
}
func decodeStreamAssignment(buf []byte) (*streamAssignment, error) {
var sa streamAssignment
err := json.Unmarshal(buf, &sa)
return &sa, err
}
// createGroupForConsumer will create a new group with same peer set as the stream.
func (cc *jetStreamCluster) createGroupForConsumer(sa *streamAssignment) *raftGroup {
peers := sa.Group.Peers
if len(peers) == 0 {
return nil
}
return &raftGroup{Name: groupNameForConsumer(peers, sa.Config.Storage), Storage: sa.Config.Storage, Peers: peers}
}
// jsClusteredConsumerRequest is first point of entry to create a consumer with R > 1.
func (s *Server) jsClusteredConsumerRequest(ci *ClientInfo, acc *Account, subject, reply string, rmsg []byte, stream string, cfg *ConsumerConfig) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
return
}
js.mu.Lock()
defer js.mu.Unlock()
var resp = JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}}
// Lookup the stream assignment.
sa := js.streamAssignment(acc.Name, stream)
if sa == nil {
resp.Error = NewJSStreamNotFoundError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Check for max consumers here to short circuit if possible.
if maxc := sa.Config.MaxConsumers; maxc > 0 {
// Don't count DIRECTS.
total := 0
for _, ca := range sa.consumers {
if ca.Config != nil && !ca.Config.Direct {
total++
}
}
if total >= maxc {
resp.Error = NewJSMaximumConsumersLimitError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
}
// Also short circuit if DeliverLastPerSubject is set with no FilterSubject.
if cfg.DeliverPolicy == DeliverLastPerSubject {
badConfig := cfg.FilterSubject == _EMPTY_
if !badConfig {
subjects := sa.Config.Subjects
if len(subjects) == 1 && subjects[0] == cfg.FilterSubject && subjectIsLiteral(subjects[0]) {
badConfig = true
}
}
if badConfig {
resp.Error = NewJSConsumerInvalidPolicyError(fmt.Errorf("consumer delivery policy is deliver last per subject, but FilterSubject is not set"))
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
}
// Setup proper default for ack wait if we are in explicit ack mode.
if cfg.AckWait == 0 && (cfg.AckPolicy == AckExplicit || cfg.AckPolicy == AckAll) {
cfg.AckWait = JsAckWaitDefault
}
// Setup default of -1, meaning no limit for MaxDeliver.
if cfg.MaxDeliver == 0 {
cfg.MaxDeliver = -1
}
// Set proper default for max ack pending if we are ack explicit and none has been set.
if cfg.AckPolicy == AckExplicit && cfg.MaxAckPending == 0 {
cfg.MaxAckPending = JsDefaultMaxAckPending
}
rg := cc.createGroupForConsumer(sa)
if rg == nil {
resp.Error = NewJSInsufficientResourcesError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
// Pick a preferred leader.
rg.setPreferred()
// We need to set the ephemeral here before replicating.
var oname string
if !isDurableConsumer(cfg) {
// We chose to have ephemerals be R=1 unless stream is interest or workqueue.
if sa.Config.Retention == LimitsPolicy {
rg.Peers = []string{rg.Preferred}
rg.Name = groupNameForConsumer(rg.Peers, rg.Storage)
}
// Make sure name is unique.
for {
oname = createConsumerName()
if sa.consumers != nil {
if sa.consumers[oname] != nil {
continue
}
}
break
}
} else {
oname = cfg.Durable
if ca := sa.consumers[oname]; ca != nil && !ca.deleted {
isPull := ca.Config.DeliverSubject == _EMPTY_
// This can be ok if delivery subject update.
shouldErr := isPull || ca.pending || (!reflect.DeepEqual(cfg, ca.Config) && !configsEqualSansDelivery(*cfg, *ca.Config))
if !shouldErr {
rr := acc.sl.Match(ca.Config.DeliverSubject)
shouldErr = len(rr.psubs)+len(rr.qsubs) != 0
}
if shouldErr {
resp.Error = NewJSConsumerNameExistError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
}
}
ca := &consumerAssignment{Group: rg, Stream: stream, Name: oname, Config: cfg, Subject: subject, Reply: reply, Client: ci, Created: time.Now().UTC()}
eca := encodeAddConsumerAssignment(ca)
// Mark this as pending.
if sa.consumers == nil {
sa.consumers = make(map[string]*consumerAssignment)
}
ca.pending = true
sa.consumers[ca.Name] = ca
// Do formal proposal.
cc.meta.Propose(eca)
}
func encodeAddConsumerAssignment(ca *consumerAssignment) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(assignConsumerOp))
json.NewEncoder(&bb).Encode(ca)
return bb.Bytes()
}
func encodeDeleteConsumerAssignment(ca *consumerAssignment) []byte {
var bb bytes.Buffer
bb.WriteByte(byte(removeConsumerOp))
json.NewEncoder(&bb).Encode(ca)
return bb.Bytes()
}
func decodeConsumerAssignment(buf []byte) (*consumerAssignment, error) {
var ca consumerAssignment
err := json.Unmarshal(buf, &ca)
return &ca, err
}
func encodeAddConsumerAssignmentCompressed(ca *consumerAssignment) []byte {
b, err := json.Marshal(ca)
if err != nil {
return nil
}
// TODO(dlc) - Streaming better approach here probably.
var bb bytes.Buffer
bb.WriteByte(byte(assignCompressedConsumerOp))
bb.Write(s2.Encode(nil, b))
return bb.Bytes()
}
func decodeConsumerAssignmentCompressed(buf []byte) (*consumerAssignment, error) {
var ca consumerAssignment
js, err := s2.Decode(nil, buf)
if err != nil {
return nil, err
}
err = json.Unmarshal(js, &ca)
return &ca, err
}
var errBadStreamMsg = errors.New("jetstream cluster bad replicated stream msg")
func decodeStreamMsg(buf []byte) (subject, reply string, hdr, msg []byte, lseq uint64, ts int64, err error) {
var le = binary.LittleEndian
if len(buf) < 26 {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
lseq = le.Uint64(buf)
buf = buf[8:]
ts = int64(le.Uint64(buf))
buf = buf[8:]
sl := int(le.Uint16(buf))
buf = buf[2:]
if len(buf) < sl {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
subject = string(buf[:sl])
buf = buf[sl:]
if len(buf) < 2 {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
rl := int(le.Uint16(buf))
buf = buf[2:]
if len(buf) < rl {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
reply = string(buf[:rl])
buf = buf[rl:]
if len(buf) < 2 {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
hl := int(le.Uint16(buf))
buf = buf[2:]
if len(buf) < hl {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
if hdr = buf[:hl]; len(hdr) == 0 {
hdr = nil
}
buf = buf[hl:]
if len(buf) < 4 {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
ml := int(le.Uint32(buf))
buf = buf[4:]
if len(buf) < ml {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, errBadStreamMsg
}
if msg = buf[:ml]; len(msg) == 0 {
msg = nil
}
return subject, reply, hdr, msg, lseq, ts, nil
}
func encodeStreamMsg(subject, reply string, hdr, msg []byte, lseq uint64, ts int64) []byte {
elen := 1 + 8 + 8 + len(subject) + len(reply) + len(hdr) + len(msg)
elen += (2 + 2 + 2 + 4) // Encoded lengths, 4bytes
// TODO(dlc) - check sizes of subject, reply and hdr, make sure uint16 ok.
buf := make([]byte, elen)
buf[0] = byte(streamMsgOp)
var le = binary.LittleEndian
wi := 1
le.PutUint64(buf[wi:], lseq)
wi += 8
le.PutUint64(buf[wi:], uint64(ts))
wi += 8
le.PutUint16(buf[wi:], uint16(len(subject)))
wi += 2
copy(buf[wi:], subject)
wi += len(subject)
le.PutUint16(buf[wi:], uint16(len(reply)))
wi += 2
copy(buf[wi:], reply)
wi += len(reply)
le.PutUint16(buf[wi:], uint16(len(hdr)))
wi += 2
if len(hdr) > 0 {
copy(buf[wi:], hdr)
wi += len(hdr)
}
le.PutUint32(buf[wi:], uint32(len(msg)))
wi += 4
if len(msg) > 0 {
copy(buf[wi:], msg)
wi += len(msg)
}
return buf[:wi]
}
// StreamSnapshot is used for snapshotting and out of band catch up in clustered mode.
type streamSnapshot struct {
Msgs uint64 `json:"messages"`
Bytes uint64 `json:"bytes"`
FirstSeq uint64 `json:"first_seq"`
LastSeq uint64 `json:"last_seq"`
Deleted []uint64 `json:"deleted,omitempty"`
}
// Grab a snapshot of a stream for clustered mode.
func (mset *stream) stateSnapshot() []byte {
mset.mu.RLock()
defer mset.mu.RUnlock()
state := mset.store.State()
snap := &streamSnapshot{
Msgs: state.Msgs,
Bytes: state.Bytes,
FirstSeq: state.FirstSeq,
LastSeq: state.LastSeq,
Deleted: state.Deleted,
}
b, _ := json.Marshal(snap)
return b
}
// processClusteredMsg will propose the inbound message to the underlying raft group.
func (mset *stream) processClusteredInboundMsg(subject, reply string, hdr, msg []byte) error {
// For possible error response.
var response []byte
mset.mu.RLock()
canRespond := !mset.cfg.NoAck && len(reply) > 0
name, stype := mset.cfg.Name, mset.cfg.Storage
s, js, jsa, st, rf, outq := mset.srv, mset.js, mset.jsa, mset.cfg.Storage, mset.cfg.Replicas, mset.outq
maxMsgSize, lseq := int(mset.cfg.MaxMsgSize), mset.lseq
mset.mu.RUnlock()
// Check here pre-emptively if we have exceeded this server limits.
if js.limitsExceeded(stype) {
s.resourcesExeededError()
if canRespond {
b, _ := json.Marshal(&JSPubAckResponse{PubAck: &PubAck{Stream: name}, Error: NewJSInsufficientResourcesError()})
outq.send(&jsPubMsg{reply, _EMPTY_, _EMPTY_, nil, b, nil, 0, nil})
}
// Stepdown regardless.
if node := mset.raftNode(); node != nil {
node.StepDown()
}
return NewJSInsufficientResourcesError()
}
// Check here pre-emptively if we have exceeded our account limits.
var exceeded bool
jsa.mu.RLock()
if st == MemoryStorage {
total := jsa.storeTotal + int64(memStoreMsgSize(subject, hdr, msg)*uint64(rf))
if jsa.limits.MaxMemory > 0 && total > jsa.limits.MaxMemory {
exceeded = true
}
} else {
total := jsa.storeTotal + int64(fileStoreMsgSize(subject, hdr, msg)*uint64(rf))
if jsa.limits.MaxStore > 0 && total > jsa.limits.MaxStore {
exceeded = true
}
}
jsa.mu.RUnlock()
// If we have exceeded our account limits go ahead and return.
if exceeded {
err := fmt.Errorf("JetStream resource limits exceeded for account: %q", jsa.acc().Name)
s.Warnf(err.Error())
if canRespond {
var resp = &JSPubAckResponse{PubAck: &PubAck{Stream: name}}
resp.Error = NewJSAccountResourcesExceededError()
response, _ = json.Marshal(resp)
outq.send(&jsPubMsg{reply, _EMPTY_, _EMPTY_, nil, response, nil, 0, nil})
}
return err
}
// Check msgSize if we have a limit set there. Again this works if it goes through but better to be pre-emptive.
if maxMsgSize >= 0 && (len(hdr)+len(msg)) > maxMsgSize {
err := fmt.Errorf("JetStream message size exceeds limits for '%s > %s'", jsa.acc().Name, mset.cfg.Name)
s.Warnf(err.Error())
if canRespond {
var resp = &JSPubAckResponse{PubAck: &PubAck{Stream: name}}
resp.Error = NewJSStreamMessageExceedsMaximumError()
response, _ = json.Marshal(resp)
outq.send(&jsPubMsg{reply, _EMPTY_, _EMPTY_, nil, response, nil, 0, nil})
}
return err
}
// Since we encode header len as u16 make sure we do not exceed.
// Again this works if it goes through but better to be pre-emptive.
if len(hdr) > math.MaxUint16 {
err := fmt.Errorf("JetStream header size exceeds limits for '%s > %s'", jsa.acc().Name, mset.cfg.Name)
s.Warnf(err.Error())
if canRespond {
var resp = &JSPubAckResponse{PubAck: &PubAck{Stream: name}}
resp.Error = NewJSStreamHeaderExceedsMaximumError()
response, _ = json.Marshal(resp)
outq.send(&jsPubMsg{reply, _EMPTY_, _EMPTY_, nil, response, nil, 0, nil})
}
return err
}
// Proceed with proposing this message.
// We only use mset.clseq for clustering and in case we run ahead of actual commits.
// Check if we need to set initial value here
mset.clMu.Lock()
if mset.clseq == 0 || mset.clseq < lseq {
mset.clseq = mset.lastSeq()
}
esm := encodeStreamMsg(subject, reply, hdr, msg, mset.clseq, time.Now().UnixNano())
mset.clseq++
// Do proposal.
err := mset.node.Propose(esm)
if err != nil {
mset.clseq--
}
mset.clMu.Unlock()
if err != nil {
if canRespond {
var resp = &JSPubAckResponse{PubAck: &PubAck{Stream: mset.cfg.Name}}
resp.Error = &ApiError{Code: 503, Description: err.Error()}
response, _ = json.Marshal(resp)
// If we errored out respond here.
outq.send(&jsPubMsg{reply, _EMPTY_, _EMPTY_, nil, response, nil, 0, nil})
}
}
if err != nil && isOutOfSpaceErr(err) {
s.handleOutOfSpace(mset)
}
return err
}
// For requesting messages post raft snapshot to catch up streams post server restart.
// Any deleted msgs etc will be handled inline on catchup.
type streamSyncRequest struct {
Peer string `json:"peer,omitempty"`
FirstSeq uint64 `json:"first_seq"`
LastSeq uint64 `json:"last_seq"`
}
// Given a stream state that represents a snapshot, calculate the sync request based on our current state.
func (mset *stream) calculateSyncRequest(state *StreamState, snap *streamSnapshot) *streamSyncRequest {
// Quick check if we are already caught up.
if state.LastSeq >= snap.LastSeq {
return nil
}
return &streamSyncRequest{FirstSeq: state.LastSeq + 1, LastSeq: snap.LastSeq, Peer: mset.node.ID()}
}
// processSnapshotDeletes will update our current store based on the snapshot
// but only processing deletes and new FirstSeq / purges.
func (mset *stream) processSnapshotDeletes(snap *streamSnapshot) {
state := mset.store.State()
// Adjust if FirstSeq has moved.
if snap.FirstSeq > state.FirstSeq {
mset.store.Compact(snap.FirstSeq)
state = mset.store.State()
}
// Range the deleted and delete if applicable.
for _, dseq := range snap.Deleted {
if dseq <= state.LastSeq {
mset.store.RemoveMsg(dseq)
}
}
}
func (mset *stream) setCatchupPeer(peer string, lag uint64) {
if peer == _EMPTY_ {
return
}
mset.mu.Lock()
if mset.catchups == nil {
mset.catchups = make(map[string]uint64)
}
mset.catchups[peer] = lag
mset.mu.Unlock()
}
// Will decrement by one.
func (mset *stream) updateCatchupPeer(peer string) {
if peer == _EMPTY_ {
return
}
mset.mu.Lock()
if lag := mset.catchups[peer]; lag > 0 {
mset.catchups[peer] = lag - 1
}
mset.mu.Unlock()
}
func (mset *stream) clearCatchupPeer(peer string) {
mset.mu.Lock()
if mset.catchups != nil {
delete(mset.catchups, peer)
}
mset.mu.Unlock()
}
// Lock should be held.
func (mset *stream) clearAllCatchupPeers() {
if mset.catchups != nil {
mset.catchups = nil
}
}
func (mset *stream) lagForCatchupPeer(peer string) uint64 {
mset.mu.RLock()
defer mset.mu.RUnlock()
if mset.catchups == nil {
return 0
}
return mset.catchups[peer]
}
func (mset *stream) hasCatchupPeers() bool {
mset.mu.RLock()
defer mset.mu.RUnlock()
return len(mset.catchups) > 0
}
func (mset *stream) setCatchingUp() {
mset.mu.Lock()
mset.catchup = true
mset.mu.Unlock()
}
func (mset *stream) clearCatchingUp() {
mset.mu.Lock()
mset.catchup = false
mset.mu.Unlock()
}
func (mset *stream) isCatchingUp() bool {
mset.mu.RLock()
defer mset.mu.RUnlock()
return mset.catchup
}
// Process a stream snapshot.
func (mset *stream) processSnapshot(snap *streamSnapshot) error {
// Update any deletes, etc.
mset.processSnapshotDeletes(snap)
mset.mu.Lock()
state := mset.store.State()
sreq := mset.calculateSyncRequest(&state, snap)
s, js, subject, n := mset.srv, mset.js, mset.sa.Sync, mset.node
mset.mu.Unlock()
// Make sure our state's first sequence is <= the leader's snapshot.
if snap.FirstSeq < state.FirstSeq {
return errFirstSequenceMismatch
}
// Bug that would cause this to be empty on stream update.
if subject == _EMPTY_ {
return errors.New("corrupt stream assignment detected")
}
// Just return if up to date or already exceeded limits.
if sreq == nil || js.limitsExceeded(mset.cfg.Storage) {
return nil
}
// Pause the apply channel for our raft group while we catch up.
n.PauseApply()
defer n.ResumeApply()
// Set our catchup state.
mset.setCatchingUp()
defer mset.clearCatchingUp()
var sub *subscription
var err error
const activityInterval = 5 * time.Second
notActive := time.NewTimer(activityInterval)
defer notActive.Stop()
defer func() {
if sub != nil {
s.sysUnsubscribe(sub)
}
// Make sure any consumers are updated for the pending amounts.
mset.mu.Lock()
for _, o := range mset.consumers {
o.mu.Lock()
if o.isLeader() {
// This expects mset lock to be held.
o.setInitialPendingAndStart()
}
o.mu.Unlock()
}
mset.mu.Unlock()
}()
RETRY:
// If we have a sub clear that here.
if sub != nil {
s.sysUnsubscribe(sub)
sub = nil
}
// Grab sync request again on failures.
if sreq == nil {
mset.mu.Lock()
state := mset.store.State()
sreq = mset.calculateSyncRequest(&state, snap)
mset.mu.Unlock()
if sreq == nil {
return nil
}
}
// Used to transfer message from the wire to another Go routine internally.
type im struct {
msg []byte
reply string
}
sz := int(sreq.LastSeq-sreq.FirstSeq) + 1
msgsC := make(chan *im, sz)
// Send our catchup request here.
reply := syncReplySubject()
sub, err = s.sysSubscribe(reply, func(_ *subscription, _ *client, _ *Account, _, reply string, msg []byte) {
// Make copies - https://github.com/go101/go101/wiki
// TODO(dlc) - Since we are using a buffer from the inbound client/route.
select {
case msgsC <- &im{append(msg[:0:0], msg...), reply}:
default:
s.Warnf("Failed to place catchup message onto internal channel: %d pending", len(msgsC))
return
}
})
if err != nil {
s.Errorf("Could not subscribe to stream catchup: %v", err)
return err
}
b, _ := json.Marshal(sreq)
s.sendInternalMsgLocked(subject, reply, nil, b)
// Clear our sync request and capture last.
last := sreq.LastSeq
sreq = nil
// Run our own select loop here.
for qch, lch := n.QuitC(), n.LeadChangeC(); ; {
select {
case mrec := <-msgsC:
notActive.Reset(activityInterval)
msg := mrec.msg
// Check for eof signaling.
if len(msg) == 0 {
return nil
}
if lseq, err := mset.processCatchupMsg(msg); err == nil {
if lseq >= last {
return nil
}
} else if isOutOfSpaceErr(err) {
return err
} else if err == NewJSInsufficientResourcesError() {
if mset.js.limitsExceeded(mset.cfg.Storage) {
s.resourcesExeededError()
} else {
s.Warnf("Catchup for stream '%s > %s' errored, account resources exceeded: %v", mset.account(), mset.name(), err)
}
return err
} else {
s.Warnf("Catchup for stream '%s > %s' errored, will retry: %v", mset.account(), mset.name(), err)
goto RETRY
}
if mrec.reply != _EMPTY_ {
s.sendInternalMsgLocked(mrec.reply, _EMPTY_, nil, nil)
}
case <-notActive.C:
s.Warnf("Catchup for stream '%s > %s' stalled", mset.account(), mset.name())
notActive.Reset(activityInterval)
goto RETRY
case <-s.quitCh:
return nil
case <-qch:
return nil
case isLeader := <-lch:
js.processStreamLeaderChange(mset, isLeader)
return nil
}
}
}
// processCatchupMsg will be called to process out of band catchup msgs from a sync request.
func (mset *stream) processCatchupMsg(msg []byte) (uint64, error) {
if len(msg) == 0 || entryOp(msg[0]) != streamMsgOp {
return 0, errors.New("bad catchup msg")
}
subj, _, hdr, msg, seq, ts, err := decodeStreamMsg(msg[1:])
if err != nil {
return 0, errors.New("bad catchup msg")
}
st := mset.cfg.Storage
if mset.js.limitsExceeded(st) || mset.jsa.limitsExceeded(st) {
return 0, NewJSInsufficientResourcesError()
}
// Put into our store
// Messages to be skipped have no subject or timestamp.
// TODO(dlc) - formalize with skipMsgOp
if subj == _EMPTY_ && ts == 0 {
lseq := mset.store.SkipMsg()
if lseq != seq {
return 0, errors.New("wrong sequence for skipped msg")
}
} else if err := mset.store.StoreRawMsg(subj, hdr, msg, seq, ts); err != nil {
return 0, err
}
// Update our lseq.
mset.setLastSeq(seq)
return seq, nil
}
func (mset *stream) handleClusterSyncRequest(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) {
var sreq streamSyncRequest
if err := json.Unmarshal(msg, &sreq); err != nil {
// Log error.
return
}
mset.srv.startGoRoutine(func() { mset.runCatchup(reply, &sreq) })
}
// Lock should be held.
func (js *jetStream) offlineClusterInfo(rg *raftGroup) *ClusterInfo {
s := js.srv
ci := &ClusterInfo{Name: s.ClusterName()}
for _, peer := range rg.Peers {
if sir, ok := s.nodeToInfo.Load(peer); ok && sir != nil {
si := sir.(nodeInfo)
pi := &PeerInfo{Name: si.name, Current: false, Offline: true}
ci.Replicas = append(ci.Replicas, pi)
}
}
return ci
}
// clusterInfo will report on the status of the raft group.
func (js *jetStream) clusterInfo(rg *raftGroup) *ClusterInfo {
if js == nil {
return nil
}
js.mu.RLock()
defer js.mu.RUnlock()
s := js.srv
if rg == nil || rg.node == nil {
return &ClusterInfo{
Name: s.ClusterName(),
Leader: s.Name(),
}
}
n := rg.node
ci := &ClusterInfo{
Name: s.ClusterName(),
Leader: s.serverNameForNode(n.GroupLeader()),
}
now := time.Now()
id, peers := n.ID(), n.Peers()
// If we are leaderless, do not suppress putting us in the peer list.
if ci.Leader == _EMPTY_ {
id = _EMPTY_
}
for _, rp := range peers {
if rp.ID != id && rg.isMember(rp.ID) {
var lastSeen time.Duration
if now.After(rp.Last) && rp.Last.Unix() != 0 {
lastSeen = now.Sub(rp.Last)
}
current := rp.Current
if current && lastSeen > lostQuorumInterval {
current = false
}
if sir, ok := s.nodeToInfo.Load(rp.ID); ok && sir != nil {
si := sir.(nodeInfo)
pi := &PeerInfo{Name: si.name, Current: current, Offline: si.offline, Active: lastSeen, Lag: rp.Lag}
ci.Replicas = append(ci.Replicas, pi)
}
}
}
return ci
}
func (mset *stream) checkClusterInfo(si *StreamInfo) {
for _, r := range si.Cluster.Replicas {
peer := string(getHash(r.Name))
if lag := mset.lagForCatchupPeer(peer); lag > 0 {
r.Current = false
r.Lag = lag
}
}
}
func (mset *stream) handleClusterStreamInfoRequest(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) {
mset.mu.RLock()
sysc, js, sa, config := mset.sysc, mset.srv.js, mset.sa, mset.cfg
stype := mset.cfg.Storage
isLeader := mset.isLeader()
mset.mu.RUnlock()
// By design all members will receive this. Normally we only want the leader answering.
// But if we have stalled and lost quorom all can respond.
if sa != nil && !js.isGroupLeaderless(sa.Group) && !isLeader {
return
}
// If we are here we are in a compromised state due to server limits let someone else answer if they can.
if !isLeader && js.limitsExceeded(stype) {
time.Sleep(100 * time.Millisecond)
}
si := &StreamInfo{
Created: mset.createdTime(),
State: mset.state(),
Config: config,
Cluster: js.clusterInfo(mset.raftGroup()),
Sources: mset.sourcesInfo(),
Mirror: mset.mirrorInfo(),
}
// Check for out of band catchups.
if mset.hasCatchupPeers() {
mset.checkClusterInfo(si)
}
sysc.sendInternalMsg(reply, _EMPTY_, nil, si)
}
func (mset *stream) runCatchup(sendSubject string, sreq *streamSyncRequest) {
s := mset.srv
defer s.grWG.Done()
const maxOutBytes = int64(1 * 1024 * 1024) // 1MB for now.
const maxOutMsgs = int32(16384)
outb := int64(0)
outm := int32(0)
// Flow control processing.
ackReplySize := func(subj string) int64 {
if li := strings.LastIndexByte(subj, btsep); li > 0 && li < len(subj) {
return parseAckReplyNum(subj[li+1:])
}
return 0
}
nextBatchC := make(chan struct{}, 1)
nextBatchC <- struct{}{}
// Setup ackReply for flow control.
ackReply := syncAckSubject()
ackSub, _ := s.sysSubscribe(ackReply, func(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) {
sz := ackReplySize(subject)
atomic.AddInt64(&outb, -sz)
atomic.AddInt32(&outm, -1)
mset.updateCatchupPeer(sreq.Peer)
select {
case nextBatchC <- struct{}{}:
default:
}
})
defer s.sysUnsubscribe(ackSub)
ackReplyT := strings.ReplaceAll(ackReply, ".*", ".%d")
// EOF
defer s.sendInternalMsgLocked(sendSubject, _EMPTY_, nil, nil)
const activityInterval = 5 * time.Second
notActive := time.NewTimer(activityInterval)
defer notActive.Stop()
// Setup sequences to walk through.
seq, last := sreq.FirstSeq, sreq.LastSeq
mset.setCatchupPeer(sreq.Peer, last-seq)
defer mset.clearCatchupPeer(sreq.Peer)
sendNextBatch := func() {
for ; seq <= last && atomic.LoadInt64(&outb) <= maxOutBytes && atomic.LoadInt32(&outm) <= maxOutMsgs; seq++ {
subj, hdr, msg, ts, err := mset.store.LoadMsg(seq)
// if this is not a deleted msg, bail out.
if err != nil && err != ErrStoreMsgNotFound && err != errDeletedMsg {
// break, something changed.
seq = last + 1
return
}
// S2?
em := encodeStreamMsg(subj, _EMPTY_, hdr, msg, seq, ts)
// Place size in reply subject for flow control.
reply := fmt.Sprintf(ackReplyT, len(em))
atomic.AddInt64(&outb, int64(len(em)))
atomic.AddInt32(&outm, 1)
s.sendInternalMsgLocked(sendSubject, reply, nil, em)
}
}
// Grab stream quit channel.
mset.mu.RLock()
qch := mset.qch
mset.mu.RUnlock()
if qch == nil {
return
}
// Run as long as we are still active and need catchup.
// FIXME(dlc) - Purge event? Stream delete?
for {
select {
case <-s.quitCh:
return
case <-qch:
return
case <-notActive.C:
s.Warnf("Catchup for stream '%s > %s' stalled", mset.account(), mset.name())
return
case <-nextBatchC:
// Update our activity timer.
notActive.Reset(activityInterval)
sendNextBatch()
// Check if we are finished.
if seq > last {
s.Debugf("Done resync for stream '%s > %s'", mset.account(), mset.name())
return
}
}
}
}
const jscAllSubj = "$JSC.>"
func syncSubjForStream() string {
return syncSubject("$JSC.SYNC")
}
func syncReplySubject() string {
return syncSubject("$JSC.R")
}
func infoReplySubject() string {
return syncSubject("$JSC.R")
}
func syncAckSubject() string {
return syncSubject("$JSC.ACK") + ".*"
}
func syncSubject(pre string) string {
var sb strings.Builder
sb.WriteString(pre)
sb.WriteByte(btsep)
var b [replySuffixLen]byte
rn := rand.Int63()
for i, l := 0, rn; i < len(b); i++ {
b[i] = digits[l%base]
l /= base
}
sb.Write(b[:])
return sb.String()
}
const (
clusterStreamInfoT = "$JSC.SI.%s.%s"
clusterConsumerInfoT = "$JSC.CI.%s.%s.%s"
jsaUpdatesSubT = "$JSC.ARU.%s.*"
jsaUpdatesPubT = "$JSC.ARU.%s.%s"
)
| 1 | 14,178 | Do we need also to protect access to `mset.js` and `mset.jsa` or even `mset.store` down below? (not sure if those are immutable or not). | nats-io-nats-server | go |
@@ -579,6 +579,7 @@ func (k *KeybaseServiceBase) ResolveImplicitTeamByID(
func (k *KeybaseServiceBase) checkForRevokedVerifyingKey(
ctx context.Context, currUserInfo UserInfo, kid keybase1.KID) (
newUserInfo UserInfo, exists bool, err error) {
+ newUserInfo = currUserInfo
for key, info := range currUserInfo.RevokedVerifyingKeys {
if !key.KID().Equal(kid) {
continue | 1 | // Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"fmt"
"sync"
"time"
kbname "github.com/keybase/client/go/kbun"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/kbfs/kbfscrypto"
"github.com/keybase/kbfs/kbfsmd"
"github.com/keybase/kbfs/tlf"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
// KeybaseServiceBase implements most of KeybaseService from protocol
// defined clients.
type KeybaseServiceBase struct {
context Context
identifyClient keybase1.IdentifyInterface
userClient keybase1.UserInterface
teamsClient keybase1.TeamsInterface
merkleClient keybase1.MerkleInterface
sessionClient keybase1.SessionInterface
favoriteClient keybase1.FavoriteInterface
kbfsClient keybase1.KbfsInterface
kbfsMountClient keybase1.KbfsMountInterface
gitClient keybase1.GitInterface
log logger.Logger
config Config
merkleRoot *EventuallyConsistentMerkleRoot
sessionCacheLock sync.RWMutex
// Set to the zero value when invalidated.
cachedCurrentSession SessionInfo
sessionInProgressCh chan struct{}
userCacheLock sync.RWMutex
// Map entries are removed when invalidated.
userCache map[keybase1.UID]UserInfo
userCacheUnverifiedKeys map[keybase1.UID][]keybase1.PublicKey
teamCacheLock sync.RWMutex
// Map entries are removed when invalidated.
teamCache map[keybase1.TeamID]TeamInfo
lastNotificationFilenameLock sync.Mutex
lastNotificationFilename string
lastPathUpdated string
lastSyncNotificationPath string
}
// Wrapper over `KeybaseServiceBase` implementing a `merkleRootGetter`
// that gets the merkle root directly from the service, without using
// the cache.
type keybaseServiceMerkleGetter struct {
k *KeybaseServiceBase
}
var _ merkleRootGetter = (*keybaseServiceMerkleGetter)(nil)
func (k *keybaseServiceMerkleGetter) GetCurrentMerkleRoot(
ctx context.Context) (keybase1.MerkleRootV2, time.Time, error) {
return k.k.getCurrentMerkleRoot(ctx)
}
func (k *keybaseServiceMerkleGetter) VerifyMerkleRoot(
_ context.Context, _ keybase1.MerkleRootV2, _ keybase1.KBFSRoot) error {
panic("constMerkleRootGetter doesn't verify merkle roots")
}
// NewKeybaseServiceBase makes a new KeybaseService.
func NewKeybaseServiceBase(config Config, kbCtx Context, log logger.Logger) *KeybaseServiceBase {
k := KeybaseServiceBase{
config: config,
context: kbCtx,
log: log,
userCache: make(map[keybase1.UID]UserInfo),
userCacheUnverifiedKeys: make(map[keybase1.UID][]keybase1.PublicKey),
teamCache: make(map[keybase1.TeamID]TeamInfo),
}
if config != nil {
k.merkleRoot = NewEventuallyConsistentMerkleRoot(
config, &keybaseServiceMerkleGetter{&k})
}
return &k
}
// FillClients sets the client protocol implementations needed for a KeybaseService.
func (k *KeybaseServiceBase) FillClients(
identifyClient keybase1.IdentifyInterface,
userClient keybase1.UserInterface, teamsClient keybase1.TeamsInterface,
merkleClient keybase1.MerkleInterface,
sessionClient keybase1.SessionInterface,
favoriteClient keybase1.FavoriteInterface,
kbfsClient keybase1.KbfsInterface,
kbfsMountClient keybase1.KbfsMountInterface,
gitClient keybase1.GitInterface) {
k.identifyClient = identifyClient
k.userClient = userClient
k.teamsClient = teamsClient
k.merkleClient = merkleClient
k.sessionClient = sessionClient
k.favoriteClient = favoriteClient
k.kbfsClient = kbfsClient
k.kbfsMountClient = kbfsMountClient
k.gitClient = gitClient
}
type addVerifyingKeyFunc func(kbfscrypto.VerifyingKey)
type addCryptPublicKeyFunc func(kbfscrypto.CryptPublicKey)
// processKey adds the given public key to the appropriate verifying
// or crypt list (as return values), and also updates the given name
// map and parent map in place.
func processKey(publicKey keybase1.PublicKeyV2NaCl,
addVerifyingKey addVerifyingKeyFunc,
addCryptPublicKey addCryptPublicKeyFunc,
kidNames map[keybase1.KID]string,
parents map[keybase1.KID]keybase1.KID) error {
// Import the KID to validate it.
key, err := libkb.ImportKeypairFromKID(publicKey.Base.Kid)
if err != nil {
return err
}
if publicKey.Base.IsSibkey {
addVerifyingKey(kbfscrypto.MakeVerifyingKey(key.GetKID()))
} else {
addCryptPublicKey(kbfscrypto.MakeCryptPublicKey(key.GetKID()))
}
if publicKey.DeviceDescription != "" {
kidNames[publicKey.Base.Kid] = publicKey.DeviceDescription
}
if publicKey.Parent != nil {
parents[publicKey.Base.Kid] = *publicKey.Parent
}
return nil
}
// updateKIDNamesFromParents sets the name of each KID without a name
// that has a a parent with a name, to that parent's name.
func updateKIDNamesFromParents(kidNames map[keybase1.KID]string,
parents map[keybase1.KID]keybase1.KID) {
for kid, parent := range parents {
if _, ok := kidNames[kid]; ok {
continue
}
if parentName, ok := kidNames[parent]; ok {
kidNames[kid] = parentName
}
}
}
func filterKeys(keys map[keybase1.KID]keybase1.PublicKeyV2NaCl) (
verifyingKeys []kbfscrypto.VerifyingKey,
cryptPublicKeys []kbfscrypto.CryptPublicKey,
kidNames map[keybase1.KID]string, err error) {
kidNames = make(map[keybase1.KID]string, len(keys))
parents := make(map[keybase1.KID]keybase1.KID, len(keys))
addVerifyingKey := func(key kbfscrypto.VerifyingKey) {
verifyingKeys = append(verifyingKeys, key)
}
addCryptPublicKey := func(key kbfscrypto.CryptPublicKey) {
cryptPublicKeys = append(cryptPublicKeys, key)
}
for _, publicKey := range keys {
if publicKey.Base.Revocation != nil {
continue
}
err := processKey(publicKey, addVerifyingKey, addCryptPublicKey,
kidNames, parents)
if err != nil {
return nil, nil, nil, err
}
}
updateKIDNamesFromParents(kidNames, parents)
return verifyingKeys, cryptPublicKeys, kidNames, nil
}
func (k *KeybaseServiceBase) filterRevokedKeys(
ctx context.Context,
uid keybase1.UID,
keys map[keybase1.KID]keybase1.PublicKeyV2NaCl,
reset *keybase1.ResetSummary) (
map[kbfscrypto.VerifyingKey]revokedKeyInfo,
map[kbfscrypto.CryptPublicKey]revokedKeyInfo,
map[keybase1.KID]string, error) {
verifyingKeys := make(map[kbfscrypto.VerifyingKey]revokedKeyInfo)
cryptPublicKeys := make(map[kbfscrypto.CryptPublicKey]revokedKeyInfo)
var kidNames = map[keybase1.KID]string{}
var parents = map[keybase1.KID]keybase1.KID{}
for _, key := range keys {
var info revokedKeyInfo
if key.Base.Revocation != nil {
info.Time = key.Base.Revocation.Time
info.MerkleRoot = key.Base.Revocation.PrevMerkleRootSigned
// If we don't have a prev seqno, then we already have the
// best merkle data we're going to get.
info.filledInMerkle = info.MerkleRoot.Seqno <= 0
info.sigChainLocation = key.Base.Revocation.SigChainLocation
} else if reset != nil {
info.Time = keybase1.ToTime(keybase1.FromUnixTime(reset.Ctime))
info.MerkleRoot.Seqno = reset.MerkleRoot.Seqno
info.MerkleRoot.HashMeta = reset.MerkleRoot.HashMeta
// If we don't have a prev seqno, then we already have the
// best merkle data we're going to get.
info.filledInMerkle = info.MerkleRoot.Seqno <= 0
info.resetSeqno = reset.ResetSeqno
info.isReset = true
} else {
// Not revoked.
continue
}
addVerifyingKey := func(key kbfscrypto.VerifyingKey) {
verifyingKeys[key] = info
}
addCryptPublicKey := func(key kbfscrypto.CryptPublicKey) {
cryptPublicKeys[key] = info
}
err := processKey(key, addVerifyingKey, addCryptPublicKey,
kidNames, parents)
if err != nil {
return nil, nil, nil, err
}
}
updateKIDNamesFromParents(kidNames, parents)
return verifyingKeys, cryptPublicKeys, kidNames, nil
}
func (k *KeybaseServiceBase) getCachedCurrentSession() SessionInfo {
k.sessionCacheLock.RLock()
defer k.sessionCacheLock.RUnlock()
return k.cachedCurrentSession
}
func (k *KeybaseServiceBase) setCachedCurrentSession(s SessionInfo) {
k.sessionCacheLock.Lock()
defer k.sessionCacheLock.Unlock()
k.cachedCurrentSession = s
}
func (k *KeybaseServiceBase) getCachedUserInfo(uid keybase1.UID) UserInfo {
k.userCacheLock.RLock()
defer k.userCacheLock.RUnlock()
return k.userCache[uid]
}
func (k *KeybaseServiceBase) setCachedUserInfo(uid keybase1.UID, info UserInfo) {
k.userCacheLock.Lock()
defer k.userCacheLock.Unlock()
if info.Name == kbname.NormalizedUsername("") {
delete(k.userCache, uid)
} else {
k.userCache[uid] = info
}
}
func (k *KeybaseServiceBase) getCachedUnverifiedKeys(uid keybase1.UID) (
[]keybase1.PublicKey, bool) {
k.userCacheLock.RLock()
defer k.userCacheLock.RUnlock()
if unverifiedKeys, ok := k.userCacheUnverifiedKeys[uid]; ok {
return unverifiedKeys, true
}
return nil, false
}
func (k *KeybaseServiceBase) setCachedUnverifiedKeys(uid keybase1.UID, pk []keybase1.PublicKey) {
k.userCacheLock.Lock()
defer k.userCacheLock.Unlock()
k.userCacheUnverifiedKeys[uid] = pk
}
func (k *KeybaseServiceBase) clearCachedUnverifiedKeys(uid keybase1.UID) {
k.userCacheLock.Lock()
defer k.userCacheLock.Unlock()
delete(k.userCacheUnverifiedKeys, uid)
}
func (k *KeybaseServiceBase) getCachedTeamInfo(tid keybase1.TeamID) TeamInfo {
k.teamCacheLock.RLock()
defer k.teamCacheLock.RUnlock()
return k.teamCache[tid]
}
func (k *KeybaseServiceBase) setCachedTeamInfo(
tid keybase1.TeamID, info TeamInfo) {
k.teamCacheLock.Lock()
defer k.teamCacheLock.Unlock()
if info.Name == kbname.NormalizedUsername("") {
delete(k.teamCache, tid)
} else {
k.teamCache[tid] = info
}
}
func (k *KeybaseServiceBase) clearCaches() {
k.setCachedCurrentSession(SessionInfo{})
func() {
k.userCacheLock.Lock()
defer k.userCacheLock.Unlock()
k.userCache = make(map[keybase1.UID]UserInfo)
k.userCacheUnverifiedKeys = make(map[keybase1.UID][]keybase1.PublicKey)
}()
k.teamCacheLock.Lock()
defer k.teamCacheLock.Unlock()
k.teamCache = make(map[keybase1.TeamID]TeamInfo)
}
// LoggedIn implements keybase1.NotifySessionInterface.
func (k *KeybaseServiceBase) LoggedIn(ctx context.Context, name string) error {
k.log.CDebugf(ctx, "Current session logged in: %s", name)
// Since we don't have the whole session, just clear the cache and
// repopulate it. The `CurrentSession` call executes the "logged
// in" flow.
k.setCachedCurrentSession(SessionInfo{})
const sessionID = 0
_, err := k.CurrentSession(ctx, sessionID)
if err != nil {
k.log.CDebugf(ctx, "Getting current session failed when %s is logged "+
"in, so pretending user has logged out: %v",
name, err)
if k.config != nil {
serviceLoggedOut(ctx, k.config)
}
return nil
}
return nil
}
// LoggedOut implements keybase1.NotifySessionInterface.
func (k *KeybaseServiceBase) LoggedOut(ctx context.Context) error {
k.log.CDebugf(ctx, "Current session logged out")
k.setCachedCurrentSession(SessionInfo{})
if k.config != nil {
serviceLoggedOut(ctx, k.config)
}
return nil
}
// KeyfamilyChanged implements keybase1.NotifyKeyfamilyInterface.
func (k *KeybaseServiceBase) KeyfamilyChanged(ctx context.Context,
uid keybase1.UID) error {
k.log.CDebugf(ctx, "Key family for user %s changed", uid)
k.setCachedUserInfo(uid, UserInfo{})
k.clearCachedUnverifiedKeys(uid)
if k.getCachedCurrentSession().UID == uid {
mdServer := k.config.MDServer()
if mdServer != nil {
// Ignore any errors for now, we don't want to block this
// notification and it's not worth spawning a goroutine for.
mdServer.CheckForRekeys(context.Background())
}
}
return nil
}
// ReachabilityChanged implements keybase1.ReachabiltyInterface.
func (k *KeybaseServiceBase) ReachabilityChanged(ctx context.Context,
reachability keybase1.Reachability) error {
k.log.CDebugf(ctx, "CheckReachability invoked: %v", reachability)
if reachability.Reachable == keybase1.Reachable_YES {
k.config.KBFSOps().PushConnectionStatusChange(GregorServiceName, nil)
} else {
k.config.KBFSOps().PushConnectionStatusChange(
GregorServiceName, errDisconnected{})
}
mdServer := k.config.MDServer()
if mdServer != nil {
mdServer.CheckReachability(ctx)
}
return nil
}
// StartReachability implements keybase1.ReachabilityInterface.
func (k *KeybaseServiceBase) StartReachability(ctx context.Context) (res keybase1.Reachability, err error) {
return k.CheckReachability(ctx)
}
// CheckReachability implements keybase1.ReachabilityInterface.
func (k *KeybaseServiceBase) CheckReachability(ctx context.Context) (res keybase1.Reachability, err error) {
res.Reachable = keybase1.Reachable_NO
mdServer := k.config.MDServer()
if mdServer != nil && mdServer.IsConnected() {
res.Reachable = keybase1.Reachable_YES
}
return res, nil
}
// PaperKeyCached implements keybase1.NotifyPaperKeyInterface.
func (k *KeybaseServiceBase) PaperKeyCached(ctx context.Context,
arg keybase1.PaperKeyCachedArg) error {
k.log.CDebugf(ctx, "Paper key for %s cached", arg.Uid)
if k.getCachedCurrentSession().UID == arg.Uid {
err := k.config.KBFSOps().KickoffAllOutstandingRekeys()
if err != nil {
// Ignore and log errors here. For now the only way it could error
// is when the method is called on a folderBranchOps which is a
// developer mistake and not recoverable from code.
k.log.CDebugf(ctx,
"Calling KickoffAllOutstandingRekeys error: %s", err)
}
// Ignore any errors for now, we don't want to block this
// notification and it's not worth spawning a goroutine for.
mdServer := k.config.MDServer()
if mdServer != nil {
mdServer.CheckForRekeys(context.Background())
}
}
return nil
}
// ClientOutOfDate implements keybase1.NotifySessionInterface.
func (k *KeybaseServiceBase) ClientOutOfDate(ctx context.Context,
arg keybase1.ClientOutOfDateArg) error {
k.log.CDebugf(ctx, "Client out of date: %v", arg)
return nil
}
// ConvertIdentifyError converts a errors during identify into KBFS errors
func ConvertIdentifyError(assertion string, err error) error {
switch err.(type) {
case libkb.NotFoundError:
return NoSuchUserError{assertion}
case libkb.ResolutionError:
return NoSuchUserError{assertion}
}
return err
}
// Resolve implements the KeybaseService interface for KeybaseServiceBase.
func (k *KeybaseServiceBase) Resolve(ctx context.Context, assertion string) (
kbname.NormalizedUsername, keybase1.UserOrTeamID, error) {
res, err := k.identifyClient.Resolve3(ctx, assertion)
if err != nil {
return kbname.NormalizedUsername(""), keybase1.UserOrTeamID(""),
ConvertIdentifyError(assertion, err)
}
return kbname.NewNormalizedUsername(res.Name), res.Id, nil
}
// Identify implements the KeybaseService interface for KeybaseServiceBase.
func (k *KeybaseServiceBase) Identify(ctx context.Context, assertion, reason string) (
kbname.NormalizedUsername, keybase1.UserOrTeamID, error) {
// setting UseDelegateUI to true here will cause daemon to use
// registered identify ui providers instead of terminal if any
// are available. If not, then it will use the terminal UI.
arg := keybase1.IdentifyLiteArg{
Assertion: assertion,
UseDelegateUI: true,
Reason: keybase1.IdentifyReason{Reason: reason},
// No need to go back and forth with the UI until the service
// knows for sure there's a need for a dialogue.
CanSuppressUI: true,
}
ei := getExtendedIdentify(ctx)
arg.IdentifyBehavior = ei.behavior
res, err := k.identifyClient.IdentifyLite(ctx, arg)
// IdentifyLite still returns keybase1.UserPlusKeys data (sans
// keys), even if it gives a NoSigChainError or a UserDeletedError,
// and in KBFS it's fine if the user doesn't have a full sigchain
// (e.g., it's just like the sharing before signup case, except
// the user already has a UID). Both types of users are based
// entirely on server trust anyway.
switch err.(type) {
case nil:
case libkb.NoSigChainError, libkb.UserDeletedError:
k.log.CDebugf(ctx,
"Ignoring error (%s) for user %s with no sigchain; "+
"error type=%T", err, res.Ul.Name, err)
default:
return kbname.NormalizedUsername(""), keybase1.UserOrTeamID(""),
ConvertIdentifyError(assertion, err)
}
// This is required for every identify call. The userBreak
// function will take care of checking if res.TrackBreaks is nil
// or not.
name := kbname.NormalizedUsername(res.Ul.Name)
if res.Ul.Id.IsUser() {
asUser, err := res.Ul.Id.AsUser()
if err != nil {
return kbname.NormalizedUsername(""), keybase1.UserOrTeamID(""), err
}
ei.userBreak(name, asUser, res.TrackBreaks)
}
return name, res.Ul.Id, nil
}
// ResolveIdentifyImplicitTeam implements the KeybaseService interface
// for KeybaseServiceBase.
func (k *KeybaseServiceBase) ResolveIdentifyImplicitTeam(
ctx context.Context, assertions, suffix string, tlfType tlf.Type,
doIdentifies bool, reason string) (ImplicitTeamInfo, error) {
if tlfType != tlf.Private && tlfType != tlf.Public {
return ImplicitTeamInfo{}, fmt.Errorf(
"Invalid implicit team TLF type: %s", tlfType)
}
arg := keybase1.ResolveIdentifyImplicitTeamArg{
Assertions: assertions,
Suffix: suffix,
DoIdentifies: doIdentifies,
Reason: keybase1.IdentifyReason{Reason: reason},
Create: true,
IsPublic: tlfType == tlf.Public,
}
ei := getExtendedIdentify(ctx)
arg.IdentifyBehavior = ei.behavior
res, err := k.identifyClient.ResolveIdentifyImplicitTeam(ctx, arg)
if err != nil {
return ImplicitTeamInfo{}, ConvertIdentifyError(assertions, err)
}
name := kbname.NormalizedUsername(res.DisplayName)
// This is required for every identify call. The userBreak
// function will take care of checking if res.TrackBreaks is nil
// or not.
for userVer, breaks := range res.TrackBreaks {
// TODO: resolve the UID into a username so we don't have to
// pass in the full display name here?
ei.userBreak(name, userVer.Uid, &breaks)
}
iteamInfo := ImplicitTeamInfo{
Name: name,
TID: res.TeamID,
}
if res.FolderID != "" {
iteamInfo.TlfID, err = tlf.ParseID(res.FolderID.String())
if err != nil {
return ImplicitTeamInfo{}, err
}
}
return iteamInfo, nil
}
// ResolveImplicitTeamByID implements the KeybaseService interface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) ResolveImplicitTeamByID(
ctx context.Context, teamID keybase1.TeamID) (name string, err error) {
arg := keybase1.ResolveImplicitTeamArg{
Id: teamID,
}
res, err := k.identifyClient.ResolveImplicitTeam(ctx, arg)
if err != nil {
return "", err
}
return res.Name, nil
}
func (k *KeybaseServiceBase) checkForRevokedVerifyingKey(
ctx context.Context, currUserInfo UserInfo, kid keybase1.KID) (
newUserInfo UserInfo, exists bool, err error) {
for key, info := range currUserInfo.RevokedVerifyingKeys {
if !key.KID().Equal(kid) {
continue
}
exists = true
if info.filledInMerkle {
break
}
k.log.CDebugf(ctx, "Filling in merkle info for user %s, revoked key %s",
currUserInfo.UID, kid)
// If possible, ask the service to give us the first merkle
// root that covers this revoke. Some older device revokes
// didn't yet include a prev field, so we can't refine the
// merkle root in those cases, and will be relying only on
// server trust.
if info.MerkleRoot.Seqno > 0 {
var res keybase1.NextMerkleRootRes
if info.isReset {
res, err = k.userClient.FindNextMerkleRootAfterReset(ctx,
keybase1.FindNextMerkleRootAfterResetArg{
Uid: currUserInfo.UID,
ResetSeqno: info.resetSeqno,
Prev: keybase1.ResetMerkleRoot{
Seqno: info.MerkleRoot.Seqno,
HashMeta: info.MerkleRoot.HashMeta,
},
})
} else {
res, err = k.userClient.FindNextMerkleRootAfterRevoke(ctx,
keybase1.FindNextMerkleRootAfterRevokeArg{
Uid: currUserInfo.UID,
Kid: kid,
Loc: info.sigChainLocation,
Prev: info.MerkleRoot,
})
}
if m, ok := err.(libkb.MerkleClientError); ok && m.IsOldTree() {
k.log.CDebugf(ctx, "Merkle root is too old for checking "+
"the revoked key: %+v", err)
info.MerkleRoot.Seqno = 0
} else if err != nil {
return UserInfo{}, false, err
} else if res.Res != nil {
info.MerkleRoot = *res.Res
}
}
info.filledInMerkle = true
currUserInfo.RevokedVerifyingKeys[key] = info
k.setCachedUserInfo(currUserInfo.UID, currUserInfo)
break
}
return currUserInfo, exists, nil
}
// LoadUserPlusKeys implements the KeybaseService interface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) LoadUserPlusKeys(ctx context.Context,
uid keybase1.UID, pollForKID keybase1.KID) (UserInfo, error) {
cachedUserInfo := k.getCachedUserInfo(uid)
if cachedUserInfo.Name != kbname.NormalizedUsername("") {
if pollForKID == keybase1.KID("") {
return cachedUserInfo, nil
}
// Skip the cache if pollForKID isn't present in
// `VerifyingKeys` or one of the revoked verifying keys.
for _, key := range cachedUserInfo.VerifyingKeys {
if key.KID().Equal(pollForKID) {
return cachedUserInfo, nil
}
}
// Check if the key is revoked, and fill in the merkle info in
// that case.
cachedUserInfo, exists, err := k.checkForRevokedVerifyingKey(
ctx, cachedUserInfo, pollForKID)
if err != nil {
return UserInfo{}, err
}
if exists {
return cachedUserInfo, nil
}
}
arg := keybase1.LoadUserPlusKeysV2Arg{Uid: uid, PollForKID: pollForKID}
res, err := k.userClient.LoadUserPlusKeysV2(ctx, arg)
if err != nil {
return UserInfo{}, err
}
userInfo, err := k.processUserPlusKeys(ctx, res)
if err != nil {
return UserInfo{}, err
}
if pollForKID != keybase1.KID("") {
// Fill in merkle info if we were explicitly trying to load a
// revoked key.
userInfo, _, err = k.checkForRevokedVerifyingKey(
ctx, userInfo, pollForKID)
if err != nil {
return UserInfo{}, err
}
}
return userInfo, nil
}
func (k *KeybaseServiceBase) getLastWriterInfo(
ctx context.Context, teamInfo TeamInfo, tlfType tlf.Type, user keybase1.UID,
verifyingKey kbfscrypto.VerifyingKey) (TeamInfo, error) {
if _, ok := teamInfo.LastWriters[verifyingKey]; ok {
// Already cached, nothing to do.
return teamInfo, nil
}
res, err := k.teamsClient.FindNextMerkleRootAfterTeamRemovalBySigningKey(
ctx, keybase1.FindNextMerkleRootAfterTeamRemovalBySigningKeyArg{
Uid: user,
SigningKey: verifyingKey.KID(),
Team: teamInfo.TID,
IsPublic: tlfType == tlf.Public,
})
if err != nil {
return TeamInfo{}, err
}
// Copy any old data to avoid races.
newLastWriters := make(
map[kbfscrypto.VerifyingKey]keybase1.MerkleRootV2,
len(teamInfo.LastWriters)+1)
for k, v := range teamInfo.LastWriters {
newLastWriters[k] = v
}
newLastWriters[verifyingKey] = *res.Res
teamInfo.LastWriters = newLastWriters
return teamInfo, nil
}
var allowedLoadTeamRoles = map[keybase1.TeamRole]bool{
keybase1.TeamRole_NONE: true,
keybase1.TeamRole_WRITER: true,
keybase1.TeamRole_READER: true,
}
// LoadTeamPlusKeys implements the KeybaseService interface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) LoadTeamPlusKeys(
ctx context.Context, tid keybase1.TeamID, tlfType tlf.Type,
desiredKeyGen kbfsmd.KeyGen, desiredUser keybase1.UserVersion,
desiredKey kbfscrypto.VerifyingKey, desiredRole keybase1.TeamRole) (
TeamInfo, error) {
if !allowedLoadTeamRoles[desiredRole] {
panic(fmt.Sprintf("Disallowed team role: %v", desiredRole))
}
cachedTeamInfo := k.getCachedTeamInfo(tid)
if cachedTeamInfo.Name != kbname.NormalizedUsername("") {
// If the cached team info doesn't satisfy our desires, don't
// use it.
satisfiesDesires := true
if desiredKeyGen >= kbfsmd.FirstValidKeyGen {
// If `desiredKeyGen` is at most as large as the keygen in
// the cached latest team info, then our cached info
// satisfies our desires.
satisfiesDesires = desiredKeyGen <= cachedTeamInfo.LatestKeyGen
}
if satisfiesDesires && desiredUser.Uid.Exists() {
// If the user is in the writer map, that satisfies none, reader
// or writer desires.
satisfiesDesires = cachedTeamInfo.Writers[desiredUser.Uid]
if !satisfiesDesires {
if desiredRole == keybase1.TeamRole_NONE ||
desiredRole == keybase1.TeamRole_READER {
// If the user isn't a writer, but the desired
// role is a reader, we need to check the reader
// map explicitly.
satisfiesDesires = cachedTeamInfo.Readers[desiredUser.Uid]
} else if !desiredKey.IsNil() {
// If the desired role was at least a writer, but
// the user isn't currently a writer, see if they
// ever were.
var err error
cachedTeamInfo, err = k.getLastWriterInfo(
ctx, cachedTeamInfo, tlfType, desiredUser.Uid,
desiredKey)
if err != nil {
return TeamInfo{}, err
}
k.setCachedTeamInfo(tid, cachedTeamInfo)
}
}
}
if satisfiesDesires {
return cachedTeamInfo, nil
}
}
arg := keybase1.LoadTeamPlusApplicationKeysArg{
Id: tid,
Application: keybase1.TeamApplication_KBFS,
}
if desiredKeyGen >= kbfsmd.FirstValidKeyGen {
arg.Refreshers.NeedKeyGeneration =
keybase1.PerTeamKeyGeneration(desiredKeyGen)
}
if desiredUser.Uid.Exists() && desiredKey.IsNil() {
arg.Refreshers.WantMembers = append(
arg.Refreshers.WantMembers, desiredUser)
arg.Refreshers.WantMembersRole = desiredRole
}
res, err := k.teamsClient.LoadTeamPlusApplicationKeys(ctx, arg)
if err != nil {
return TeamInfo{}, err
}
if tid != res.Id {
return TeamInfo{}, fmt.Errorf(
"TID doesn't match: %s vs %s", tid, res.Id)
}
info := TeamInfo{
Name: kbname.NormalizedUsername(res.Name),
TID: res.Id,
CryptKeys: make(map[kbfsmd.KeyGen]kbfscrypto.TLFCryptKey),
Writers: make(map[keybase1.UID]bool),
Readers: make(map[keybase1.UID]bool),
}
for _, key := range res.ApplicationKeys {
keyGen := kbfsmd.KeyGen(key.KeyGeneration)
info.CryptKeys[keyGen] =
kbfscrypto.MakeTLFCryptKey(key.Key)
if keyGen > info.LatestKeyGen {
info.LatestKeyGen = keyGen
}
}
for _, user := range res.Writers {
info.Writers[user.Uid] = true
}
for _, user := range res.OnlyReaders {
info.Readers[user.Uid] = true
}
// For subteams, get the root team ID.
if tid.IsSubTeam() {
rootID, err := k.teamsClient.GetTeamRootID(ctx, tid)
if err != nil {
return TeamInfo{}, err
}
info.RootID = rootID
}
// Fill in `LastWriters`, only if needed.
if desiredUser.Uid.Exists() && desiredRole == keybase1.TeamRole_WRITER &&
!info.Writers[desiredUser.Uid] && !desiredKey.IsNil() {
info, err = k.getLastWriterInfo(
ctx, info, tlfType, desiredUser.Uid, desiredKey)
if err != nil {
return TeamInfo{}, err
}
}
k.setCachedTeamInfo(tid, info)
return info, nil
}
// CreateTeamTLF implements the KeybaseService interface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) CreateTeamTLF(
ctx context.Context, teamID keybase1.TeamID, tlfID tlf.ID) (err error) {
return k.kbfsClient.CreateTLF(ctx, keybase1.CreateTLFArg{
TeamID: teamID,
TlfID: keybase1.TLFID(tlfID.String()),
})
}
// GetTeamSettings implements the KeybaseService interface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) GetTeamSettings(
ctx context.Context, teamID keybase1.TeamID) (
keybase1.KBFSTeamSettings, error) {
// TODO: get invalidations from the server and cache the settings?
return k.kbfsClient.GetKBFSTeamSettings(ctx, teamID)
}
func (k *KeybaseServiceBase) getCurrentMerkleRoot(ctx context.Context) (
keybase1.MerkleRootV2, time.Time, error) {
const merkleFreshnessMs = int(time.Second * 60 / time.Millisecond)
res, err := k.merkleClient.GetCurrentMerkleRoot(ctx, merkleFreshnessMs)
if err != nil {
return keybase1.MerkleRootV2{}, time.Time{}, err
}
return res.Root, keybase1.FromTime(res.UpdateTime), nil
}
// GetCurrentMerkleRoot implements the KeybaseService interface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) GetCurrentMerkleRoot(ctx context.Context) (
keybase1.MerkleRootV2, time.Time, error) {
// Refresh the cached value in the background if the cached value
// is older than 30s; if our cached value is more than 60s old,
// block.
_, root, rootTime, err := k.merkleRoot.Get(
ctx, 30*time.Second, 60*time.Second)
return root, rootTime, err
}
// VerifyMerkleRoot implements the KBPKI interface for KeybaseServiceBase.
func (k *KeybaseServiceBase) VerifyMerkleRoot(
ctx context.Context, root keybase1.MerkleRootV2,
kbfsRoot keybase1.KBFSRoot) error {
return k.merkleClient.VerifyMerkleRootAndKBFS(ctx,
keybase1.VerifyMerkleRootAndKBFSArg{
Root: root,
ExpectedKBFSRoot: kbfsRoot,
})
}
func (k *KeybaseServiceBase) processUserPlusKeys(
ctx context.Context, upk keybase1.UserPlusKeysV2AllIncarnations) (
UserInfo, error) {
verifyingKeys, cryptPublicKeys, kidNames, err := filterKeys(
upk.Current.DeviceKeys)
if err != nil {
return UserInfo{}, err
}
revokedVerifyingKeys, revokedCryptPublicKeys, revokedKidNames, err :=
k.filterRevokedKeys(
ctx, upk.Current.Uid, upk.Current.DeviceKeys, upk.Current.Reset)
if err != nil {
return UserInfo{}, err
}
if len(revokedKidNames) > 0 {
for k, v := range revokedKidNames {
kidNames[k] = v
}
}
for _, incarnation := range upk.PastIncarnations {
revokedVerifyingKeysPast, revokedCryptPublicKeysPast,
revokedKidNames, err :=
k.filterRevokedKeys(
ctx, incarnation.Uid, incarnation.DeviceKeys, incarnation.Reset)
if err != nil {
return UserInfo{}, err
}
if len(revokedKidNames) > 0 {
for k, v := range revokedKidNames {
kidNames[k] = v
}
}
for k, v := range revokedVerifyingKeysPast {
revokedVerifyingKeys[k] = v
}
for k, v := range revokedCryptPublicKeysPast {
revokedCryptPublicKeys[k] = v
}
}
u := UserInfo{
Name: kbname.NewNormalizedUsername(
upk.Current.Username),
UID: upk.Current.Uid,
VerifyingKeys: verifyingKeys,
CryptPublicKeys: cryptPublicKeys,
KIDNames: kidNames,
EldestSeqno: upk.Current.EldestSeqno,
RevokedVerifyingKeys: revokedVerifyingKeys,
RevokedCryptPublicKeys: revokedCryptPublicKeys,
}
k.setCachedUserInfo(upk.Current.Uid, u)
return u, nil
}
func (k *KeybaseServiceBase) getCachedCurrentSessionOrInProgressCh() (
cachedSession SessionInfo, inProgressCh chan struct{}, doRPC bool) {
k.sessionCacheLock.Lock()
defer k.sessionCacheLock.Unlock()
if k.cachedCurrentSession != (SessionInfo{}) {
return k.cachedCurrentSession, nil, false
}
// If someone already started the RPC, wait for them (and release
// the lock).
if k.sessionInProgressCh != nil {
return SessionInfo{}, k.sessionInProgressCh, false
}
k.sessionInProgressCh = make(chan struct{})
return SessionInfo{}, k.sessionInProgressCh, true
}
func (k *KeybaseServiceBase) getCurrentSession(
ctx context.Context, sessionID int) (SessionInfo, bool, error) {
var cachedCurrentSession SessionInfo
var inProgressCh chan struct{}
doRPC := false
// Loop until either we have the session info, or until we are the
// sole goroutine that needs to make the RPC. Avoid holding the
// session cache lock during the RPC, since that can result in a
// deadlock if the RPC results in a call to `clearCaches()`.
for !doRPC {
cachedCurrentSession, inProgressCh, doRPC =
k.getCachedCurrentSessionOrInProgressCh()
if cachedCurrentSession != (SessionInfo{}) {
return cachedCurrentSession, false, nil
}
if !doRPC {
// Wait for another goroutine to finish the RPC.
select {
case <-inProgressCh:
case <-ctx.Done():
return SessionInfo{}, false, ctx.Err()
}
}
}
var s SessionInfo
// Close and clear the in-progress channel, even on an error.
defer func() {
k.sessionCacheLock.Lock()
defer k.sessionCacheLock.Unlock()
k.cachedCurrentSession = s
close(k.sessionInProgressCh)
k.sessionInProgressCh = nil
}()
res, err := k.sessionClient.CurrentSession(ctx, sessionID)
if err != nil {
if _, ok := err.(libkb.NoSessionError); ok {
// Use an error with a proper OS error code attached to it.
err = NoCurrentSessionError{}
}
return SessionInfo{}, false, err
}
s, err = SessionInfoFromProtocol(res)
if err != nil {
return SessionInfo{}, false, err
}
k.log.CDebugf(
ctx, "new session with username %s, uid %s, crypt public key %s, and verifying key %s",
s.Name, s.UID, s.CryptPublicKey, s.VerifyingKey)
return s, true, nil
}
// CurrentSession implements the KeybaseService interface for KeybaseServiceBase.
func (k *KeybaseServiceBase) CurrentSession(ctx context.Context, sessionID int) (
SessionInfo, error) {
s, newSession, err := k.getCurrentSession(ctx, sessionID)
if err != nil {
return SessionInfo{}, err
}
if newSession && k.config != nil {
// Don't hold the lock while calling `serviceLoggedIn`.
_ = serviceLoggedIn(ctx, k.config, s, TLFJournalBackgroundWorkEnabled)
}
return s, nil
}
// FavoriteAdd implements the KeybaseService interface for KeybaseServiceBase.
func (k *KeybaseServiceBase) FavoriteAdd(ctx context.Context, folder keybase1.Folder) error {
return k.favoriteClient.FavoriteAdd(ctx, keybase1.FavoriteAddArg{Folder: folder})
}
// FavoriteDelete implements the KeybaseService interface for KeybaseServiceBase.
func (k *KeybaseServiceBase) FavoriteDelete(ctx context.Context, folder keybase1.Folder) error {
return k.favoriteClient.FavoriteIgnore(ctx,
keybase1.FavoriteIgnoreArg{Folder: folder})
}
// FavoriteList implements the KeybaseService interface for KeybaseServiceBase.
func (k *KeybaseServiceBase) FavoriteList(ctx context.Context, sessionID int) ([]keybase1.Folder, error) {
results, err := k.favoriteClient.GetFavorites(ctx, sessionID)
if err != nil {
return nil, err
}
return results.FavoriteFolders, nil
}
// Notify implements the KeybaseService interface for KeybaseServiceBase.
func (k *KeybaseServiceBase) Notify(ctx context.Context, notification *keybase1.FSNotification) error {
// Reduce log spam by not repeating log lines for
// notifications with the same filename.
//
// TODO: Only do this in debug mode.
func() {
k.lastNotificationFilenameLock.Lock()
defer k.lastNotificationFilenameLock.Unlock()
if notification.Filename != k.lastNotificationFilename {
k.lastNotificationFilename = notification.Filename
k.log.CDebugf(ctx, "Sending notification for %s", notification.Filename)
}
}()
return k.kbfsClient.FSEvent(ctx, *notification)
}
// NotifyPathUpdated implements the KeybaseService interface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) NotifyPathUpdated(
ctx context.Context, path string) error {
// Reduce log spam by not repeating log lines for
// notifications with the same filename.
//
// TODO: Only do this in debug mode.
func() {
k.lastNotificationFilenameLock.Lock()
defer k.lastNotificationFilenameLock.Unlock()
if path != k.lastPathUpdated {
k.lastPathUpdated = path
k.log.CDebugf(ctx, "Sending path updated notification for %s", path)
}
}()
return k.kbfsClient.FSPathUpdate(ctx, path)
}
// NotifySyncStatus implements the KeybaseService interface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) NotifySyncStatus(ctx context.Context,
status *keybase1.FSPathSyncStatus) error {
// Reduce log spam by not repeating log lines for
// notifications with the same pathname.
//
// TODO: Only do this in debug mode.
func() {
k.lastNotificationFilenameLock.Lock()
defer k.lastNotificationFilenameLock.Unlock()
if status.Path != k.lastSyncNotificationPath {
k.lastSyncNotificationPath = status.Path
k.log.CDebugf(ctx, "Sending notification for %s", status.Path)
}
}()
return k.kbfsClient.FSSyncEvent(ctx, *status)
}
// FlushUserFromLocalCache implements the KeybaseService interface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) FlushUserFromLocalCache(ctx context.Context,
uid keybase1.UID) {
k.log.CDebugf(ctx, "Flushing cache for user %s", uid)
k.setCachedUserInfo(uid, UserInfo{})
}
// CtxKeybaseServiceTagKey is the type used for unique context tags
// used while servicing incoming keybase requests.
type CtxKeybaseServiceTagKey int
const (
// CtxKeybaseServiceIDKey is the type of the tag for unique
// operation IDs used while servicing incoming keybase requests.
CtxKeybaseServiceIDKey CtxKeybaseServiceTagKey = iota
)
// CtxKeybaseServiceOpID is the display name for the unique operation
// enqueued rekey ID tag.
const CtxKeybaseServiceOpID = "KSID"
// FSEditListRequest implements keybase1.NotifyFSRequestInterface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) FSEditListRequest(ctx context.Context,
req keybase1.FSEditListRequest) (err error) {
ctx = CtxWithRandomIDReplayable(ctx, CtxKeybaseServiceIDKey, CtxKeybaseServiceOpID,
k.log)
k.log.CDebugf(ctx, "Edit list request for %s (public: %t)",
req.Folder.Name, !req.Folder.Private)
tlfHandle, err := getHandleFromFolderName(
ctx, k.config.KBPKI(), k.config.MDOps(), req.Folder.Name,
!req.Folder.Private)
if err != nil {
return err
}
rootNode, _, err := k.config.KBFSOps().
GetOrCreateRootNode(ctx, tlfHandle, MasterBranch)
if err != nil {
return err
}
history, err := k.config.KBFSOps().GetEditHistory(ctx,
rootNode.GetFolderBranch())
if err != nil {
return err
}
// TODO(KBFS-2996) Convert the edits to an RPC response.
resp := keybase1.FSEditListArg{
RequestID: req.RequestID,
Edits: history,
}
k.log.CDebugf(ctx, "Sending edit history response with %d writer clusters",
len(resp.Edits.History))
return k.kbfsClient.FSEditList(ctx, resp)
}
// FSSyncStatusRequest implements keybase1.NotifyFSRequestInterface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) FSSyncStatusRequest(ctx context.Context,
req keybase1.FSSyncStatusRequest) (err error) {
k.log.CDebugf(ctx, "Got sync status request: %v", req)
resp := keybase1.FSSyncStatusArg{RequestID: req.RequestID}
// For now, just return the number of syncing bytes.
jServer, err := GetJournalServer(k.config)
if err == nil {
status, _ := jServer.Status(ctx)
resp.Status.TotalSyncingBytes = status.UnflushedBytes
k.log.CDebugf(ctx, "Sending sync status response with %d syncing bytes",
status.UnflushedBytes)
} else {
k.log.CDebugf(ctx, "No journal server, sending empty response")
}
return k.kbfsClient.FSSyncStatus(ctx, resp)
}
// TeamChangedByID implements keybase1.NotifyTeamInterface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) TeamChangedByID(ctx context.Context,
arg keybase1.TeamChangedByIDArg) error {
k.log.CDebugf(ctx, "Flushing cache for team %s "+
"(membershipChange=%t, keyRotated=%t, renamed=%t)",
arg.TeamID, arg.Changes.MembershipChanged,
arg.Changes.KeyRotated, arg.Changes.Renamed)
k.setCachedTeamInfo(arg.TeamID, TeamInfo{})
if arg.Changes.Renamed {
k.config.KBFSOps().TeamNameChanged(ctx, arg.TeamID)
}
return nil
}
// TeamChangedByName implements keybase1.NotifyTeamInterface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) TeamChangedByName(ctx context.Context,
arg keybase1.TeamChangedByNameArg) error {
// ignore
return nil
}
// TeamDeleted implements keybase1.NotifyTeamInterface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) TeamDeleted(ctx context.Context,
teamID keybase1.TeamID) error {
return nil
}
// TeamExit implements keybase1.NotifyTeamInterface for KeybaseServiceBase.
func (k *KeybaseDaemonRPC) TeamExit(context.Context, keybase1.TeamID) error {
return nil
}
// NewlyAddedToTeam implements keybase1.NotifyTeamInterface for
// KeybaseServiceBase.
func (k *KeybaseDaemonRPC) NewlyAddedToTeam(context.Context, keybase1.TeamID) error {
return nil
}
// TeamAbandoned implements keybase1.NotifyTeamInterface for KeybaseServiceBase.
func (k *KeybaseDaemonRPC) TeamAbandoned(
ctx context.Context, tid keybase1.TeamID) error {
k.log.CDebugf(ctx, "Implicit team %s abandoned", tid)
k.setCachedTeamInfo(tid, TeamInfo{})
k.config.KBFSOps().TeamAbandoned(ctx, tid)
return nil
}
// AvatarUpdated implements keybase1.NotifyTeamInterface for KeybaseServiceBase.
func (k *KeybaseDaemonRPC) AvatarUpdated(ctx context.Context,
arg keybase1.AvatarUpdatedArg) error {
return nil
}
// StartMigration implements keybase1.ImplicitTeamMigrationInterface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) StartMigration(ctx context.Context,
folder keybase1.Folder) (err error) {
mdServer := k.config.MDServer()
if mdServer == nil {
return errors.New("no mdserver")
}
// Making a favorite here to reuse the code that converts from
// `keybase1.FolderType` into `tlf.Type`.
fav := NewFavoriteFromFolder(folder)
handle, err := GetHandleFromFolderNameAndType(ctx, k.config.KBPKI(), k.config.MDOps(), fav.Name, fav.Type)
if err != nil {
return err
}
return k.config.MDServer().StartImplicitTeamMigration(ctx, handle.TlfID())
}
// FinalizeMigration implements keybase1.ImplicitTeamMigrationInterface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) FinalizeMigration(ctx context.Context,
folder keybase1.Folder) (err error) {
fav := NewFavoriteFromFolder(folder)
handle, err := GetHandleFromFolderNameAndType(
ctx, k.config.KBPKI(), k.config.MDOps(), fav.Name, fav.Type)
if err != nil {
return err
}
return k.config.KBFSOps().MigrateToImplicitTeam(ctx, handle.TlfID())
}
// GetTLFCryptKeys implements the TlfKeysInterface interface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) GetTLFCryptKeys(ctx context.Context,
query keybase1.TLFQuery) (res keybase1.GetTLFCryptKeysRes, err error) {
if ctx, err = makeExtendedIdentify(
CtxWithRandomIDReplayable(ctx,
CtxKeybaseServiceIDKey, CtxKeybaseServiceOpID, k.log),
query.IdentifyBehavior,
); err != nil {
return keybase1.GetTLFCryptKeysRes{}, err
}
tlfHandle, err := getHandleFromFolderName(
ctx, k.config.KBPKI(), k.config.MDOps(), query.TlfName, false)
if err != nil {
return res, err
}
res.NameIDBreaks.CanonicalName = keybase1.CanonicalTlfName(
tlfHandle.GetCanonicalName())
keys, id, err := k.config.KBFSOps().GetTLFCryptKeys(ctx, tlfHandle)
if err != nil {
return res, err
}
res.NameIDBreaks.TlfID = keybase1.TLFID(id.String())
for i, key := range keys {
res.CryptKeys = append(res.CryptKeys, keybase1.CryptKey{
KeyGeneration: int(kbfsmd.FirstValidKeyGen) + i,
Key: keybase1.Bytes32(key.Data()),
})
}
if query.IdentifyBehavior.WarningInsteadOfErrorOnBrokenTracks() {
res.NameIDBreaks.Breaks = getExtendedIdentify(ctx).getTlfBreakAndClose()
}
return res, nil
}
// GetPublicCanonicalTLFNameAndID implements the TlfKeysInterface interface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) GetPublicCanonicalTLFNameAndID(
ctx context.Context, query keybase1.TLFQuery) (
res keybase1.CanonicalTLFNameAndIDWithBreaks, err error) {
if ctx, err = makeExtendedIdentify(
CtxWithRandomIDReplayable(ctx,
CtxKeybaseServiceIDKey, CtxKeybaseServiceOpID, k.log),
query.IdentifyBehavior,
); err != nil {
return keybase1.CanonicalTLFNameAndIDWithBreaks{}, err
}
tlfHandle, err := getHandleFromFolderName(
ctx, k.config.KBPKI(), k.config.MDOps(), query.TlfName,
true /* public */)
if err != nil {
return res, err
}
res.CanonicalName = keybase1.CanonicalTlfName(
tlfHandle.GetCanonicalName())
id, err := k.config.KBFSOps().GetTLFID(ctx, tlfHandle)
if err != nil {
return res, err
}
res.TlfID = keybase1.TLFID(id.String())
if query.IdentifyBehavior.WarningInsteadOfErrorOnBrokenTracks() {
res.Breaks = getExtendedIdentify(ctx).getTlfBreakAndClose()
}
return res, nil
}
// EstablishMountDir asks the service for the current mount path
func (k *KeybaseServiceBase) EstablishMountDir(ctx context.Context) (
string, error) {
dir, err := k.kbfsMountClient.GetCurrentMountDir(ctx)
if err != nil {
k.log.CInfof(ctx, "GetCurrentMountDir fails - ", err)
return "", err
}
if dir == "" {
dirs, err := k.kbfsMountClient.GetAllAvailableMountDirs(ctx)
if err != nil {
k.log.CInfof(ctx, "GetAllAvailableMountDirs fails - ", err)
return "", err
}
dir, err = chooseDefaultMount(ctx, dirs, k.log)
if err != nil {
k.log.CInfof(ctx, "chooseDefaultMount fails - ", err)
return "", err
}
err2 := k.kbfsMountClient.SetCurrentMountDir(ctx, dir)
if err2 != nil {
k.log.CInfof(ctx, "SetCurrentMountDir fails - ", err2)
}
// Continue mounting even if we can't save the mount
k.log.CDebugf(ctx, "Choosing mountdir %s from %v", dir, dirs)
}
return dir, err
}
// PutGitMetadata implements the KeybaseService interface for
// KeybaseServiceBase.
func (k *KeybaseServiceBase) PutGitMetadata(
ctx context.Context, folder keybase1.Folder, repoID keybase1.RepoID,
metadata keybase1.GitLocalMetadata) error {
return k.gitClient.PutGitMetadata(ctx, keybase1.PutGitMetadataArg{
Folder: folder,
RepoID: repoID,
Metadata: metadata,
})
}
| 1 | 20,182 | I'd rather you do this under `if info.filledInMerkle {` since that's the only place it's relevant. | keybase-kbfs | go |
@@ -344,13 +344,8 @@ public class RecoveryStrategy implements Runnable, Closeable {
// though
try {
CloudDescriptor cloudDesc = this.coreDescriptor.getCloudDescriptor();
- ZkNodeProps leaderprops = zkStateReader.getLeaderRetry(
- cloudDesc.getCollectionName(), cloudDesc.getShardId());
- final String leaderBaseUrl = leaderprops.getStr(ZkStateReader.BASE_URL_PROP);
- final String leaderCoreName = leaderprops.getStr(ZkStateReader.CORE_NAME_PROP);
-
- String leaderUrl = ZkCoreNodeProps.getCoreUrl(leaderBaseUrl, leaderCoreName);
-
+ ZkNodeProps leaderprops = zkStateReader.getLeaderRetry(cloudDesc.getCollectionName(), cloudDesc.getShardId());
+ String leaderUrl = ZkCoreNodeProps.getCoreUrl(leaderprops);
String ourUrl = ZkCoreNodeProps.getCoreUrl(baseUrl, coreName);
boolean isLeader = leaderUrl.equals(ourUrl); // TODO: We can probably delete most of this code if we say this | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.cloud;
import java.io.Closeable;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.store.Directory;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient.HttpUriRequestResponse;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.request.CoreAdminRequest.WaitForState;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.SolrPingResponse;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.ZkCoreNodeProps;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.cloud.ZooKeeperException;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.UpdateParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.DirectoryFactory.DirContext;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.ReplicationHandler;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.update.CommitUpdateCommand;
import org.apache.solr.update.PeerSyncWithLeader;
import org.apache.solr.update.UpdateLog;
import org.apache.solr.update.UpdateLog.RecoveryInfo;
import org.apache.solr.update.UpdateShardHandlerConfig;
import org.apache.solr.util.RefCounted;
import org.apache.solr.util.SolrPluginUtils;
import org.apache.solr.util.plugin.NamedListInitializedPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class may change in future and customisations are not supported between versions in terms of API or back compat
* behaviour.
*
* @lucene.experimental
*/
public class RecoveryStrategy implements Runnable, Closeable {
public static class Builder implements NamedListInitializedPlugin {
@SuppressWarnings({"rawtypes"})
private NamedList args;
@Override
public void init(@SuppressWarnings({"rawtypes"})NamedList args) {
this.args = args;
}
// this should only be used from SolrCoreState
@SuppressWarnings({"unchecked"})
public RecoveryStrategy create(CoreContainer cc, CoreDescriptor cd,
RecoveryStrategy.RecoveryListener recoveryListener) {
final RecoveryStrategy recoveryStrategy = newRecoveryStrategy(cc, cd, recoveryListener);
SolrPluginUtils.invokeSetters(recoveryStrategy, args);
return recoveryStrategy;
}
protected RecoveryStrategy newRecoveryStrategy(CoreContainer cc, CoreDescriptor cd,
RecoveryStrategy.RecoveryListener recoveryListener) {
return new RecoveryStrategy(cc, cd, recoveryListener);
}
}
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private int waitForUpdatesWithStaleStatePauseMilliSeconds = Integer
.getInteger("solr.cloud.wait-for-updates-with-stale-state-pause", 2500);
private int maxRetries = 500;
private int startingRecoveryDelayMilliSeconds = 2000;
public static interface RecoveryListener {
public void recovered();
public void failed();
}
private volatile boolean close = false;
private RecoveryListener recoveryListener;
private ZkController zkController;
private String baseUrl;
private String coreZkNodeName;
private ZkStateReader zkStateReader;
private volatile String coreName;
private int retries;
private boolean recoveringAfterStartup;
private CoreContainer cc;
private volatile HttpUriRequest prevSendPreRecoveryHttpUriRequest;
private final Replica.Type replicaType;
private CoreDescriptor coreDescriptor;
protected RecoveryStrategy(CoreContainer cc, CoreDescriptor cd, RecoveryListener recoveryListener) {
this.cc = cc;
this.coreName = cd.getName();
this.recoveryListener = recoveryListener;
zkController = cc.getZkController();
zkStateReader = zkController.getZkStateReader();
baseUrl = zkController.getBaseUrl();
coreZkNodeName = cd.getCloudDescriptor().getCoreNodeName();
replicaType = cd.getCloudDescriptor().getReplicaType();
}
final public int getWaitForUpdatesWithStaleStatePauseMilliSeconds() {
return waitForUpdatesWithStaleStatePauseMilliSeconds;
}
final public void setWaitForUpdatesWithStaleStatePauseMilliSeconds(
int waitForUpdatesWithStaleStatePauseMilliSeconds) {
this.waitForUpdatesWithStaleStatePauseMilliSeconds = waitForUpdatesWithStaleStatePauseMilliSeconds;
}
final public int getMaxRetries() {
return maxRetries;
}
final public void setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
}
final public int getStartingRecoveryDelayMilliSeconds() {
return startingRecoveryDelayMilliSeconds;
}
final public void setStartingRecoveryDelayMilliSeconds(int startingRecoveryDelayMilliSeconds) {
this.startingRecoveryDelayMilliSeconds = startingRecoveryDelayMilliSeconds;
}
final public boolean getRecoveringAfterStartup() {
return recoveringAfterStartup;
}
final public void setRecoveringAfterStartup(boolean recoveringAfterStartup) {
this.recoveringAfterStartup = recoveringAfterStartup;
}
/** Builds a new HttpSolrClient for use in recovery. Caller must close */
private final HttpSolrClient buildRecoverySolrClient(final String leaderUrl) {
// workaround for SOLR-13605: get the configured timeouts & set them directly
// (even though getRecoveryOnlyHttpClient() already has them set)
final UpdateShardHandlerConfig cfg = cc.getConfig().getUpdateShardHandlerConfig();
return (new HttpSolrClient.Builder(leaderUrl)
.withConnectionTimeout(cfg.getDistributedConnectionTimeout())
.withSocketTimeout(cfg.getDistributedSocketTimeout())
.withHttpClient(cc.getUpdateShardHandler().getRecoveryOnlyHttpClient())
).build();
}
// make sure any threads stop retrying
@Override
final public void close() {
close = true;
if (prevSendPreRecoveryHttpUriRequest != null) {
prevSendPreRecoveryHttpUriRequest.abort();
}
log.warn("Stopping recovery for core=[{}] coreNodeName=[{}]", coreName, coreZkNodeName);
}
final private void recoveryFailed(final SolrCore core,
final ZkController zkController, final String baseUrl,
final String shardZkNodeName, final CoreDescriptor cd) throws Exception {
SolrException.log(log, "Recovery failed - I give up.");
try {
zkController.publish(cd, Replica.State.RECOVERY_FAILED);
} finally {
close();
recoveryListener.failed();
}
}
/**
* This method may change in future and customisations are not supported between versions in terms of API or back
* compat behaviour.
*
* @lucene.experimental
*/
protected String getReplicateLeaderUrl(ZkNodeProps leaderprops) {
return new ZkCoreNodeProps(leaderprops).getCoreUrl();
}
final private void replicate(String nodeName, SolrCore core, ZkNodeProps leaderprops)
throws SolrServerException, IOException {
final String leaderUrl = getReplicateLeaderUrl(leaderprops);
log.info("Attempting to replicate from [{}].", leaderUrl);
// send commit
commitOnLeader(leaderUrl);
// use rep handler directly, so we can do this sync rather than async
SolrRequestHandler handler = core.getRequestHandler(ReplicationHandler.PATH);
ReplicationHandler replicationHandler = (ReplicationHandler) handler;
if (replicationHandler == null) {
throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE,
"Skipping recovery, no " + ReplicationHandler.PATH + " handler found");
}
ModifiableSolrParams solrParams = new ModifiableSolrParams();
solrParams.set(ReplicationHandler.LEADER_URL, leaderUrl);
solrParams.set(ReplicationHandler.SKIP_COMMIT_ON_LEADER_VERSION_ZERO, replicaType == Replica.Type.TLOG);
if (isClosed()) return; // we check closed on return
boolean success = replicationHandler.doFetch(solrParams, false).getSuccessful();
if (!success) {
throw new SolrException(ErrorCode.SERVER_ERROR, "Replication for recovery failed.");
}
// solrcloud_debug
if (log.isDebugEnabled()) {
try {
RefCounted<SolrIndexSearcher> searchHolder = core
.getNewestSearcher(false);
SolrIndexSearcher searcher = searchHolder.get();
Directory dir = core.getDirectoryFactory().get(core.getIndexDir(), DirContext.META_DATA, null);
try {
final IndexCommit commit = core.getDeletionPolicy().getLatestCommit();
if (log.isDebugEnabled()) {
log.debug("{} replicated {} from {} gen: {} data: {} index: {} newIndex: {} files: {}"
, core.getCoreContainer().getZkController().getNodeName()
, searcher.count(new MatchAllDocsQuery())
, leaderUrl
, (null == commit ? "null" : commit.getGeneration())
, core.getDataDir()
, core.getIndexDir()
, core.getNewIndexDir()
, Arrays.asList(dir.listAll()));
}
} finally {
core.getDirectoryFactory().release(dir);
searchHolder.decref();
}
} catch (Exception e) {
log.debug("Error in solrcloud_debug block", e);
}
}
}
final private void commitOnLeader(String leaderUrl) throws SolrServerException,
IOException {
try (HttpSolrClient client = buildRecoverySolrClient(leaderUrl)) {
UpdateRequest ureq = new UpdateRequest();
ureq.setParams(new ModifiableSolrParams());
// ureq.getParams().set(DistributedUpdateProcessor.COMMIT_END_POINT, true);
// ureq.getParams().set(UpdateParams.OPEN_SEARCHER, onlyLeaderIndexes);// Why do we need to open searcher if
// "onlyLeaderIndexes"?
ureq.getParams().set(UpdateParams.OPEN_SEARCHER, false);
ureq.setAction(AbstractUpdateRequest.ACTION.COMMIT, false, true).process(
client);
}
}
@Override
final public void run() {
// set request info for logging
try (SolrCore core = cc.getCore(coreName)) {
if (core == null) {
SolrException.log(log, "SolrCore not found - cannot recover:" + coreName);
return;
}
log.info("Starting recovery process. recoveringAfterStartup={}", recoveringAfterStartup);
try {
doRecovery(core);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
SolrException.log(log, "", e);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
} catch (Exception e) {
log.error("", e);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
}
}
}
final public void doRecovery(SolrCore core) throws Exception {
// we can lose our core descriptor, so store it now
this.coreDescriptor = core.getCoreDescriptor();
if (this.coreDescriptor.getCloudDescriptor().requiresTransactionLog()) {
doSyncOrReplicateRecovery(core);
} else {
doReplicateOnlyRecovery(core);
}
}
final private void doReplicateOnlyRecovery(SolrCore core) throws InterruptedException {
boolean successfulRecovery = false;
// if (core.getUpdateHandler().getUpdateLog() != null) {
// SolrException.log(log, "'replicate-only' recovery strategy should only be used if no update logs are present, but
// this core has one: "
// + core.getUpdateHandler().getUpdateLog());
// return;
// }
while (!successfulRecovery && !Thread.currentThread().isInterrupted() && !isClosed()) { // don't use interruption or
// it will close channels
// though
try {
CloudDescriptor cloudDesc = this.coreDescriptor.getCloudDescriptor();
ZkNodeProps leaderprops = zkStateReader.getLeaderRetry(
cloudDesc.getCollectionName(), cloudDesc.getShardId());
final String leaderBaseUrl = leaderprops.getStr(ZkStateReader.BASE_URL_PROP);
final String leaderCoreName = leaderprops.getStr(ZkStateReader.CORE_NAME_PROP);
String leaderUrl = ZkCoreNodeProps.getCoreUrl(leaderBaseUrl, leaderCoreName);
String ourUrl = ZkCoreNodeProps.getCoreUrl(baseUrl, coreName);
boolean isLeader = leaderUrl.equals(ourUrl); // TODO: We can probably delete most of this code if we say this
// strategy can only be used for pull replicas
if (isLeader && !cloudDesc.isLeader()) {
throw new SolrException(ErrorCode.SERVER_ERROR, "Cloud state still says we are leader.");
}
if (cloudDesc.isLeader()) {
assert cloudDesc.getReplicaType() != Replica.Type.PULL;
// we are now the leader - no one else must have been suitable
log.warn("We have not yet recovered - but we are now the leader!");
log.info("Finished recovery process.");
zkController.publish(this.coreDescriptor, Replica.State.ACTIVE);
return;
}
if (log.isInfoEnabled()) {
log.info("Publishing state of core [{}] as recovering, leader is [{}] and I am [{}]", core.getName(), leaderUrl,
ourUrl);
}
zkController.publish(this.coreDescriptor, Replica.State.RECOVERING);
if (isClosed()) {
if (log.isInfoEnabled()) {
log.info("Recovery for core {} has been closed", core.getName());
}
break;
}
log.info("Starting Replication Recovery.");
try {
log.info("Stopping background replicate from leader process");
zkController.stopReplicationFromLeader(coreName);
replicate(zkController.getNodeName(), core, leaderprops);
if (isClosed()) {
if (log.isInfoEnabled()) {
log.info("Recovery for core {} has been closed", core.getName());
}
break;
}
log.info("Replication Recovery was successful.");
successfulRecovery = true;
} catch (Exception e) {
SolrException.log(log, "Error while trying to recover", e);
}
} catch (Exception e) {
SolrException.log(log, "Error while trying to recover. core=" + coreName, e);
} finally {
if (successfulRecovery) {
log.info("Restarting background replicate from leader process");
zkController.startReplicationFromLeader(coreName, false);
log.info("Registering as Active after recovery.");
try {
zkController.publish(this.coreDescriptor, Replica.State.ACTIVE);
} catch (Exception e) {
log.error("Could not publish as ACTIVE after succesful recovery", e);
successfulRecovery = false;
}
if (successfulRecovery) {
close = true;
recoveryListener.recovered();
}
}
}
if (!successfulRecovery) {
// lets pause for a moment and we need to try again...
// TODO: we don't want to retry for some problems?
// Or do a fall off retry...
try {
if (isClosed()) {
if (log.isInfoEnabled()) {
log.info("Recovery for core {} has been closed", core.getName());
}
break;
}
log.error("Recovery failed - trying again... ({})", retries);
retries++;
if (retries >= maxRetries) {
SolrException.log(log, "Recovery failed - max retries exceeded (" + retries + ").");
try {
recoveryFailed(core, zkController, baseUrl, coreZkNodeName, this.coreDescriptor);
} catch (Exception e) {
SolrException.log(log, "Could not publish that recovery failed", e);
}
break;
}
} catch (Exception e) {
SolrException.log(log, "An error has occurred during recovery", e);
}
try {
// Wait an exponential interval between retries, start at 5 seconds and work up to a minute.
// If we're at attempt >= 4, there's no point computing pow(2, retries) because the result
// will always be the minimum of the two (12). Since we sleep at 5 seconds sub-intervals in
// order to check if we were closed, 12 is chosen as the maximum loopCount (5s * 12 = 1m).
int loopCount = retries < 4 ? (int) Math.min(Math.pow(2, retries), 12) : 12;
if (log.isInfoEnabled()) {
log.info("Wait [{}] seconds before trying to recover again (attempt={})",
TimeUnit.MILLISECONDS.toSeconds(loopCount * startingRecoveryDelayMilliSeconds), retries);
}
for (int i = 0; i < loopCount; i++) {
if (isClosed()) {
if (log.isInfoEnabled()) {
log.info("Recovery for core {} has been closed", core.getName());
}
break; // check if someone closed us
}
Thread.sleep(startingRecoveryDelayMilliSeconds);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Recovery was interrupted.", e);
close = true;
}
}
}
// We skip core.seedVersionBuckets(); We don't have a transaction log
log.info("Finished recovery process, successful=[{}]", successfulRecovery);
}
// TODO: perhaps make this grab a new core each time through the loop to handle core reloads?
public final void doSyncOrReplicateRecovery(SolrCore core) throws Exception {
boolean successfulRecovery = false;
UpdateLog ulog;
ulog = core.getUpdateHandler().getUpdateLog();
if (ulog == null) {
SolrException.log(log, "No UpdateLog found - cannot recover.");
recoveryFailed(core, zkController, baseUrl, coreZkNodeName,
this.coreDescriptor);
return;
}
// we temporary ignore peersync for tlog replicas
boolean firstTime = replicaType != Replica.Type.TLOG;
List<Long> recentVersions;
try (UpdateLog.RecentUpdates recentUpdates = ulog.getRecentUpdates()) {
recentVersions = recentUpdates.getVersions(ulog.getNumRecordsToKeep());
} catch (Exception e) {
SolrException.log(log, "Corrupt tlog - ignoring.", e);
recentVersions = new ArrayList<>(0);
}
List<Long> startingVersions = ulog.getStartingVersions();
if (startingVersions != null && recoveringAfterStartup) {
try {
int oldIdx = 0; // index of the start of the old list in the current list
long firstStartingVersion = startingVersions.size() > 0 ? startingVersions.get(0) : 0;
for (; oldIdx < recentVersions.size(); oldIdx++) {
if (recentVersions.get(oldIdx) == firstStartingVersion) break;
}
if (oldIdx > 0) {
log.info("Found new versions added after startup: num=[{}]", oldIdx);
if (log.isInfoEnabled()) {
log.info("currentVersions size={} range=[{} to {}]", recentVersions.size(), recentVersions.get(0),
recentVersions.get(recentVersions.size() - 1));
}
}
if (startingVersions.isEmpty()) {
log.info("startupVersions is empty");
} else {
if (log.isInfoEnabled()) {
log.info("startupVersions size={} range=[{} to {}]", startingVersions.size(), startingVersions.get(0),
startingVersions.get(startingVersions.size() - 1));
}
}
} catch (Exception e) {
SolrException.log(log, "Error getting recent versions.", e);
recentVersions = new ArrayList<>(0);
}
}
if (recoveringAfterStartup) {
// if we're recovering after startup (i.e. we have been down), then we need to know what the last versions were
// when we went down. We may have received updates since then.
recentVersions = startingVersions;
try {
if (ulog.existOldBufferLog()) {
// this means we were previously doing a full index replication
// that probably didn't complete and buffering updates in the
// meantime.
log.info("Looks like a previous replication recovery did not complete - skipping peer sync.");
firstTime = false; // skip peersync
}
} catch (Exception e) {
SolrException.log(log, "Error trying to get ulog starting operation.", e);
firstTime = false; // skip peersync
}
}
if (replicaType == Replica.Type.TLOG) {
zkController.stopReplicationFromLeader(coreName);
}
final String ourUrl = ZkCoreNodeProps.getCoreUrl(baseUrl, coreName);
Future<RecoveryInfo> replayFuture = null;
while (!successfulRecovery && !Thread.currentThread().isInterrupted() && !isClosed()) { // don't use interruption or
// it will close channels
// though
try {
CloudDescriptor cloudDesc = this.coreDescriptor.getCloudDescriptor();
final Replica leader = pingLeader(ourUrl, this.coreDescriptor, true);
if (isClosed()) {
log.info("RecoveryStrategy has been closed");
break;
}
boolean isLeader = leader.getCoreUrl().equals(ourUrl);
if (isLeader && !cloudDesc.isLeader()) {
throw new SolrException(ErrorCode.SERVER_ERROR, "Cloud state still says we are leader.");
}
if (cloudDesc.isLeader()) {
// we are now the leader - no one else must have been suitable
log.warn("We have not yet recovered - but we are now the leader!");
log.info("Finished recovery process.");
zkController.publish(this.coreDescriptor, Replica.State.ACTIVE);
return;
}
log.info("Begin buffering updates. core=[{}]", coreName);
// recalling buffer updates will drop the old buffer tlog
ulog.bufferUpdates();
if (log.isInfoEnabled()) {
log.info("Publishing state of core [{}] as recovering, leader is [{}] and I am [{}]", core.getName(),
leader.getCoreUrl(),
ourUrl);
}
zkController.publish(this.coreDescriptor, Replica.State.RECOVERING);
final Slice slice = zkStateReader.getClusterState().getCollection(cloudDesc.getCollectionName())
.getSlice(cloudDesc.getShardId());
try {
prevSendPreRecoveryHttpUriRequest.abort();
} catch (NullPointerException e) {
// okay
}
if (isClosed()) {
log.info("RecoveryStrategy has been closed");
break;
}
sendPrepRecoveryCmd(leader.getBaseUrl(), leader.getCoreName(), slice);
if (isClosed()) {
log.info("RecoveryStrategy has been closed");
break;
}
// we wait a bit so that any updates on the leader
// that started before they saw recovering state
// are sure to have finished (see SOLR-7141 for
// discussion around current value)
// TODO since SOLR-11216, we probably won't need this
try {
Thread.sleep(waitForUpdatesWithStaleStatePauseMilliSeconds);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// first thing we just try to sync
if (firstTime) {
firstTime = false; // only try sync the first time through the loop
if (log.isInfoEnabled()) {
log.info("Attempting to PeerSync from [{}] - recoveringAfterStartup=[{}]", leader.getCoreUrl(),
recoveringAfterStartup);
}
// System.out.println("Attempting to PeerSync from " + leaderUrl
// + " i am:" + zkController.getNodeName());
boolean syncSuccess;
try (PeerSyncWithLeader peerSyncWithLeader = new PeerSyncWithLeader(core,
leader.getCoreUrl(), ulog.getNumRecordsToKeep())) {
syncSuccess = peerSyncWithLeader.sync(recentVersions).isSuccess();
}
if (syncSuccess) {
SolrQueryRequest req = new LocalSolrQueryRequest(core,
new ModifiableSolrParams());
// force open a new searcher
core.getUpdateHandler().commit(new CommitUpdateCommand(req, false));
req.close();
log.info("PeerSync stage of recovery was successful.");
// solrcloud_debug
cloudDebugLog(core, "synced");
log.info("Replaying updates buffered during PeerSync.");
replayFuture = replay(core);
// sync success
successfulRecovery = true;
break;
}
log.info("PeerSync Recovery was not successful - trying replication.");
}
if (isClosed()) {
log.info("RecoveryStrategy has been closed");
break;
}
log.info("Starting Replication Recovery.");
try {
replicate(zkController.getNodeName(), core, leader);
if (isClosed()) {
log.info("RecoveryStrategy has been closed");
break;
}
replayFuture = replay(core);
if (isClosed()) {
log.info("RecoveryStrategy has been closed");
break;
}
log.info("Replication Recovery was successful.");
successfulRecovery = true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Recovery was interrupted", e);
close = true;
} catch (Exception e) {
SolrException.log(log, "Error while trying to recover", e);
}
} catch (Exception e) {
SolrException.log(log, "Error while trying to recover. core=" + coreName, e);
} finally {
if (successfulRecovery) {
log.info("Registering as Active after recovery.");
try {
if (replicaType == Replica.Type.TLOG) {
zkController.startReplicationFromLeader(coreName, true);
}
zkController.publish(this.coreDescriptor, Replica.State.ACTIVE);
} catch (Exception e) {
log.error("Could not publish as ACTIVE after succesful recovery", e);
successfulRecovery = false;
}
if (successfulRecovery) {
close = true;
recoveryListener.recovered();
}
}
}
if (!successfulRecovery) {
// lets pause for a moment and we need to try again...
// TODO: we don't want to retry for some problems?
// Or do a fall off retry...
try {
if (isClosed()) {
log.info("RecoveryStrategy has been closed");
break;
}
log.error("Recovery failed - trying again... ({})", retries);
retries++;
if (retries >= maxRetries) {
SolrException.log(log, "Recovery failed - max retries exceeded (" + retries + ").");
try {
recoveryFailed(core, zkController, baseUrl, coreZkNodeName, this.coreDescriptor);
} catch (Exception e) {
SolrException.log(log, "Could not publish that recovery failed", e);
}
break;
}
} catch (Exception e) {
SolrException.log(log, "An error has occurred during recovery", e);
}
try {
// Wait an exponential interval between retries, start at 2 seconds and work up to a minute.
// Since we sleep at 2 seconds sub-intervals in
// order to check if we were closed, 30 is chosen as the maximum loopCount (2s * 30 = 1m).
double loopCount = Math.min(Math.pow(2, retries - 1), 30);
log.info("Wait [{}] seconds before trying to recover again (attempt={})",
loopCount * startingRecoveryDelayMilliSeconds, retries);
for (int i = 0; i < loopCount; i++) {
if (isClosed()) {
log.info("RecoveryStrategy has been closed");
break; // check if someone closed us
}
Thread.sleep(startingRecoveryDelayMilliSeconds);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Recovery was interrupted.", e);
close = true;
}
}
}
// if replay was skipped (possibly to due pulling a full index from the leader),
// then we still need to update version bucket seeds after recovery
if (successfulRecovery && replayFuture == null) {
log.info("Updating version bucket highest from index after successful recovery.");
core.seedVersionBuckets();
}
log.info("Finished recovery process, successful=[{}]", successfulRecovery);
}
private final Replica pingLeader(String ourUrl, CoreDescriptor coreDesc, boolean mayPutReplicaAsDown)
throws Exception {
int numTried = 0;
while (true) {
CloudDescriptor cloudDesc = coreDesc.getCloudDescriptor();
DocCollection docCollection = zkStateReader.getClusterState().getCollection(cloudDesc.getCollectionName());
if (!isClosed() && mayPutReplicaAsDown && numTried == 1 &&
docCollection.getReplica(coreDesc.getCloudDescriptor().getCoreNodeName())
.getState() == Replica.State.ACTIVE) {
// this operation may take a long time, by putting replica into DOWN state, client won't query this replica
zkController.publish(coreDesc, Replica.State.DOWN);
}
numTried++;
Replica leaderReplica = null;
if (isClosed()) {
return leaderReplica;
}
try {
leaderReplica = zkStateReader.getLeaderRetry(
cloudDesc.getCollectionName(), cloudDesc.getShardId());
} catch (SolrException e) {
Thread.sleep(500);
continue;
}
if (leaderReplica.getCoreUrl().equals(ourUrl)) {
return leaderReplica;
}
try (HttpSolrClient httpSolrClient = buildRecoverySolrClient(leaderReplica.getCoreUrl())) {
SolrPingResponse resp = httpSolrClient.ping();
return leaderReplica;
} catch (IOException e) {
log.error("Failed to connect leader {} on recovery, try again", leaderReplica.getBaseUrl());
Thread.sleep(500);
} catch (Exception e) {
if (e.getCause() instanceof IOException) {
log.error("Failed to connect leader {} on recovery, try again", leaderReplica.getBaseUrl());
Thread.sleep(500);
} else {
return leaderReplica;
}
}
}
}
public static Runnable testing_beforeReplayBufferingUpdates;
final private Future<RecoveryInfo> replay(SolrCore core)
throws InterruptedException, ExecutionException {
if (testing_beforeReplayBufferingUpdates != null) {
testing_beforeReplayBufferingUpdates.run();
}
if (replicaType == Replica.Type.TLOG) {
// roll over all updates during buffering to new tlog, make RTG available
SolrQueryRequest req = new LocalSolrQueryRequest(core,
new ModifiableSolrParams());
core.getUpdateHandler().getUpdateLog().copyOverBufferingUpdates(new CommitUpdateCommand(req, false));
req.close();
return null;
}
Future<RecoveryInfo> future = core.getUpdateHandler().getUpdateLog().applyBufferedUpdates();
if (future == null) {
// no replay needed\
log.info("No replay needed.");
} else {
log.info("Replaying buffered documents.");
// wait for replay
RecoveryInfo report = future.get();
if (report.failed) {
SolrException.log(log, "Replay failed");
throw new SolrException(ErrorCode.SERVER_ERROR, "Replay failed");
}
}
// the index may ahead of the tlog's caches after recovery, by calling this tlog's caches will be purged
core.getUpdateHandler().getUpdateLog().openRealtimeSearcher();
// solrcloud_debug
cloudDebugLog(core, "replayed");
return future;
}
final private void cloudDebugLog(SolrCore core, String op) {
if (!log.isDebugEnabled()) {
return;
}
try {
RefCounted<SolrIndexSearcher> searchHolder = core.getNewestSearcher(false);
SolrIndexSearcher searcher = searchHolder.get();
try {
final int totalHits = searcher.count(new MatchAllDocsQuery());
final String nodeName = core.getCoreContainer().getZkController().getNodeName();
log.debug("[{}] {} [{} total hits]", nodeName, op, totalHits);
} finally {
searchHolder.decref();
}
} catch (Exception e) {
log.debug("Error in solrcloud_debug block", e);
}
}
final public boolean isClosed() {
return close || cc.isShutDown();
}
final private void sendPrepRecoveryCmd(String leaderBaseUrl, String leaderCoreName, Slice slice)
throws SolrServerException, IOException, InterruptedException, ExecutionException {
WaitForState prepCmd = new WaitForState();
prepCmd.setCoreName(leaderCoreName);
prepCmd.setNodeName(zkController.getNodeName());
prepCmd.setCoreNodeName(coreZkNodeName);
prepCmd.setState(Replica.State.RECOVERING);
prepCmd.setCheckLive(true);
prepCmd.setOnlyIfLeader(true);
final Slice.State state = slice.getState();
if (state != Slice.State.CONSTRUCTION && state != Slice.State.RECOVERY && state != Slice.State.RECOVERY_FAILED) {
prepCmd.setOnlyIfLeaderActive(true);
}
int conflictWaitMs = zkController.getLeaderConflictResolveWait();
// timeout after 5 seconds more than the max timeout (conflictWait + 3 seconds) on the server side
int readTimeout = conflictWaitMs + Integer.parseInt(System.getProperty("prepRecoveryReadTimeoutExtraWait", "8000"));
try (HttpSolrClient client = buildRecoverySolrClient(leaderBaseUrl)) {
client.setSoTimeout(readTimeout);
HttpUriRequestResponse mrr = client.httpUriRequest(prepCmd);
prevSendPreRecoveryHttpUriRequest = mrr.httpUriRequest;
log.info("Sending prep recovery command to [{}]; [{}]", leaderBaseUrl, prepCmd);
mrr.future.get();
}
}
}
| 1 | 37,919 | *NULL_DEREFERENCE:* object `leaderUrl` last assigned on line 348 could be null and is dereferenced at line 351. | apache-lucene-solr | java |
@@ -38,9 +38,13 @@ class PlansController < ApplicationController
def create
@plan = Plan.new
authorize @plan
-
+
@plan.principal_investigator = current_user.surname.blank? ? nil : "#{current_user.firstname} #{current_user.surname}"
- @plan.data_contact = current_user.email
+ @plan.principal_investigator_email = current_user.email
+
+ orcid = current_user.identifier_for(IdentifierScheme.find_by(name: 'orcid'))
+ @plan.principal_investigator_identifier = orcid.identifier unless orcid.nil?
+
@plan.funder_name = plan_params[:funder_name]
@plan.visibility = (plan_params['visibility'].blank? ? Rails.application.config.default_plan_visibility : | 1 | class PlansController < ApplicationController
require 'pp'
helper SettingsTemplateHelper
after_action :verify_authorized, except: ['public_index', 'public_export']
def index
authorize Plan
@plans = current_user.plans
end
# GET /plans/public_index
# ------------------------------------------------------------------------------------
def public_index
@plans = Plan.publicly_visible
end
# GET /plans/new
# ------------------------------------------------------------------------------------
def new
@plan = Plan.new
authorize @plan
# Get all of the available funders and non-funder orgs
@funders = Org.funders.joins(:templates).where(templates: {published: true}).uniq.sort{|x,y| x.name <=> y.name }
@orgs = (Org.institutions + Org.managing_orgs).flatten.uniq.sort{|x,y| x.name <=> y.name }
# Get the current user's org
@default_org = current_user.org if @orgs.include?(current_user.org)
flash[:notice] = "#{_('This is a')} <strong>#{_('test plan')}</strong>" if params[:test]
@is_test = params[:test] ||= false
respond_to :html
end
# POST /plans
# -------------------------------------------------------------------
def create
@plan = Plan.new
authorize @plan
@plan.principal_investigator = current_user.surname.blank? ? nil : "#{current_user.firstname} #{current_user.surname}"
@plan.data_contact = current_user.email
@plan.funder_name = plan_params[:funder_name]
@plan.visibility = (plan_params['visibility'].blank? ? Rails.application.config.default_plan_visibility :
plan_params[:visibility])
# If a template hasn't been identified look for the available templates
if plan_params[:template_id].blank?
template_options(plan_params[:org_id], plan_params[:funder_id])
# Return the 'Select a template' section
respond_to do |format|
format.js {}
end
# Otherwise create the plan
else
@plan.template = Template.find(plan_params[:template_id])
if plan_params[:title].blank?
@plan.title = current_user.firstname.blank? ? _('My Plan') + '(' + @plan.template.title + ')' :
current_user.firstname + "'s" + _(" Plan")
else
@plan.title = plan_params[:title]
end
if @plan.save
@plan.assign_creator(current_user)
# pre-select org's guidance
ggs = GuidanceGroup.where(org_id: plan_params[:org_id],
optional_subset: false,
published: true)
if !ggs.blank? then @plan.guidance_groups << ggs end
default = Template.find_by(is_default: true)
msg = success_message(_('plan'), _('created'))
if !default.nil? && default == @plan.template
# We used the generic/default template
msg += _('This plan is based on the default template.')
elsif [email protected]_of.nil?
# We used a customized version of the the funder template
msg += "#{_('This plan is based on the')} #{plan_params[:funder_name]} #{_('template with customisations by the')} #{plan_params[:org_name]}"
else
# We used the specified org's or funder's template
msg += "#{_('This plan is based on the')} #{@plan.template.org.name} template."
end
flash[:notice] = msg
respond_to do |format|
format.js { render js: "window.location='#{plan_url(@plan)}?editing=true'" }
end
else
# Something went wrong so report the issue to the user
flash[:alert] = failed_create_error(@plan, 'Plan')
respond_to do |format|
format.js {}
end
end
end
end
# GET /plans/show
def show
@plan = Plan.eager_load(params[:id])
authorize @plan
@visibility = @plan.visibility.present? ? @plan.visibility.to_s : Rails.application.config.default_plan_visibility
@editing = (!params[:editing].nil? && @plan.administerable_by?(current_user.id))
# Get all Guidance Groups applicable for the plan and group them by org
@all_guidance_groups = @plan.get_guidance_group_options
@all_ggs_grouped_by_org = @all_guidance_groups.sort.group_by(&:org)
# Important ones come first on the page - we grab the user's org's GGs and "Organisation" org type GGs
@important_ggs = []
@important_ggs << [current_user.org, @all_ggs_grouped_by_org.delete(current_user.org)]
@all_ggs_grouped_by_org.each do |org, ggs|
if org.organisation?
@important_ggs << [org,ggs]
@all_ggs_grouped_by_org.delete(org)
end
end
# Sort the rest by org name for the accordion
@all_ggs_grouped_by_org = @all_ggs_grouped_by_org.sort_by {|org,gg| org.name}
@selected_guidance_groups = @plan.guidance_groups.pluck(:id)
@based_on = (@plan.template.customization_of.nil? ? @plan.template : Template.where(dmptemplate: @plan.template.customization_of).first)
respond_to :html
end
# we can go into this with the user able to edit or not able to edit
# the same edit form gets rendered but then different partials get used
# to render the answers depending on whether it is readonly or not
#
# we may or may not have a phase param.
# if we have none then we are editing/displaying the plan details
# if we have a phase then we are editing that phase.
#
# GET /plans/1/edit
def edit
@plan = Plan.find(params[:id])
authorize @plan
@visibility = @plan.visibility.present? ? @plan.visibility.to_s : Rails.application.config.default_plan_visibility
# If there was no phase specified use the template's 1st phase
@phase = (params[:phase].nil? ? @plan.template.phases.first : Phase.find(params[:phase]))
@show_phase_tab = params[:phase]
@readonly = [email protected]_by?(current_user.id)
# Get all Guidance Groups applicable for the plan and group them by org
@all_guidance_groups = @plan.get_guidance_group_options
@all_ggs_grouped_by_org = @all_guidance_groups.sort.group_by(&:org)
# Important ones come first on the page - we grab the user's org's GGs and "Organisation" org type GGs
@important_ggs = []
@important_ggs << [current_user.org, @all_ggs_grouped_by_org.delete(current_user.org)]
@all_ggs_grouped_by_org.each do |org, ggs|
if org.organisation?
@important_ggs << [org,ggs]
@all_ggs_grouped_by_org.delete(org)
end
end
# Sort the rest by org name for the accordion
@all_ggs_grouped_by_org = @all_ggs_grouped_by_org.sort_by {|org,gg| org.name}
@selected_guidance_groups = @plan.guidance_groups.pluck(:id)
@based_on = (@plan.template.customization_of.nil? ? @plan.template : Template.where(dmptemplate: @plan.template.customization_of).first)
flash[:notice] = "#{_('This is a')} <strong>#{_('test plan')}</strong>" if params[:test]
@is_test = params[:test] ||= false
respond_to :html
end
# PUT /plans/1
# PUT /plans/1.json
def update
@plan = Plan.find(params[:id])
authorize @plan
attrs = plan_params
respond_to do |format|
if @plan.update_attributes(attrs)
format.html { redirect_to @plan, :editing => false, notice: success_message(_('plan'), _('saved')) }
format.json { head :no_content }
else
flash[:alert] = failed_update_error(@plan, _('plan'))
format.html { render action: "edit" }
end
end
end
def update_guidance_choices
@plan = Plan.find(params[:id])
authorize @plan
guidance_group_ids = params[:guidance_group_ids].blank? ? [] : params[:guidance_group_ids].map(&:to_i)
all_guidance_groups = @plan.get_guidance_group_options
plan_groups = @plan.guidance_groups
guidance_groups = GuidanceGroup.where( id: guidance_group_ids)
all_guidance_groups.each do |group|
# case where plan group exists but not in selection
if plan_groups.include?(group) && ! guidance_groups.include?(group)
# remove from plan groups
@plan.guidance_groups.delete(group)
end
# case where plan group dosent exist and in selection
if !plan_groups.include?(group) && guidance_groups.include?(group)
# add to plan groups
@plan.guidance_groups << group
end
end
@plan.save
flash[:notice] = success_message(_('guidance choices'), _('saved'))
redirect_to action: "show"
end
def share
@plan = Plan.find(params[:id])
authorize @plan
#@plan_data = @plan.to_hash
end
def destroy
@plan = Plan.find(params[:id])
authorize @plan
if @plan.destroy
respond_to do |format|
format.html { redirect_to plans_url, notice: success_message(_('plan'), _('deleted')) }
end
else
respond_to do |format|
flash[:alert] = failed_create_error(@plan, _('plan'))
format.html { render action: "edit" }
end
end
end
# GET /status/1.json
# only returns json, why is this here?
def status
@plan = Plan.find(params[:id])
authorize @plan
respond_to do |format|
format.json { render json: @plan.status }
end
end
def answer
@plan = Plan.find(params[:id])
authorize @plan
if !params[:q_id].nil?
respond_to do |format|
format.json { render json: @plan.answer(params[:q_id], false).to_json(:include => :options) }
end
else
respond_to do |format|
format.json { render json: {} }
end
end
end
def show_export
@plan = Plan.find(params[:id])
authorize @plan
render 'show_export'
end
def export
@plan = Plan.find(params[:id])
authorize @plan
# If no format is specified, default to PDF
params[:format] = 'pdf' if params[:format].nil?
@exported_plan = ExportedPlan.new.tap do |ep|
ep.plan = @plan
ep.phase_id = params[:phase_id]
ep.user = current_user
ep.format = params[:format].to_sym
plan_settings = @plan.settings(:export)
Settings::Template::DEFAULT_SETTINGS.each do |key, value|
ep.settings(:export).send("#{key}=", plan_settings.send(key))
end
end
begin
@exported_plan.save!
file_name = @exported_plan.settings(:export)[:value]['title'].gsub(/ /, "_")
respond_to do |format|
format.html
format.csv { send_data @exported_plan.as_csv, filename: "#{file_name}.csv" }
format.text { send_data @exported_plan.as_txt, filename: "#{file_name}.txt" }
format.docx { render docx: 'export', filename: "#{file_name}.docx" }
format.pdf do
@formatting = @plan.settings(:export).formatting
render pdf: file_name,
margin: @formatting[:margin],
footer: {
center: _('This document was generated by %{application_name}') % {application_name: Rails.configuration.branding[:application][:name]},
font_size: 8,
spacing: (@formatting[:margin][:bottom] / 2) - 4,
right: '[page] of [topage]'
}
end
end
rescue ActiveRecord::RecordInvalid => e
redirect_to show_export_plan_path(@plan), alert: _('%{format} is not a valid exporting format. Available formats to export are %{available_formats}.') %
{format: params[:format], available_formats: ExportedPlan::VALID_FORMATS.to_s}
end
end
# GET /plans/[:plan_slug]/public_export
# -------------------------------------------------------------
def public_export
@plan = Plan.find(params[:id])
# If the plan has multiple phases we should export each
@plan.phases.each do |phase|
@exported_plan = ExportedPlan.new.tap do |ep|
ep.plan = @plan
ep.phase_id = phase.id
ep.format = :pdf
plan_settings = @plan.settings(:export)
Settings::Template::DEFAULT_SETTINGS.each do |key, value|
ep.settings(:export).send("#{key}=", plan_settings.send(key))
end
end
begin
@exported_plan.save!
# If the template has multiple phases then append the phase title to the filename
if @plan.phases.count > 1
file_name = "#{@plan.title.gsub(/ /, "_")}-#{phase.title}"
else
file_name = @plan.title.gsub(/ /, "_")
end
respond_to do |format|
format.pdf do
@formatting = @plan.settings(:export).formatting
render pdf: file_name,
margin: @formatting[:margin],
footer: {
center: _('This document was generated by %{application_name}') % {application_name: Rails.configuration.branding[:application][:name]},
font_size: 8,
spacing: (@formatting[:margin][:bottom] / 2) - 4,
right: '[page] of [topage]'
}
end
end
rescue ActiveRecord::RecordInvalid => e
redirect_to show_export_plan_path(@plan), alert: _('Unable to download the DMP at this time.')
end
end
end
def duplicate
plan = Plan.find(params[:id])
authorize plan
@plan = Plan.deep_copy(plan)
respond_to do |format|
if @plan.save
@plan.assign_creator(current_user)
flash[:notice] = success_message(_('plan'), _('copied'))
format.js { render js: "window.location='#{plan_url(@plan)}?editing=true'" }
# format.html { redirect_to @plan, notice: _('Plan was successfully duplicated.') }
# format.json { head :no_content }
else
flash[:alert] = failed_create_error(@plan, 'Plan')
format.js {}
end
end
end
# AJAX access to update the plan's visibility
# POST /plans/:id
def visibility
plan = Plan.find(params[:id])
authorize plan
plan.visibility = "#{plan_params[:visibility]}"
if plan.save
render json: {code: 1, msg: ''}
else
render json: {code: 0, msg: _("Unable to change the plan's Test status")}
end
end
private
def plan_params
params.require(:plan).permit(:org_id, :org_name, :funder_id, :funder_name, :template_id, :title, :visibility)
end
# different versions of the same template have the same dmptemplate_id
# but different version numbers so for each set of templates with the
# same dmptemplate_id choose the highest version number.
def get_most_recent( templates )
groups = Hash.new
templates.each do |t|
k = t.dmptemplate_id
if !groups.has_key?(k)
groups[k] = t
else
other = groups[k]
if other.version < t.version
groups[k] = t
end
end
end
groups.values
end
def fixup_hash(plan)
rollup(plan, "notes", "answer_id", "answers")
rollup(plan, "answers", "question_id", "questions")
rollup(plan, "questions", "section_id", "sections")
rollup(plan, "sections", "phase_id", "phases")
plan["template"]["phases"] = plan.delete("phases")
ghash = {}
plan["guidance_groups"].map{|g| ghash[g["id"]] = g}
plan["plans_guidance_groups"].each do |pgg|
pgg["guidance_group"] = ghash[ pgg["guidance_group_id"] ]
end
plan["template"]["org"] = Org.find(plan["template"]["org_id"]).serializable_hash()
end
# find all object under src_plan_key
# merge them into the items under obj_plan_key using
# super_id = id
# so we have answers which each have a question_id
# rollup(plan, "answers", "quesiton_id", "questions")
# will put the answers into the right questions.
def rollup(plan, src_plan_key, super_id, obj_plan_key)
id_to_obj = Hash.new()
plan[src_plan_key].each do |o|
id = o[super_id]
if !id_to_obj.has_key?(id)
id_to_obj[id] = Array.new
end
id_to_obj[id] << o
end
plan[obj_plan_key].each do |o|
id = o["id"]
if id_to_obj.has_key?(id)
o[src_plan_key] = id_to_obj[ id ]
end
end
plan.delete(src_plan_key)
end
# Collect all of the templates available for the org+funder combination
# --------------------------------------------------------------------------
def template_options(org_id, funder_id)
@templates = []
if !org_id.blank? || !funder_id.blank?
if funder_id.blank?
# Load the org's template(s)
unless org_id.nil?
org = Org.find(org_id)
@templates = Template.valid.where(published: true, org: org, customization_of: nil).to_a
@msg = _("We found multiple DMP templates corresponding to the research organisation.") if @templates.count > 1
end
else
funder = Org.find(funder_id)
# Load the funder's template(s)
@templates = Template.valid.where(published: true, org: funder).to_a
unless org_id.blank?
org = Org.find(org_id)
# Swap out any organisational cusotmizations of a funder template
@templates.each do |tmplt|
customization = Template.valid.find_by(published: true, org: org, customization_of: tmplt.dmptemplate_id)
unless customization.nil?
@templates.delete(tmplt)
@templates << customization
end
end
end
msg = _("We found multiple DMP templates corresponding to the funder.") if @templates.count > 1
end
end
# If no templates were available use the generic templates
if @templates.empty?
@msg = _("Using the generic Data Management Plan")
@templates << Template.find_by(is_default: true)
end
@templates = @templates.sort{|x,y| x.title <=> y.title } if @templates.count > 1
end
end
| 1 | 16,781 | Since the IdentifierScheme's don't change without us making additional code changes, perhaps this should be added as a constant as we previously did with Perms? | DMPRoadmap-roadmap | rb |
@@ -14,6 +14,7 @@
# limitations under the License.
#
+import os
import functools
import shutil
import sys | 1 | #
# Copyright (C) 2019 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import functools
import shutil
import sys
import tempfile
import unittest
from contextlib import contextmanager
import pandas as pd
from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession, SQLContext
from databricks import koalas
from databricks.koalas.frame import DataFrame
from databricks.koalas.series import Series
class PySparkTestCase(unittest.TestCase):
def setUp(self):
self._old_sys_path = list(sys.path)
if SparkContext._active_spark_context is not None:
SparkContext._active_spark_context.stop()
class_name = self.__class__.__name__
self.sc = SparkContext('local[4]', class_name)
def tearDown(self):
self.sc.stop()
sys.path = self._old_sys_path
class ReusedPySparkTestCase(unittest.TestCase):
@classmethod
def conf(cls):
"""
Override this in subclasses to supply a more specific conf
"""
return SparkConf()
@classmethod
def setUpClass(cls):
if SparkContext._active_spark_context is not None:
SparkContext._active_spark_context.stop()
cls.sc = SparkContext('local[4]', cls.__name__, conf=cls.conf())
@classmethod
def tearDownClass(cls):
cls.sc.stop()
class SQLTestUtils(object):
"""
This util assumes the instance of this to have 'spark' attribute, having a spark session.
It is usually used with 'ReusedSQLTestCase' class but can be used if you feel sure the
the implementation of this class has 'spark' attribute.
"""
@contextmanager
def sql_conf(self, pairs):
"""
A convenient context manager to test some configuration specific logic. This sets
`value` to the configuration `key` and then restores it back when it exits.
"""
assert isinstance(pairs, dict), "pairs should be a dictionary."
assert hasattr(self, "spark"), "it should have 'spark' attribute, having a spark session."
keys = pairs.keys()
new_values = pairs.values()
old_values = [self.spark.conf.get(key, None) for key in keys]
for key, new_value in zip(keys, new_values):
self.spark.conf.set(key, new_value)
try:
yield
finally:
for key, old_value in zip(keys, old_values):
if old_value is None:
self.spark.conf.unset(key)
else:
self.spark.conf.set(key, old_value)
@contextmanager
def database(self, *databases):
"""
A convenient context manager to test with some specific databases. This drops the given
databases if it exists and sets current database to "default" when it exits.
"""
assert hasattr(self, "spark"), "it should have 'spark' attribute, having a spark session."
try:
yield
finally:
for db in databases:
self.spark.sql("DROP DATABASE IF EXISTS %s CASCADE" % db)
self.spark.catalog.setCurrentDatabase("default")
@contextmanager
def table(self, *tables):
"""
A convenient context manager to test with some specific tables. This drops the given tables
if it exists.
"""
assert hasattr(self, "spark"), "it should have 'spark' attribute, having a spark session."
try:
yield
finally:
for t in tables:
self.spark.sql("DROP TABLE IF EXISTS %s" % t)
@contextmanager
def tempView(self, *views):
"""
A convenient context manager to test with some specific views. This drops the given views
if it exists.
"""
assert hasattr(self, "spark"), "it should have 'spark' attribute, having a spark session."
try:
yield
finally:
for v in views:
self.spark.catalog.dropTempView(v)
@contextmanager
def function(self, *functions):
"""
A convenient context manager to test with some specific functions. This drops the given
functions if it exists.
"""
assert hasattr(self, "spark"), "it should have 'spark' attribute, having a spark session."
try:
yield
finally:
for f in functions:
self.spark.sql("DROP FUNCTION IF EXISTS %s" % f)
class ReusedSQLTestCase(ReusedPySparkTestCase, SQLTestUtils):
@classmethod
def setUpClass(cls):
super(ReusedSQLTestCase, cls).setUpClass()
cls.spark = SparkSession(cls.sc)
cls.spark.conf.set('spark.sql.execution.arrow.enabled', True)
@classmethod
def tearDownClass(cls):
super(ReusedSQLTestCase, cls).tearDownClass()
cls.spark.stop()
SQLContext._instantiatedContext = None
def assertPandasEqual(self, left, right):
if isinstance(left, pd.DataFrame) and isinstance(right, pd.DataFrame):
msg = ("DataFrames are not equal: " +
"\n\nLeft:\n%s\n%s" % (left, left.dtypes) +
"\n\nRight:\n%s\n%s" % (right, right.dtypes))
self.assertTrue(left.equals(right), msg=msg)
elif isinstance(left, pd.Series) and isinstance(right, pd.Series):
msg = ("Series are not equal: " +
"\n\nLeft:\n%s\n%s" % (left, left.dtype) +
"\n\nRight:\n%s\n%s" % (right, right.dtype))
self.assertTrue((left == right).all(), msg=msg)
elif isinstance(left, pd.Index) and isinstance(right, pd.Index):
msg = ("Indices are not equal: " +
"\n\nLeft:\n%s\n%s" % (left, left.dtype) +
"\n\nRight:\n%s\n%s" % (right, right.dtype))
self.assertTrue((left == right).all(), msg=msg)
else:
raise ValueError("Unexpected values: (%s, %s)" % (left, right))
def assertPandasAlmostEqual(self, left, right):
"""
This function checks if given Pandas objects approximately same,
which means the conditions below:
- Both objects are nullable
- Compare floats rounding to the number of decimal places, 7 after
dropping missing values (NaN, NaT, None)
"""
if isinstance(left, pd.DataFrame) and isinstance(right, pd.DataFrame):
msg = ("DataFrames are not almost equal: " +
"\n\nLeft:\n%s\n%s" % (left, left.dtypes) +
"\n\nRight:\n%s\n%s" % (right, right.dtypes))
self.assertEqual(left.shape, right.shape, msg=msg)
for lcol, rcol in zip(left.columns, right.columns):
self.assertEqual(str(lcol), str(rcol), msg=msg)
for lnull, rnull in zip(left[lcol].isnull(), right[rcol].isnull()):
self.assertEqual(lnull, rnull, msg=msg)
for lval, rval in zip(left[lcol].dropna(), right[rcol].dropna()):
self.assertAlmostEqual(lval, rval, msg=msg)
elif isinstance(left, pd.Series) and isinstance(left, pd.Series):
msg = ("Series are not almost equal: " +
"\n\nLeft:\n%s\n%s" % (left, left.dtype) +
"\n\nRight:\n%s\n%s" % (right, right.dtype))
self.assertEqual(len(left), len(right), msg=msg)
for lnull, rnull in zip(left.isnull(), right.isnull()):
self.assertEqual(lnull, rnull, msg=msg)
for lval, rval in zip(left.dropna(), right.dropna()):
self.assertAlmostEqual(lval, rval, msg=msg)
elif isinstance(left, pd.Index) and isinstance(left, pd.Index):
msg = ("Indices are not almost equal: " +
"\n\nLeft:\n%s\n%s" % (left, left.dtype) +
"\n\nRight:\n%s\n%s" % (right, right.dtype))
self.assertEqual(len(left), len(right), msg=msg)
for lnull, rnull in zip(left.isnull(), right.isnull()):
self.assertEqual(lnull, rnull, msg=msg)
for lval, rval in zip(left.dropna(), right.dropna()):
self.assertAlmostEqual(lval, rval, msg=msg)
else:
raise ValueError("Unexpected values: (%s, %s)" % (left, right))
def assert_eq(self, left, right, almost=False):
"""
Asserts if two arbitrary objects are equal or not. If given objects are Koalas DataFrame
or Series, they are converted into Pandas' and compared.
:param left: object to compare
:param right: object to compare
:param almost: if this is enabled, the comparison is delegated to `unittest`'s
`assertAlmostEqual`. See its documentation for more details.
"""
lpdf = self._to_pandas(left)
rpdf = self._to_pandas(right)
if isinstance(lpdf, (pd.DataFrame, pd.Series, pd.Index)):
if almost:
self.assertPandasAlmostEqual(lpdf, rpdf)
else:
self.assertPandasEqual(lpdf, rpdf)
else:
if almost:
self.assertAlmostEqual(lpdf, rpdf)
else:
self.assertEqual(lpdf, rpdf)
@staticmethod
def _to_pandas(df):
if isinstance(df, (DataFrame, Series)):
return df.toPandas()
else:
return df
class TestUtils(object):
@contextmanager
def temp_dir(self):
tmp = tempfile.mkdtemp()
try:
yield tmp
finally:
shutil.rmtree(tmp)
@contextmanager
def temp_file(self):
with self.temp_dir() as tmp:
yield tempfile.mktemp(dir=tmp)
class ComparisonTestBase(ReusedSQLTestCase):
@property
def kdf(self):
return koalas.from_pandas(self.pdf)
@property
def pdf(self):
return self.kdf.toPandas()
def compare_both(f=None, almost=True):
if f is None:
return functools.partial(compare_both, almost=almost)
elif isinstance(f, bool):
return functools.partial(compare_both, almost=f)
@functools.wraps(f)
def wrapped(self):
if almost:
compare = self.assertPandasAlmostEqual
else:
compare = self.assertPandasEqual
for result_pandas, result_spark in zip(f(self, self.pdf), f(self, self.kdf)):
compare(result_pandas, result_spark.toPandas())
return wrapped
| 1 | 9,042 | nit: We can revert this now. | databricks-koalas | py |
@@ -5,9 +5,19 @@ import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
+
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
+
+import org.apache.commons.lang3.ArrayUtils;
+
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.activity.MainActivity;
import de.danoeh.antennapod.core.feed.FeedItem; | 1 | package de.danoeh.antennapod.adapter;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.activity.MainActivity;
import de.danoeh.antennapod.core.feed.FeedItem;
import de.danoeh.antennapod.core.util.FeedItemUtil;
import de.danoeh.antennapod.fragment.ItemPagerFragment;
import de.danoeh.antennapod.menuhandler.FeedItemMenuHandler;
import de.danoeh.antennapod.view.viewholder.EpisodeItemViewHolder;
import org.apache.commons.lang3.ArrayUtils;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
* List adapter for the list of new episodes.
*/
public class EpisodeItemListAdapter extends RecyclerView.Adapter<EpisodeItemViewHolder>
implements View.OnCreateContextMenuListener {
private final WeakReference<MainActivity> mainActivityRef;
private List<FeedItem> episodes = new ArrayList<>();
private FeedItem selectedItem;
public EpisodeItemListAdapter(MainActivity mainActivity) {
super();
this.mainActivityRef = new WeakReference<>(mainActivity);
setHasStableIds(true);
}
public void updateItems(List<FeedItem> items) {
episodes = items;
notifyDataSetChanged();
}
@Override
public final int getItemViewType(int position) {
return R.id.view_type_episode_item;
}
@NonNull
@Override
public final EpisodeItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new EpisodeItemViewHolder(mainActivityRef.get(), parent);
}
@Override
public final void onBindViewHolder(EpisodeItemViewHolder holder, int pos) {
// Reset state of recycled views
holder.coverHolder.setVisibility(View.VISIBLE);
holder.dragHandle.setVisibility(View.GONE);
beforeBindViewHolder(holder, pos);
FeedItem item = episodes.get(pos);
holder.bind(item);
holder.itemView.setOnLongClickListener(v -> {
selectedItem = item;
return false;
});
holder.itemView.setOnClickListener(v -> {
MainActivity activity = mainActivityRef.get();
if (activity != null) {
long[] ids = FeedItemUtil.getIds(episodes);
int position = ArrayUtils.indexOf(ids, item.getId());
activity.loadChildFragment(ItemPagerFragment.newInstance(ids, position));
}
});
holder.itemView.setOnCreateContextMenuListener(this);
afterBindViewHolder(holder, pos);
holder.hideSeparatorIfNecessary();
}
protected void beforeBindViewHolder(EpisodeItemViewHolder holder, int pos) {
}
protected void afterBindViewHolder(EpisodeItemViewHolder holder, int pos) {
}
@Override
public void onViewRecycled(@NonNull EpisodeItemViewHolder holder) {
super.onViewRecycled(holder);
// Set all listeners to null. This is required to prevent leaking fragments that have set a listener.
// Activity -> recycledViewPool -> EpisodeItemViewHolder -> Listener -> Fragment (can not be garbage collected)
holder.itemView.setOnClickListener(null);
holder.itemView.setOnCreateContextMenuListener(null);
holder.itemView.setOnLongClickListener(null);
holder.secondaryActionButton.setOnClickListener(null);
holder.dragHandle.setOnTouchListener(null);
holder.coverHolder.setOnTouchListener(null);
}
/**
* {@link #notifyItemChanged(int)} is final, so we can not override.
* Calling {@link #notifyItemChanged(int)} may bind the item to a new ViewHolder and execute a transition.
* This causes flickering and breaks the download animation that stores the old progress in the View.
* Instead, we tell the adapter to use partial binding by calling {@link #notifyItemChanged(int, Object)}.
* We actually ignore the payload and always do a full bind but calling the partial bind method ensures
* that ViewHolders are always re-used.
* @param position Position of the item that has changed
*/
public void notifyItemChangedCompat(int position) {
notifyItemChanged(position, "foo");
}
@Nullable
public FeedItem getSelectedItem() {
return selectedItem;
}
@Override
public long getItemId(int position) {
FeedItem item = episodes.get(position);
return item != null ? item.getId() : RecyclerView.NO_POSITION;
}
@Override
public int getItemCount() {
return episodes.size();
}
protected FeedItem getItem(int index) {
return episodes.get(index);
}
protected Activity getActivity() {
return mainActivityRef.get();
}
@Override
public void onCreateContextMenu(final ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = mainActivityRef.get().getMenuInflater();
inflater.inflate(R.menu.feeditemlist_context, menu);
menu.setHeaderTitle(selectedItem.getTitle());
FeedItemMenuHandler.onPrepareMenu(menu, selectedItem, R.id.skip_episode_item);
}
}
| 1 | 19,231 | Oh, that's the reason why you have two different data structures here. Does the order of the `selectedItems` list matter? If not, I think it would be more clear if both would be a Set. | AntennaPod-AntennaPod | java |
@@ -2034,6 +2034,7 @@ void LuaScriptInterface::registerFunctions()
registerClass("Container", "Item", LuaScriptInterface::luaContainerCreate);
registerMetaMethod("Container", "__eq", LuaScriptInterface::luaUserdataCompare);
+ registerMethod("Container", "getContentDescription", LuaScriptInterface::luaContainerGetContentDescription);
registerMethod("Container", "getSize", LuaScriptInterface::luaContainerGetSize);
registerMethod("Container", "getCapacity", LuaScriptInterface::luaContainerGetCapacity);
registerMethod("Container", "getEmptySlots", LuaScriptInterface::luaContainerGetEmptySlots); | 1 | /**
* The Forgotten Server - a free and open-source MMORPG server emulator
* Copyright (C) 2015 Mark Samman <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "otpch.h"
#include <boost/range/adaptor/reversed.hpp>
#include "luascript.h"
#include "chat.h"
#include "player.h"
#include "item.h"
#include "game.h"
#include "house.h"
#include "housetile.h"
#include "protocolstatus.h"
#include "combat.h"
#include "spells.h"
#include "condition.h"
#include "monsters.h"
#include "baseevents.h"
#include "iologindata.h"
#include "configmanager.h"
#include "town.h"
#include "vocation.h"
#include "teleport.h"
#include "ban.h"
#include "mounts.h"
#include "databasemanager.h"
#include "bed.h"
#include "monster.h"
#include "scheduler.h"
#include "raids.h"
#include "databasetasks.h"
extern Chat* g_chat;
extern Game g_game;
extern Monsters g_monsters;
extern ConfigManager g_config;
extern Vocations g_vocations;
extern Spells* g_spells;
enum {
EVENT_ID_LOADING = 1,
EVENT_ID_USER = 1000,
};
ScriptEnvironment::DBResultMap ScriptEnvironment::m_tempResults;
uint32_t ScriptEnvironment::m_lastResultId = 0;
std::multimap<ScriptEnvironment*, Item*> ScriptEnvironment::tempItems;
LuaEnvironment g_luaEnvironment;
ScriptEnvironment::ScriptEnvironment()
{
m_curNpc = nullptr;
resetEnv();
m_lastUID = std::numeric_limits<uint16_t>::max();
}
ScriptEnvironment::~ScriptEnvironment()
{
resetEnv();
}
void ScriptEnvironment::resetEnv()
{
m_scriptId = 0;
m_callbackId = 0;
m_timerEvent = false;
m_interface = nullptr;
localMap.clear();
m_tempResults.clear();
auto pair = tempItems.equal_range(this);
auto it = pair.first;
while (it != pair.second) {
Item* item = it->second;
if (item->getParent() == VirtualCylinder::virtualCylinder) {
g_game.ReleaseItem(item);
}
it = tempItems.erase(it);
}
}
bool ScriptEnvironment::setCallbackId(int32_t callbackId, LuaScriptInterface* scriptInterface)
{
if (m_callbackId != 0) {
//nested callbacks are not allowed
if (m_interface) {
m_interface->reportErrorFunc("Nested callbacks!");
}
return false;
}
m_callbackId = callbackId;
m_interface = scriptInterface;
return true;
}
void ScriptEnvironment::getEventInfo(int32_t& scriptId, std::string& desc, LuaScriptInterface*& scriptInterface, int32_t& callbackId, bool& timerEvent) const
{
scriptId = m_scriptId;
desc = m_eventdesc;
scriptInterface = m_interface;
callbackId = m_callbackId;
timerEvent = m_timerEvent;
}
uint32_t ScriptEnvironment::addThing(Thing* thing)
{
if (!thing || thing->isRemoved()) {
return 0;
}
Creature* creature = thing->getCreature();
if (creature) {
return creature->getID();
}
Item* item = thing->getItem();
if (item && item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) {
return item->getUniqueId();
}
for (const auto& it : localMap) {
if (it.second == item) {
return it.first;
}
}
localMap[++m_lastUID] = item;
return m_lastUID;
}
void ScriptEnvironment::insertItem(uint32_t uid, Item* item)
{
auto result = localMap.emplace(uid, item);
if (!result.second) {
std::cout << std::endl << "Lua Script Error: Thing uid already taken.";
}
}
Thing* ScriptEnvironment::getThingByUID(uint32_t uid)
{
if (uid >= 0x10000000) {
return g_game.getCreatureByID(uid);
}
if (uid <= std::numeric_limits<uint16_t>::max()) {
Item* item = g_game.getUniqueItem(uid);
if (item && !item->isRemoved()) {
return item;
}
return nullptr;
}
auto it = localMap.find(uid);
if (it != localMap.end()) {
Item* item = it->second;
if (!item->isRemoved()) {
return item;
}
}
return nullptr;
}
Item* ScriptEnvironment::getItemByUID(uint32_t uid)
{
Thing* thing = getThingByUID(uid);
if (!thing) {
return nullptr;
}
return thing->getItem();
}
Container* ScriptEnvironment::getContainerByUID(uint32_t uid)
{
Item* item = getItemByUID(uid);
if (!item) {
return nullptr;
}
return item->getContainer();
}
void ScriptEnvironment::removeItemByUID(uint32_t uid)
{
if (uid <= std::numeric_limits<uint16_t>::max()) {
g_game.removeUniqueItem(uid);
return;
}
auto it = localMap.find(uid);
if (it != localMap.end()) {
localMap.erase(it);
}
}
void ScriptEnvironment::addTempItem(Item* item)
{
tempItems.emplace(this, item);
}
void ScriptEnvironment::removeTempItem(Item* item)
{
for (auto it = tempItems.begin(), end = tempItems.end(); it != end; ++it) {
if (it->second == item) {
tempItems.erase(it);
break;
}
}
}
uint32_t ScriptEnvironment::addResult(DBResult_ptr res)
{
m_tempResults[++m_lastResultId] = res;
return m_lastResultId;
}
bool ScriptEnvironment::removeResult(uint32_t id)
{
auto it = m_tempResults.find(id);
if (it == m_tempResults.end()) {
return false;
}
m_tempResults.erase(it);
return true;
}
DBResult_ptr ScriptEnvironment::getResultByID(uint32_t id)
{
auto it = m_tempResults.find(id);
if (it == m_tempResults.end()) {
return nullptr;
}
return it->second;
}
std::string LuaScriptInterface::getErrorDesc(ErrorCode_t code)
{
switch (code) {
case LUA_ERROR_PLAYER_NOT_FOUND: return "Player not found";
case LUA_ERROR_CREATURE_NOT_FOUND: return "Creature not found";
case LUA_ERROR_ITEM_NOT_FOUND: return "Item not found";
case LUA_ERROR_THING_NOT_FOUND: return "Thing not found";
case LUA_ERROR_TILE_NOT_FOUND: return "Tile not found";
case LUA_ERROR_HOUSE_NOT_FOUND: return "House not found";
case LUA_ERROR_COMBAT_NOT_FOUND: return "Combat not found";
case LUA_ERROR_CONDITION_NOT_FOUND: return "Condition not found";
case LUA_ERROR_AREA_NOT_FOUND: return "Area not found";
case LUA_ERROR_CONTAINER_NOT_FOUND: return "Container not found";
case LUA_ERROR_VARIANT_NOT_FOUND: return "Variant not found";
case LUA_ERROR_VARIANT_UNKNOWN: return "Unknown variant type";
case LUA_ERROR_SPELL_NOT_FOUND: return "Spell not found";
default: return "Bad error code";
}
}
ScriptEnvironment LuaScriptInterface::m_scriptEnv[16];
int32_t LuaScriptInterface::m_scriptEnvIndex = -1;
LuaScriptInterface::LuaScriptInterface(std::string interfaceName)
: m_luaState(nullptr), m_interfaceName(interfaceName), m_eventTableRef(-1)
{
if (!g_luaEnvironment.getLuaState()) {
g_luaEnvironment.initState();
}
}
LuaScriptInterface::~LuaScriptInterface()
{
closeState();
}
bool LuaScriptInterface::reInitState()
{
g_luaEnvironment.clearCombatObjects(this);
g_luaEnvironment.clearAreaObjects(this);
closeState();
return initState();
}
/// Same as lua_pcall, but adds stack trace to error strings in called function.
int LuaScriptInterface::protectedCall(lua_State* L, int nargs, int nresults)
{
int error_index = lua_gettop(L) - nargs;
lua_pushcfunction(L, luaErrorHandler);
lua_insert(L, error_index);
int ret = lua_pcall(L, nargs, nresults, error_index);
lua_remove(L, error_index);
return ret;
}
int32_t LuaScriptInterface::loadFile(const std::string& file, Npc* npc /* = nullptr*/)
{
//loads file as a chunk at stack top
int ret = luaL_loadfile(m_luaState, file.c_str());
if (ret != 0) {
m_lastLuaError = popString(m_luaState);
return -1;
}
//check that it is loaded as a function
if (!isFunction(m_luaState, -1)) {
return -1;
}
m_loadingFile = file;
if (!reserveScriptEnv()) {
return -1;
}
ScriptEnvironment* env = getScriptEnv();
env->setScriptId(EVENT_ID_LOADING, this);
env->setNpc(npc);
//execute it
ret = protectedCall(m_luaState, 0, 0);
if (ret != 0) {
reportError(nullptr, popString(m_luaState));
resetScriptEnv();
return -1;
}
resetScriptEnv();
return 0;
}
int32_t LuaScriptInterface::getEvent(const std::string& eventName)
{
//get our events table
lua_rawgeti(m_luaState, LUA_REGISTRYINDEX, m_eventTableRef);
if (!isTable(m_luaState, -1)) {
lua_pop(m_luaState, 1);
return -1;
}
//get current event function pointer
lua_getglobal(m_luaState, eventName.c_str());
if (!isFunction(m_luaState, -1)) {
lua_pop(m_luaState, 2);
return -1;
}
//save in our events table
lua_pushvalue(m_luaState, -1);
lua_rawseti(m_luaState, -3, m_runningEventId);
lua_pop(m_luaState, 2);
//reset global value of this event
lua_pushnil(m_luaState);
lua_setglobal(m_luaState, eventName.c_str());
m_cacheFiles[m_runningEventId] = m_loadingFile + ":" + eventName;
return m_runningEventId++;
}
int32_t LuaScriptInterface::getMetaEvent(const std::string& globalName, const std::string& eventName)
{
//get our events table
lua_rawgeti(m_luaState, LUA_REGISTRYINDEX, m_eventTableRef);
if (!isTable(m_luaState, -1)) {
lua_pop(m_luaState, 1);
return -1;
}
//get current event function pointer
lua_getglobal(m_luaState, globalName.c_str());
lua_getfield(m_luaState, -1, eventName.c_str());
if (!isFunction(m_luaState, -1)) {
lua_pop(m_luaState, 3);
return -1;
}
//save in our events table
lua_pushvalue(m_luaState, -1);
lua_rawseti(m_luaState, -4, m_runningEventId);
lua_pop(m_luaState, 1);
//reset global value of this event
lua_pushnil(m_luaState);
lua_setfield(m_luaState, -2, eventName.c_str());
lua_pop(m_luaState, 2);
m_cacheFiles[m_runningEventId] = m_loadingFile + ":" + globalName + "@" + eventName;
return m_runningEventId++;
}
const std::string& LuaScriptInterface::getFileById(int32_t scriptId)
{
if (scriptId == EVENT_ID_LOADING) {
return m_loadingFile;
}
auto it = m_cacheFiles.find(scriptId);
if (it == m_cacheFiles.end()) {
static const std::string& unk = "(Unknown scriptfile)";
return unk;
}
return it->second;
}
std::string LuaScriptInterface::getStackTrace(const std::string& error_desc)
{
lua_getglobal(m_luaState, "debug");
if (!isTable(m_luaState, -1)) {
lua_pop(m_luaState, 1);
return error_desc;
}
lua_getfield(m_luaState, -1, "traceback");
if (!isFunction(m_luaState, -1)) {
lua_pop(m_luaState, 2);
return error_desc;
}
lua_replace(m_luaState, -2);
pushString(m_luaState, error_desc);
lua_call(m_luaState, 1, 1);
return popString(m_luaState);
}
void LuaScriptInterface::reportError(const char* function, const std::string& error_desc, bool stack_trace/* = false*/)
{
int32_t scriptId;
int32_t callbackId;
bool timerEvent;
std::string event_desc;
LuaScriptInterface* scriptInterface;
getScriptEnv()->getEventInfo(scriptId, event_desc, scriptInterface, callbackId, timerEvent);
std::cout << std::endl << "Lua Script Error: ";
if (scriptInterface) {
std::cout << '[' << scriptInterface->getInterfaceName() << "] " << std::endl;
if (timerEvent) {
std::cout << "in a timer event called from: " << std::endl;
}
if (callbackId) {
std::cout << "in callback: " << scriptInterface->getFileById(callbackId) << std::endl;
}
std::cout << scriptInterface->getFileById(scriptId) << std::endl;
}
if (!event_desc.empty()) {
std::cout << "Event: " << event_desc << std::endl;
}
if (function) {
std::cout << function << "(). ";
}
if (stack_trace && scriptInterface) {
std::cout << scriptInterface->getStackTrace(error_desc) << std::endl;
} else {
std::cout << error_desc << std::endl;
}
}
bool LuaScriptInterface::pushFunction(int32_t functionId)
{
lua_rawgeti(m_luaState, LUA_REGISTRYINDEX, m_eventTableRef);
if (!isTable(m_luaState, -1)) {
return false;
}
lua_rawgeti(m_luaState, -1, functionId);
lua_replace(m_luaState, -2);
return isFunction(m_luaState, -1);
}
bool LuaScriptInterface::initState()
{
m_luaState = g_luaEnvironment.getLuaState();
if (!m_luaState) {
return false;
}
lua_newtable(m_luaState);
m_eventTableRef = luaL_ref(m_luaState, LUA_REGISTRYINDEX);
m_runningEventId = EVENT_ID_USER;
return true;
}
bool LuaScriptInterface::closeState()
{
if (!g_luaEnvironment.getLuaState() || !m_luaState) {
return false;
}
m_cacheFiles.clear();
if (m_eventTableRef != -1) {
luaL_unref(m_luaState, LUA_REGISTRYINDEX, m_eventTableRef);
m_eventTableRef = -1;
}
m_luaState = nullptr;
return true;
}
int LuaScriptInterface::luaErrorHandler(lua_State* L)
{
const std::string& errorMessage = popString(L);
pushString(L, getScriptEnv()->getScriptInterface()->getStackTrace(errorMessage));
return 1;
}
bool LuaScriptInterface::callFunction(int params)
{
bool result = false;
int size = lua_gettop(m_luaState);
if (protectedCall(m_luaState, params, 1) != 0) {
LuaScriptInterface::reportError(nullptr, LuaScriptInterface::getString(m_luaState, -1));
} else {
result = LuaScriptInterface::getBoolean(m_luaState, -1);
}
lua_pop(m_luaState, 1);
if ((lua_gettop(m_luaState) + params + 1) != size) {
LuaScriptInterface::reportError(nullptr, "Stack size changed!");
}
resetScriptEnv();
return result;
}
void LuaScriptInterface::callVoidFunction(int params)
{
int size = lua_gettop(m_luaState);
if (protectedCall(m_luaState, params, 0) != 0) {
LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(m_luaState));
}
if ((lua_gettop(m_luaState) + params + 1) != size) {
LuaScriptInterface::reportError(nullptr, "Stack size changed!");
}
resetScriptEnv();
}
void LuaScriptInterface::pushVariant(lua_State* L, const LuaVariant& var)
{
lua_createtable(L, 0, 2);
setField(L, "type", var.type);
switch (var.type) {
case VARIANT_NUMBER:
setField(L, "number", var.number);
break;
case VARIANT_STRING:
setField(L, "string", var.text);
break;
case VARIANT_TARGETPOSITION:
case VARIANT_POSITION: {
pushPosition(L, var.pos);
lua_setfield(L, -2, "pos");
break;
}
default:
break;
}
setMetatable(L, -1, "Variant");
}
void LuaScriptInterface::pushThing(lua_State* L, Thing* thing)
{
if (!thing) {
lua_createtable(L, 0, 4);
setField(L, "uid", 0);
setField(L, "itemid", 0);
setField(L, "actionid", 0);
setField(L, "type", 0);
return;
}
if (Item* item = thing->getItem()) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else if (Creature* creature = thing->getCreature()) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else {
lua_pushnil(L);
}
}
void LuaScriptInterface::pushString(lua_State* L, const std::string& value)
{
lua_pushlstring(L, value.c_str(), value.length());
}
void LuaScriptInterface::pushCallback(lua_State* L, int32_t callback)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, callback);
}
std::string LuaScriptInterface::popString(lua_State* L)
{
if (lua_gettop(L) == 0) {
return std::string();
}
std::string str(getString(L, -1));
lua_pop(L, 1);
return str;
}
int32_t LuaScriptInterface::popCallback(lua_State* L)
{
return luaL_ref(L, LUA_REGISTRYINDEX);
}
// Metatables
void LuaScriptInterface::setMetatable(lua_State* L, int32_t index, const std::string& name)
{
luaL_getmetatable(L, name.c_str());
lua_setmetatable(L, index - 1);
}
void LuaScriptInterface::setWeakMetatable(lua_State* L, int32_t index, const std::string& name)
{
static std::set<std::string> weakObjectTypes;
const std::string& weakName = name + "_weak";
auto result = weakObjectTypes.emplace(name);
if (result.second) {
luaL_getmetatable(L, name.c_str());
int childMetatable = lua_gettop(L);
luaL_newmetatable(L, weakName.c_str());
int metatable = lua_gettop(L);
static const std::vector<std::string> methodKeys = {"__index", "__metatable", "__eq"};
for (const std::string& metaKey : methodKeys) {
lua_getfield(L, childMetatable, metaKey.c_str());
lua_setfield(L, metatable, metaKey.c_str());
}
static const std::vector<int> methodIndexes = {'h', 'p', 't'};
for (int metaIndex : methodIndexes) {
lua_rawgeti(L, childMetatable, metaIndex);
lua_rawseti(L, metatable, metaIndex);
}
lua_pushnil(L);
lua_setfield(L, metatable, "__gc");
lua_remove(L, childMetatable);
} else {
luaL_getmetatable(L, weakName.c_str());
}
lua_setmetatable(L, index - 1);
}
void LuaScriptInterface::setItemMetatable(lua_State* L, int32_t index, const Item* item)
{
if (item->getContainer()) {
luaL_getmetatable(L, "Container");
} else if (item->getTeleport()) {
luaL_getmetatable(L, "Teleport");
} else {
luaL_getmetatable(L, "Item");
}
lua_setmetatable(L, index - 1);
}
void LuaScriptInterface::setCreatureMetatable(lua_State* L, int32_t index, const Creature* creature)
{
if (creature->getPlayer()) {
luaL_getmetatable(L, "Player");
} else if (creature->getMonster()) {
luaL_getmetatable(L, "Monster");
} else {
luaL_getmetatable(L, "Npc");
}
lua_setmetatable(L, index - 1);
}
// Get
std::string LuaScriptInterface::getString(lua_State* L, int32_t arg)
{
size_t len;
const char* c_str = lua_tolstring(L, arg, &len);
if (!c_str || len == 0) {
return std::string();
}
return std::string(c_str, len);
}
Position LuaScriptInterface::getPosition(lua_State* L, int32_t arg, int32_t& stackpos)
{
Position position;
position.x = getField<uint16_t>(L, arg, "x");
position.y = getField<uint16_t>(L, arg, "y");
position.z = getField<uint8_t>(L, arg, "z");
lua_getfield(L, arg, "stackpos");
if (lua_isnil(L, -1) == 1) {
stackpos = 0;
} else {
stackpos = getNumber<int32_t>(L, -1);
}
lua_pop(L, 4);
return position;
}
Position LuaScriptInterface::getPosition(lua_State* L, int32_t arg)
{
Position position;
position.x = getField<uint16_t>(L, arg, "x");
position.y = getField<uint16_t>(L, arg, "y");
position.z = getField<uint8_t>(L, arg, "z");
lua_pop(L, 3);
return position;
}
Outfit_t LuaScriptInterface::getOutfit(lua_State* L, int32_t arg)
{
Outfit_t outfit;
outfit.lookMount = getField<uint16_t>(L, arg, "lookMount");
outfit.lookAddons = getField<uint8_t>(L, arg, "lookAddons");
outfit.lookFeet = getField<uint8_t>(L, arg, "lookFeet");
outfit.lookLegs = getField<uint8_t>(L, arg, "lookLegs");
outfit.lookBody = getField<uint8_t>(L, arg, "lookBody");
outfit.lookHead = getField<uint8_t>(L, arg, "lookHead");
outfit.lookTypeEx = getField<uint16_t>(L, arg, "lookTypeEx");
outfit.lookType = getField<uint16_t>(L, arg, "lookType");
lua_pop(L, 8);
return outfit;
}
LuaVariant LuaScriptInterface::getVariant(lua_State* L, int32_t arg)
{
LuaVariant var;
switch (var.type = getField<LuaVariantType_t>(L, arg, "type")) {
case VARIANT_NUMBER: {
var.number = getField<uint32_t>(L, arg, "number");
lua_pop(L, 2);
break;
}
case VARIANT_STRING: {
var.text = getFieldString(L, arg, "string");
lua_pop(L, 2);
break;
}
case VARIANT_POSITION:
case VARIANT_TARGETPOSITION: {
lua_getfield(L, arg, "pos");
var.pos = getPosition(L, lua_gettop(L));
lua_pop(L, 2);
break;
}
default: {
var.type = VARIANT_NONE;
lua_pop(L, 1);
break;
}
}
return var;
}
Thing* LuaScriptInterface::getThing(lua_State* L, int32_t arg)
{
Thing* thing;
if (lua_getmetatable(L, arg) != 0) {
lua_rawgeti(L, -1, 't');
switch(getNumber<uint32_t>(L, -1)) {
case LuaData_Item:
thing = getUserdata<Item>(L, arg);
break;
case LuaData_Container:
thing = getUserdata<Container>(L, arg);
break;
case LuaData_Teleport:
thing = getUserdata<Teleport>(L, arg);
break;
case LuaData_Player:
thing = getUserdata<Player>(L, arg);
break;
case LuaData_Monster:
thing = getUserdata<Monster>(L, arg);
break;
case LuaData_Npc:
thing = getUserdata<Npc>(L, arg);
break;
default:
thing = nullptr;
break;
}
lua_pop(L, 2);
} else {
thing = getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, arg));
}
return thing;
}
Creature* LuaScriptInterface::getCreature(lua_State* L, int32_t arg)
{
if (isUserdata(L, arg)) {
return getUserdata<Creature>(L, arg);
}
return g_game.getCreatureByID(getNumber<uint32_t>(L, arg));
}
Player* LuaScriptInterface::getPlayer(lua_State* L, int32_t arg)
{
if (isUserdata(L, arg)) {
return getUserdata<Player>(L, arg);
}
return g_game.getPlayerByID(getNumber<uint32_t>(L, arg));
}
std::string LuaScriptInterface::getFieldString(lua_State* L, int32_t arg, const std::string& key)
{
lua_getfield(L, arg, key.c_str());
return getString(L, -1);
}
LuaDataType LuaScriptInterface::getUserdataType(lua_State* L, int32_t arg)
{
if (lua_getmetatable(L, arg) == 0) {
return LuaData_Unknown;
}
lua_rawgeti(L, -1, 't');
LuaDataType type = getNumber<LuaDataType>(L, -1);
lua_pop(L, 2);
return type;
}
// Push
void LuaScriptInterface::pushBoolean(lua_State* L, bool value)
{
lua_pushboolean(L, value ? 1 : 0);
}
void LuaScriptInterface::pushPosition(lua_State* L, const Position& position, int32_t stackpos/* = 0*/)
{
lua_createtable(L, 0, 4);
setField(L, "x", position.x);
setField(L, "y", position.y);
setField(L, "z", position.z);
setField(L, "stackpos", stackpos);
setMetatable(L, -1, "Position");
}
void LuaScriptInterface::pushOutfit(lua_State* L, const Outfit_t& outfit)
{
lua_createtable(L, 0, 8);
setField(L, "lookType", outfit.lookType);
setField(L, "lookTypeEx", outfit.lookTypeEx);
setField(L, "lookHead", outfit.lookHead);
setField(L, "lookBody", outfit.lookBody);
setField(L, "lookLegs", outfit.lookLegs);
setField(L, "lookFeet", outfit.lookFeet);
setField(L, "lookAddons", outfit.lookAddons);
setField(L, "lookMount", outfit.lookMount);
}
#define registerEnum(value) { std::string enumName = #value; registerGlobalVariable(enumName.substr(enumName.find_last_of(':') + 1), value); }
#define registerEnumIn(tableName, value) { std::string enumName = #value; registerVariable(tableName, enumName.substr(enumName.find_last_of(':') + 1), value); }
void LuaScriptInterface::registerFunctions()
{
//getPlayerFlagValue(cid, flag)
lua_register(m_luaState, "getPlayerFlagValue", LuaScriptInterface::luaGetPlayerFlagValue);
//getPlayerInstantSpellCount(cid)
lua_register(m_luaState, "getPlayerInstantSpellCount", LuaScriptInterface::luaGetPlayerInstantSpellCount);
//getPlayerInstantSpellInfo(cid, index)
lua_register(m_luaState, "getPlayerInstantSpellInfo", LuaScriptInterface::luaGetPlayerInstantSpellInfo);
//doPlayerAddItem(uid, itemid, <optional: default: 1> count/subtype)
//doPlayerAddItem(cid, itemid, <optional: default: 1> count, <optional: default: 1> canDropOnMap, <optional: default: 1>subtype)
//Returns uid of the created item
lua_register(m_luaState, "doPlayerAddItem", LuaScriptInterface::luaDoPlayerAddItem);
//doCreateItem(itemid, type/count, pos)
//Returns uid of the created item, only works on tiles.
lua_register(m_luaState, "doCreateItem", LuaScriptInterface::luaDoCreateItem);
//doCreateItemEx(itemid, <optional> count/subtype)
lua_register(m_luaState, "doCreateItemEx", LuaScriptInterface::luaDoCreateItemEx);
//doTileAddItemEx(pos, uid)
lua_register(m_luaState, "doTileAddItemEx", LuaScriptInterface::luaDoTileAddItemEx);
//doMoveCreature(cid, direction)
lua_register(m_luaState, "doMoveCreature", LuaScriptInterface::luaDoMoveCreature);
//doSetCreatureLight(cid, lightLevel, lightColor, time)
lua_register(m_luaState, "doSetCreatureLight", LuaScriptInterface::luaDoSetCreatureLight);
//getCreatureCondition(cid, condition[, subId])
lua_register(m_luaState, "getCreatureCondition", LuaScriptInterface::luaGetCreatureCondition);
//isValidUID(uid)
lua_register(m_luaState, "isValidUID", LuaScriptInterface::luaIsValidUID);
//isDepot(uid)
lua_register(m_luaState, "isDepot", LuaScriptInterface::luaIsDepot);
//isMovable(uid)
lua_register(m_luaState, "isMovable", LuaScriptInterface::luaIsMoveable);
//doAddContainerItem(uid, itemid, <optional> count/subtype)
lua_register(m_luaState, "doAddContainerItem", LuaScriptInterface::luaDoAddContainerItem);
//getDepotId(uid)
lua_register(m_luaState, "getDepotId", LuaScriptInterface::luaGetDepotId);
//getWorldTime()
lua_register(m_luaState, "getWorldTime", LuaScriptInterface::luaGetWorldTime);
//getWorldLight()
lua_register(m_luaState, "getWorldLight", LuaScriptInterface::luaGetWorldLight);
//getWorldUpTime()
lua_register(m_luaState, "getWorldUpTime", LuaScriptInterface::luaGetWorldUpTime);
//createCombatArea( {area}, <optional> {extArea} )
lua_register(m_luaState, "createCombatArea", LuaScriptInterface::luaCreateCombatArea);
//createConditionObject(type)
lua_register(m_luaState, "createConditionObject", LuaScriptInterface::luaCreateConditionObject);
//setCombatArea(combat, area)
lua_register(m_luaState, "setCombatArea", LuaScriptInterface::luaSetCombatArea);
//setCombatCondition(combat, condition)
lua_register(m_luaState, "setCombatCondition", LuaScriptInterface::luaSetCombatCondition);
//setCombatParam(combat, key, value)
lua_register(m_luaState, "setCombatParam", LuaScriptInterface::luaSetCombatParam);
//setConditionParam(condition, key, value)
lua_register(m_luaState, "setConditionParam", LuaScriptInterface::luaSetConditionParam);
//addDamageCondition(condition, rounds, time, value)
lua_register(m_luaState, "addDamageCondition", LuaScriptInterface::luaAddDamageCondition);
//addOutfitCondition(condition, lookTypeEx, lookType, lookHead, lookBody, lookLegs, lookFeet)
lua_register(m_luaState, "addOutfitCondition", LuaScriptInterface::luaAddOutfitCondition);
//setCombatCallBack(combat, key, function_name)
lua_register(m_luaState, "setCombatCallback", LuaScriptInterface::luaSetCombatCallBack);
//setCombatFormula(combat, type, mina, minb, maxa, maxb)
lua_register(m_luaState, "setCombatFormula", LuaScriptInterface::luaSetCombatFormula);
//setConditionFormula(combat, mina, minb, maxa, maxb)
lua_register(m_luaState, "setConditionFormula", LuaScriptInterface::luaSetConditionFormula);
//doCombat(cid, combat, param)
lua_register(m_luaState, "doCombat", LuaScriptInterface::luaDoCombat);
//createCombatObject()
lua_register(m_luaState, "createCombatObject", LuaScriptInterface::luaCreateCombatObject);
//doAreaCombatHealth(cid, type, pos, area, min, max, effect)
lua_register(m_luaState, "doAreaCombatHealth", LuaScriptInterface::luaDoAreaCombatHealth);
//doTargetCombatHealth(cid, target, type, min, max, effect)
lua_register(m_luaState, "doTargetCombatHealth", LuaScriptInterface::luaDoTargetCombatHealth);
//doAreaCombatMana(cid, pos, area, min, max, effect)
lua_register(m_luaState, "doAreaCombatMana", LuaScriptInterface::luaDoAreaCombatMana);
//doTargetCombatMana(cid, target, min, max, effect)
lua_register(m_luaState, "doTargetCombatMana", LuaScriptInterface::luaDoTargetCombatMana);
//doAreaCombatCondition(cid, pos, area, condition, effect)
lua_register(m_luaState, "doAreaCombatCondition", LuaScriptInterface::luaDoAreaCombatCondition);
//doTargetCombatCondition(cid, target, condition, effect)
lua_register(m_luaState, "doTargetCombatCondition", LuaScriptInterface::luaDoTargetCombatCondition);
//doAreaCombatDispel(cid, pos, area, type, effect)
lua_register(m_luaState, "doAreaCombatDispel", LuaScriptInterface::luaDoAreaCombatDispel);
//doTargetCombatDispel(cid, target, type, effect)
lua_register(m_luaState, "doTargetCombatDispel", LuaScriptInterface::luaDoTargetCombatDispel);
//doChallengeCreature(cid, target)
lua_register(m_luaState, "doChallengeCreature", LuaScriptInterface::luaDoChallengeCreature);
//doSetMonsterOutfit(cid, name, time)
lua_register(m_luaState, "doSetMonsterOutfit", LuaScriptInterface::luaSetMonsterOutfit);
//doSetItemOutfit(cid, item, time)
lua_register(m_luaState, "doSetItemOutfit", LuaScriptInterface::luaSetItemOutfit);
//doSetCreatureOutfit(cid, outfit, time)
lua_register(m_luaState, "doSetCreatureOutfit", LuaScriptInterface::luaSetCreatureOutfit);
//isInArray(array, value)
lua_register(m_luaState, "isInArray", LuaScriptInterface::luaIsInArray);
//addEvent(callback, delay, ...)
lua_register(m_luaState, "addEvent", LuaScriptInterface::luaAddEvent);
//stopEvent(eventid)
lua_register(m_luaState, "stopEvent", LuaScriptInterface::luaStopEvent);
//saveServer()
lua_register(m_luaState, "saveServer", LuaScriptInterface::luaSaveServer);
//cleanMap()
lua_register(m_luaState, "cleanMap", LuaScriptInterface::luaCleanMap);
//debugPrint(text)
lua_register(m_luaState, "debugPrint", LuaScriptInterface::luaDebugPrint);
//isInWar(cid, target)
lua_register(m_luaState, "isInWar", LuaScriptInterface::luaIsInWar);
//doPlayerSetOfflineTrainingSkill(cid, skill)
lua_register(m_luaState, "doPlayerSetOfflineTrainingSkill", LuaScriptInterface::luaDoPlayerSetOfflineTrainingSkill);
//getWaypointPosition(name)
lua_register(m_luaState, "getWaypointPositionByName", LuaScriptInterface::luaGetWaypointPositionByName);
//sendChannelMessage(channelId, type, message)
lua_register(m_luaState, "sendChannelMessage", LuaScriptInterface::luaSendChannelMessage);
//sendGuildChannelMessage(guildId, type, message)
lua_register(m_luaState, "sendGuildChannelMessage", LuaScriptInterface::luaSendGuildChannelMessage);
#ifndef LUAJIT_VERSION
//bit operations for Lua, based on bitlib project release 24
//bit.bnot, bit.band, bit.bor, bit.bxor, bit.lshift, bit.rshift
luaL_register(m_luaState, "bit", LuaScriptInterface::luaBitReg);
#endif
//configManager table
luaL_register(m_luaState, "configManager", LuaScriptInterface::luaConfigManagerTable);
//db table
luaL_register(m_luaState, "db", LuaScriptInterface::luaDatabaseTable);
//result table
luaL_register(m_luaState, "result", LuaScriptInterface::luaResultTable);
/* New functions */
//registerClass(className, baseClass, newFunction)
//registerTable(tableName)
//registerMethod(className, functionName, function)
//registerMetaMethod(className, functionName, function)
//registerGlobalMethod(functionName, function)
//registerVariable(tableName, name, value)
//registerGlobalVariable(name, value)
//registerEnum(value)
//registerEnumIn(tableName, value)
// Enums
registerEnum(ACCOUNT_TYPE_NORMAL)
registerEnum(ACCOUNT_TYPE_TUTOR)
registerEnum(ACCOUNT_TYPE_SENIORTUTOR)
registerEnum(ACCOUNT_TYPE_GAMEMASTER)
registerEnum(ACCOUNT_TYPE_GOD)
registerEnum(CALLBACK_PARAM_LEVELMAGICVALUE)
registerEnum(CALLBACK_PARAM_SKILLVALUE)
registerEnum(CALLBACK_PARAM_TARGETTILE)
registerEnum(CALLBACK_PARAM_TARGETCREATURE)
registerEnum(COMBAT_FORMULA_UNDEFINED)
registerEnum(COMBAT_FORMULA_LEVELMAGIC)
registerEnum(COMBAT_FORMULA_SKILL)
registerEnum(COMBAT_FORMULA_DAMAGE)
registerEnum(DIRECTION_NORTH)
registerEnum(DIRECTION_EAST)
registerEnum(DIRECTION_SOUTH)
registerEnum(DIRECTION_WEST)
registerEnum(DIRECTION_SOUTHWEST)
registerEnum(DIRECTION_SOUTHEAST)
registerEnum(DIRECTION_NORTHWEST)
registerEnum(DIRECTION_NORTHEAST)
registerEnum(COMBAT_NONE)
registerEnum(COMBAT_PHYSICALDAMAGE)
registerEnum(COMBAT_ENERGYDAMAGE)
registerEnum(COMBAT_EARTHDAMAGE)
registerEnum(COMBAT_FIREDAMAGE)
registerEnum(COMBAT_UNDEFINEDDAMAGE)
registerEnum(COMBAT_LIFEDRAIN)
registerEnum(COMBAT_MANADRAIN)
registerEnum(COMBAT_HEALING)
registerEnum(COMBAT_DROWNDAMAGE)
registerEnum(COMBAT_ICEDAMAGE)
registerEnum(COMBAT_HOLYDAMAGE)
registerEnum(COMBAT_DEATHDAMAGE)
registerEnum(COMBAT_PARAM_TYPE)
registerEnum(COMBAT_PARAM_EFFECT)
registerEnum(COMBAT_PARAM_DISTANCEEFFECT)
registerEnum(COMBAT_PARAM_BLOCKSHIELD)
registerEnum(COMBAT_PARAM_BLOCKARMOR)
registerEnum(COMBAT_PARAM_TARGETCASTERORTOPMOST)
registerEnum(COMBAT_PARAM_CREATEITEM)
registerEnum(COMBAT_PARAM_AGGRESSIVE)
registerEnum(COMBAT_PARAM_DISPEL)
registerEnum(COMBAT_PARAM_USECHARGES)
registerEnum(CONDITION_NONE)
registerEnum(CONDITION_POISON)
registerEnum(CONDITION_FIRE)
registerEnum(CONDITION_ENERGY)
registerEnum(CONDITION_BLEEDING)
registerEnum(CONDITION_HASTE)
registerEnum(CONDITION_PARALYZE)
registerEnum(CONDITION_OUTFIT)
registerEnum(CONDITION_INVISIBLE)
registerEnum(CONDITION_LIGHT)
registerEnum(CONDITION_MANASHIELD)
registerEnum(CONDITION_INFIGHT)
registerEnum(CONDITION_DRUNK)
registerEnum(CONDITION_EXHAUST_WEAPON)
registerEnum(CONDITION_REGENERATION)
registerEnum(CONDITION_SOUL)
registerEnum(CONDITION_DROWN)
registerEnum(CONDITION_MUTED)
registerEnum(CONDITION_CHANNELMUTEDTICKS)
registerEnum(CONDITION_YELLTICKS)
registerEnum(CONDITION_ATTRIBUTES)
registerEnum(CONDITION_FREEZING)
registerEnum(CONDITION_DAZZLED)
registerEnum(CONDITION_CURSED)
registerEnum(CONDITION_EXHAUST_COMBAT)
registerEnum(CONDITION_EXHAUST_HEAL)
registerEnum(CONDITION_PACIFIED)
registerEnum(CONDITION_SPELLCOOLDOWN)
registerEnum(CONDITION_SPELLGROUPCOOLDOWN)
registerEnum(CONDITIONID_DEFAULT)
registerEnum(CONDITIONID_COMBAT)
registerEnum(CONDITIONID_HEAD)
registerEnum(CONDITIONID_NECKLACE)
registerEnum(CONDITIONID_BACKPACK)
registerEnum(CONDITIONID_ARMOR)
registerEnum(CONDITIONID_RIGHT)
registerEnum(CONDITIONID_LEFT)
registerEnum(CONDITIONID_LEGS)
registerEnum(CONDITIONID_FEET)
registerEnum(CONDITIONID_RING)
registerEnum(CONDITIONID_AMMO)
registerEnum(CONDITION_PARAM_OWNER)
registerEnum(CONDITION_PARAM_TICKS)
registerEnum(CONDITION_PARAM_HEALTHGAIN)
registerEnum(CONDITION_PARAM_HEALTHTICKS)
registerEnum(CONDITION_PARAM_MANAGAIN)
registerEnum(CONDITION_PARAM_MANATICKS)
registerEnum(CONDITION_PARAM_DELAYED)
registerEnum(CONDITION_PARAM_SPEED)
registerEnum(CONDITION_PARAM_LIGHT_LEVEL)
registerEnum(CONDITION_PARAM_LIGHT_COLOR)
registerEnum(CONDITION_PARAM_SOULGAIN)
registerEnum(CONDITION_PARAM_SOULTICKS)
registerEnum(CONDITION_PARAM_MINVALUE)
registerEnum(CONDITION_PARAM_MAXVALUE)
registerEnum(CONDITION_PARAM_STARTVALUE)
registerEnum(CONDITION_PARAM_TICKINTERVAL)
registerEnum(CONDITION_PARAM_FORCEUPDATE)
registerEnum(CONDITION_PARAM_SKILL_MELEE)
registerEnum(CONDITION_PARAM_SKILL_FIST)
registerEnum(CONDITION_PARAM_SKILL_CLUB)
registerEnum(CONDITION_PARAM_SKILL_SWORD)
registerEnum(CONDITION_PARAM_SKILL_AXE)
registerEnum(CONDITION_PARAM_SKILL_DISTANCE)
registerEnum(CONDITION_PARAM_SKILL_SHIELD)
registerEnum(CONDITION_PARAM_SKILL_FISHING)
registerEnum(CONDITION_PARAM_STAT_MAXHITPOINTS)
registerEnum(CONDITION_PARAM_STAT_MAXMANAPOINTS)
registerEnum(CONDITION_PARAM_STAT_MAGICPOINTS)
registerEnum(CONDITION_PARAM_STAT_MAXHITPOINTSPERCENT)
registerEnum(CONDITION_PARAM_STAT_MAXMANAPOINTSPERCENT)
registerEnum(CONDITION_PARAM_STAT_MAGICPOINTSPERCENT)
registerEnum(CONDITION_PARAM_PERIODICDAMAGE)
registerEnum(CONDITION_PARAM_SKILL_MELEEPERCENT)
registerEnum(CONDITION_PARAM_SKILL_FISTPERCENT)
registerEnum(CONDITION_PARAM_SKILL_CLUBPERCENT)
registerEnum(CONDITION_PARAM_SKILL_SWORDPERCENT)
registerEnum(CONDITION_PARAM_SKILL_AXEPERCENT)
registerEnum(CONDITION_PARAM_SKILL_DISTANCEPERCENT)
registerEnum(CONDITION_PARAM_SKILL_SHIELDPERCENT)
registerEnum(CONDITION_PARAM_SKILL_FISHINGPERCENT)
registerEnum(CONDITION_PARAM_BUFF_SPELL)
registerEnum(CONDITION_PARAM_SUBID)
registerEnum(CONDITION_PARAM_FIELD)
registerEnum(CONST_ME_NONE)
registerEnum(CONST_ME_DRAWBLOOD)
registerEnum(CONST_ME_LOSEENERGY)
registerEnum(CONST_ME_POFF)
registerEnum(CONST_ME_BLOCKHIT)
registerEnum(CONST_ME_EXPLOSIONAREA)
registerEnum(CONST_ME_EXPLOSIONHIT)
registerEnum(CONST_ME_FIREAREA)
registerEnum(CONST_ME_YELLOW_RINGS)
registerEnum(CONST_ME_GREEN_RINGS)
registerEnum(CONST_ME_HITAREA)
registerEnum(CONST_ME_TELEPORT)
registerEnum(CONST_ME_ENERGYHIT)
registerEnum(CONST_ME_MAGIC_BLUE)
registerEnum(CONST_ME_MAGIC_RED)
registerEnum(CONST_ME_MAGIC_GREEN)
registerEnum(CONST_ME_HITBYFIRE)
registerEnum(CONST_ME_HITBYPOISON)
registerEnum(CONST_ME_MORTAREA)
registerEnum(CONST_ME_SOUND_GREEN)
registerEnum(CONST_ME_SOUND_RED)
registerEnum(CONST_ME_POISONAREA)
registerEnum(CONST_ME_SOUND_YELLOW)
registerEnum(CONST_ME_SOUND_PURPLE)
registerEnum(CONST_ME_SOUND_BLUE)
registerEnum(CONST_ME_SOUND_WHITE)
registerEnum(CONST_ME_BUBBLES)
registerEnum(CONST_ME_CRAPS)
registerEnum(CONST_ME_GIFT_WRAPS)
registerEnum(CONST_ME_FIREWORK_YELLOW)
registerEnum(CONST_ME_FIREWORK_RED)
registerEnum(CONST_ME_FIREWORK_BLUE)
registerEnum(CONST_ME_STUN)
registerEnum(CONST_ME_SLEEP)
registerEnum(CONST_ME_WATERCREATURE)
registerEnum(CONST_ME_GROUNDSHAKER)
registerEnum(CONST_ME_HEARTS)
registerEnum(CONST_ME_FIREATTACK)
registerEnum(CONST_ME_ENERGYAREA)
registerEnum(CONST_ME_SMALLCLOUDS)
registerEnum(CONST_ME_HOLYDAMAGE)
registerEnum(CONST_ME_BIGCLOUDS)
registerEnum(CONST_ME_ICEAREA)
registerEnum(CONST_ME_ICETORNADO)
registerEnum(CONST_ME_ICEATTACK)
registerEnum(CONST_ME_STONES)
registerEnum(CONST_ME_SMALLPLANTS)
registerEnum(CONST_ME_CARNIPHILA)
registerEnum(CONST_ME_PURPLEENERGY)
registerEnum(CONST_ME_YELLOWENERGY)
registerEnum(CONST_ME_HOLYAREA)
registerEnum(CONST_ME_BIGPLANTS)
registerEnum(CONST_ME_CAKE)
registerEnum(CONST_ME_GIANTICE)
registerEnum(CONST_ME_WATERSPLASH)
registerEnum(CONST_ME_PLANTATTACK)
registerEnum(CONST_ME_TUTORIALARROW)
registerEnum(CONST_ME_TUTORIALSQUARE)
registerEnum(CONST_ME_MIRRORHORIZONTAL)
registerEnum(CONST_ME_MIRRORVERTICAL)
registerEnum(CONST_ME_SKULLHORIZONTAL)
registerEnum(CONST_ME_SKULLVERTICAL)
registerEnum(CONST_ME_ASSASSIN)
registerEnum(CONST_ME_STEPSHORIZONTAL)
registerEnum(CONST_ME_BLOODYSTEPS)
registerEnum(CONST_ME_STEPSVERTICAL)
registerEnum(CONST_ME_YALAHARIGHOST)
registerEnum(CONST_ME_BATS)
registerEnum(CONST_ME_SMOKE)
registerEnum(CONST_ME_INSECTS)
registerEnum(CONST_ME_DRAGONHEAD)
registerEnum(CONST_ME_ORCSHAMAN)
registerEnum(CONST_ME_ORCSHAMAN_FIRE)
registerEnum(CONST_ME_THUNDER)
registerEnum(CONST_ME_FERUMBRAS)
registerEnum(CONST_ME_CONFETTI_HORIZONTAL)
registerEnum(CONST_ME_CONFETTI_VERTICAL)
registerEnum(CONST_ME_BLACKSMOKE)
registerEnum(CONST_ME_REDSMOKE)
registerEnum(CONST_ME_YELLOWSMOKE)
registerEnum(CONST_ME_GREENSMOKE)
registerEnum(CONST_ME_PURPLESMOKE)
registerEnum(CONST_ANI_NONE)
registerEnum(CONST_ANI_SPEAR)
registerEnum(CONST_ANI_BOLT)
registerEnum(CONST_ANI_ARROW)
registerEnum(CONST_ANI_FIRE)
registerEnum(CONST_ANI_ENERGY)
registerEnum(CONST_ANI_POISONARROW)
registerEnum(CONST_ANI_BURSTARROW)
registerEnum(CONST_ANI_THROWINGSTAR)
registerEnum(CONST_ANI_THROWINGKNIFE)
registerEnum(CONST_ANI_SMALLSTONE)
registerEnum(CONST_ANI_DEATH)
registerEnum(CONST_ANI_LARGEROCK)
registerEnum(CONST_ANI_SNOWBALL)
registerEnum(CONST_ANI_POWERBOLT)
registerEnum(CONST_ANI_POISON)
registerEnum(CONST_ANI_INFERNALBOLT)
registerEnum(CONST_ANI_HUNTINGSPEAR)
registerEnum(CONST_ANI_ENCHANTEDSPEAR)
registerEnum(CONST_ANI_REDSTAR)
registerEnum(CONST_ANI_GREENSTAR)
registerEnum(CONST_ANI_ROYALSPEAR)
registerEnum(CONST_ANI_SNIPERARROW)
registerEnum(CONST_ANI_ONYXARROW)
registerEnum(CONST_ANI_PIERCINGBOLT)
registerEnum(CONST_ANI_WHIRLWINDSWORD)
registerEnum(CONST_ANI_WHIRLWINDAXE)
registerEnum(CONST_ANI_WHIRLWINDCLUB)
registerEnum(CONST_ANI_ETHEREALSPEAR)
registerEnum(CONST_ANI_ICE)
registerEnum(CONST_ANI_EARTH)
registerEnum(CONST_ANI_HOLY)
registerEnum(CONST_ANI_SUDDENDEATH)
registerEnum(CONST_ANI_FLASHARROW)
registerEnum(CONST_ANI_FLAMMINGARROW)
registerEnum(CONST_ANI_SHIVERARROW)
registerEnum(CONST_ANI_ENERGYBALL)
registerEnum(CONST_ANI_SMALLICE)
registerEnum(CONST_ANI_SMALLHOLY)
registerEnum(CONST_ANI_SMALLEARTH)
registerEnum(CONST_ANI_EARTHARROW)
registerEnum(CONST_ANI_EXPLOSION)
registerEnum(CONST_ANI_CAKE)
registerEnum(CONST_ANI_TARSALARROW)
registerEnum(CONST_ANI_VORTEXBOLT)
registerEnum(CONST_ANI_PRISMATICBOLT)
registerEnum(CONST_ANI_CRYSTALLINEARROW)
registerEnum(CONST_ANI_DRILLBOLT)
registerEnum(CONST_ANI_ENVENOMEDARROW)
registerEnum(CONST_ANI_GLOOTHSPEAR)
registerEnum(CONST_ANI_SIMPLEARROW)
registerEnum(CONST_ANI_WEAPONTYPE)
registerEnum(CONST_PROP_BLOCKSOLID)
registerEnum(CONST_PROP_HASHEIGHT)
registerEnum(CONST_PROP_BLOCKPROJECTILE)
registerEnum(CONST_PROP_BLOCKPATH)
registerEnum(CONST_PROP_ISVERTICAL)
registerEnum(CONST_PROP_ISHORIZONTAL)
registerEnum(CONST_PROP_MOVEABLE)
registerEnum(CONST_PROP_IMMOVABLEBLOCKSOLID)
registerEnum(CONST_PROP_IMMOVABLEBLOCKPATH)
registerEnum(CONST_PROP_IMMOVABLENOFIELDBLOCKPATH)
registerEnum(CONST_PROP_NOFIELDBLOCKPATH)
registerEnum(CONST_PROP_SUPPORTHANGABLE)
registerEnum(CONST_SLOT_HEAD)
registerEnum(CONST_SLOT_NECKLACE)
registerEnum(CONST_SLOT_BACKPACK)
registerEnum(CONST_SLOT_ARMOR)
registerEnum(CONST_SLOT_RIGHT)
registerEnum(CONST_SLOT_LEFT)
registerEnum(CONST_SLOT_LEGS)
registerEnum(CONST_SLOT_FEET)
registerEnum(CONST_SLOT_RING)
registerEnum(CONST_SLOT_AMMO)
registerEnum(GAME_STATE_STARTUP)
registerEnum(GAME_STATE_INIT)
registerEnum(GAME_STATE_NORMAL)
registerEnum(GAME_STATE_CLOSED)
registerEnum(GAME_STATE_SHUTDOWN)
registerEnum(GAME_STATE_CLOSING)
registerEnum(GAME_STATE_MAINTAIN)
registerEnum(MESSAGE_STATUS_CONSOLE_BLUE)
registerEnum(MESSAGE_STATUS_CONSOLE_RED)
registerEnum(MESSAGE_STATUS_DEFAULT)
registerEnum(MESSAGE_STATUS_WARNING)
registerEnum(MESSAGE_EVENT_ADVANCE)
registerEnum(MESSAGE_STATUS_SMALL)
registerEnum(MESSAGE_INFO_DESCR)
registerEnum(MESSAGE_DAMAGE_DEALT)
registerEnum(MESSAGE_DAMAGE_RECEIVED)
registerEnum(MESSAGE_HEALED)
registerEnum(MESSAGE_EXPERIENCE)
registerEnum(MESSAGE_DAMAGE_OTHERS)
registerEnum(MESSAGE_HEALED_OTHERS)
registerEnum(MESSAGE_EXPERIENCE_OTHERS)
registerEnum(MESSAGE_EVENT_DEFAULT)
registerEnum(MESSAGE_EVENT_ORANGE)
registerEnum(MESSAGE_STATUS_CONSOLE_ORANGE)
registerEnum(CREATURETYPE_PLAYER)
registerEnum(CREATURETYPE_MONSTER)
registerEnum(CREATURETYPE_NPC)
registerEnum(CREATURETYPE_SUMMON_OWN)
registerEnum(CREATURETYPE_SUMMON_OTHERS)
registerEnum(CLIENTOS_LINUX)
registerEnum(CLIENTOS_WINDOWS)
registerEnum(CLIENTOS_FLASH)
registerEnum(CLIENTOS_OTCLIENT_LINUX)
registerEnum(CLIENTOS_OTCLIENT_WINDOWS)
registerEnum(CLIENTOS_OTCLIENT_MAC)
registerEnum(ITEM_ATTRIBUTE_NONE)
registerEnum(ITEM_ATTRIBUTE_ACTIONID)
registerEnum(ITEM_ATTRIBUTE_UNIQUEID)
registerEnum(ITEM_ATTRIBUTE_DESCRIPTION)
registerEnum(ITEM_ATTRIBUTE_TEXT)
registerEnum(ITEM_ATTRIBUTE_DATE)
registerEnum(ITEM_ATTRIBUTE_WRITER)
registerEnum(ITEM_ATTRIBUTE_NAME)
registerEnum(ITEM_ATTRIBUTE_ARTICLE)
registerEnum(ITEM_ATTRIBUTE_PLURALNAME)
registerEnum(ITEM_ATTRIBUTE_WEIGHT)
registerEnum(ITEM_ATTRIBUTE_ATTACK)
registerEnum(ITEM_ATTRIBUTE_DEFENSE)
registerEnum(ITEM_ATTRIBUTE_EXTRADEFENSE)
registerEnum(ITEM_ATTRIBUTE_ARMOR)
registerEnum(ITEM_ATTRIBUTE_HITCHANCE)
registerEnum(ITEM_ATTRIBUTE_SHOOTRANGE)
registerEnum(ITEM_ATTRIBUTE_OWNER)
registerEnum(ITEM_ATTRIBUTE_DURATION)
registerEnum(ITEM_ATTRIBUTE_DECAYSTATE)
registerEnum(ITEM_ATTRIBUTE_CORPSEOWNER)
registerEnum(ITEM_ATTRIBUTE_CHARGES)
registerEnum(ITEM_ATTRIBUTE_FLUIDTYPE)
registerEnum(ITEM_ATTRIBUTE_DOORID)
registerEnum(ITEM_TYPE_DEPOT)
registerEnum(ITEM_TYPE_MAILBOX)
registerEnum(ITEM_TYPE_TRASHHOLDER)
registerEnum(ITEM_TYPE_CONTAINER)
registerEnum(ITEM_TYPE_DOOR)
registerEnum(ITEM_TYPE_MAGICFIELD)
registerEnum(ITEM_TYPE_TELEPORT)
registerEnum(ITEM_TYPE_BED)
registerEnum(ITEM_TYPE_KEY)
registerEnum(ITEM_TYPE_RUNE)
registerEnum(ITEM_BAG)
registerEnum(ITEM_GOLD_COIN)
registerEnum(ITEM_PLATINUM_COIN)
registerEnum(ITEM_CRYSTAL_COIN)
registerEnum(ITEM_AMULETOFLOSS)
registerEnum(ITEM_PARCEL)
registerEnum(ITEM_LABEL)
registerEnum(ITEM_FIREFIELD_PVP_FULL)
registerEnum(ITEM_FIREFIELD_PVP_MEDIUM)
registerEnum(ITEM_FIREFIELD_PVP_SMALL)
registerEnum(ITEM_FIREFIELD_PERSISTENT_FULL)
registerEnum(ITEM_FIREFIELD_PERSISTENT_MEDIUM)
registerEnum(ITEM_FIREFIELD_PERSISTENT_SMALL)
registerEnum(ITEM_FIREFIELD_NOPVP)
registerEnum(ITEM_POISONFIELD_PVP)
registerEnum(ITEM_POISONFIELD_PERSISTENT)
registerEnum(ITEM_POISONFIELD_NOPVP)
registerEnum(ITEM_ENERGYFIELD_PVP)
registerEnum(ITEM_ENERGYFIELD_PERSISTENT)
registerEnum(ITEM_ENERGYFIELD_NOPVP)
registerEnum(ITEM_MAGICWALL)
registerEnum(ITEM_MAGICWALL_PERSISTENT)
registerEnum(ITEM_MAGICWALL_SAFE)
registerEnum(ITEM_WILDGROWTH)
registerEnum(ITEM_WILDGROWTH_PERSISTENT)
registerEnum(ITEM_WILDGROWTH_SAFE)
registerEnum(PlayerFlag_CannotUseCombat)
registerEnum(PlayerFlag_CannotAttackPlayer)
registerEnum(PlayerFlag_CannotAttackMonster)
registerEnum(PlayerFlag_CannotBeAttacked)
registerEnum(PlayerFlag_CanConvinceAll)
registerEnum(PlayerFlag_CanSummonAll)
registerEnum(PlayerFlag_CanIllusionAll)
registerEnum(PlayerFlag_CanSenseInvisibility)
registerEnum(PlayerFlag_IgnoredByMonsters)
registerEnum(PlayerFlag_NotGainInFight)
registerEnum(PlayerFlag_HasInfiniteMana)
registerEnum(PlayerFlag_HasInfiniteSoul)
registerEnum(PlayerFlag_HasNoExhaustion)
registerEnum(PlayerFlag_CannotUseSpells)
registerEnum(PlayerFlag_CannotPickupItem)
registerEnum(PlayerFlag_CanAlwaysLogin)
registerEnum(PlayerFlag_CanBroadcast)
registerEnum(PlayerFlag_CanEditHouses)
registerEnum(PlayerFlag_CannotBeBanned)
registerEnum(PlayerFlag_CannotBePushed)
registerEnum(PlayerFlag_HasInfiniteCapacity)
registerEnum(PlayerFlag_CanPushAllCreatures)
registerEnum(PlayerFlag_CanTalkRedPrivate)
registerEnum(PlayerFlag_CanTalkRedChannel)
registerEnum(PlayerFlag_TalkOrangeHelpChannel)
registerEnum(PlayerFlag_NotGainExperience)
registerEnum(PlayerFlag_NotGainMana)
registerEnum(PlayerFlag_NotGainHealth)
registerEnum(PlayerFlag_NotGainSkill)
registerEnum(PlayerFlag_SetMaxSpeed)
registerEnum(PlayerFlag_SpecialVIP)
registerEnum(PlayerFlag_NotGenerateLoot)
registerEnum(PlayerFlag_CanTalkRedChannelAnonymous)
registerEnum(PlayerFlag_IgnoreProtectionZone)
registerEnum(PlayerFlag_IgnoreSpellCheck)
registerEnum(PlayerFlag_IgnoreWeaponCheck)
registerEnum(PlayerFlag_CannotBeMuted)
registerEnum(PlayerFlag_IsAlwaysPremium)
registerEnum(PLAYERSEX_FEMALE)
registerEnum(PLAYERSEX_MALE)
registerEnum(VOCATION_NONE)
registerEnum(SKILL_FIST)
registerEnum(SKILL_CLUB)
registerEnum(SKILL_SWORD)
registerEnum(SKILL_AXE)
registerEnum(SKILL_DISTANCE)
registerEnum(SKILL_SHIELD)
registerEnum(SKILL_FISHING)
registerEnum(SKILL_MAGLEVEL)
registerEnum(SKILL_LEVEL)
registerEnum(SKULL_NONE)
registerEnum(SKULL_YELLOW)
registerEnum(SKULL_GREEN)
registerEnum(SKULL_WHITE)
registerEnum(SKULL_RED)
registerEnum(SKULL_BLACK)
registerEnum(SKULL_ORANGE)
registerEnum(TALKTYPE_SAY)
registerEnum(TALKTYPE_WHISPER)
registerEnum(TALKTYPE_YELL)
registerEnum(TALKTYPE_PRIVATE_FROM)
registerEnum(TALKTYPE_PRIVATE_TO)
registerEnum(TALKTYPE_CHANNEL_Y)
registerEnum(TALKTYPE_CHANNEL_O)
registerEnum(TALKTYPE_PRIVATE_NP)
registerEnum(TALKTYPE_PRIVATE_PN)
registerEnum(TALKTYPE_BROADCAST)
registerEnum(TALKTYPE_CHANNEL_R1)
registerEnum(TALKTYPE_PRIVATE_RED_FROM)
registerEnum(TALKTYPE_PRIVATE_RED_TO)
registerEnum(TALKTYPE_MONSTER_SAY)
registerEnum(TALKTYPE_MONSTER_YELL)
registerEnum(TALKTYPE_CHANNEL_R2)
registerEnum(TEXTCOLOR_BLUE)
registerEnum(TEXTCOLOR_LIGHTGREEN)
registerEnum(TEXTCOLOR_LIGHTBLUE)
registerEnum(TEXTCOLOR_MAYABLUE)
registerEnum(TEXTCOLOR_DARKRED)
registerEnum(TEXTCOLOR_LIGHTGREY)
registerEnum(TEXTCOLOR_SKYBLUE)
registerEnum(TEXTCOLOR_PURPLE)
registerEnum(TEXTCOLOR_RED)
registerEnum(TEXTCOLOR_ORANGE)
registerEnum(TEXTCOLOR_YELLOW)
registerEnum(TEXTCOLOR_WHITE_EXP)
registerEnum(TEXTCOLOR_NONE)
registerEnum(TILESTATE_NONE)
registerEnum(TILESTATE_PROTECTIONZONE)
registerEnum(TILESTATE_DEPRECATED_HOUSE)
registerEnum(TILESTATE_NOPVPZONE)
registerEnum(TILESTATE_NOLOGOUT)
registerEnum(TILESTATE_PVPZONE)
registerEnum(TILESTATE_REFRESH)
registerEnum(TILESTATE_HOUSE)
registerEnum(TILESTATE_FLOORCHANGE)
registerEnum(TILESTATE_FLOORCHANGE_DOWN)
registerEnum(TILESTATE_FLOORCHANGE_NORTH)
registerEnum(TILESTATE_FLOORCHANGE_SOUTH)
registerEnum(TILESTATE_FLOORCHANGE_EAST)
registerEnum(TILESTATE_FLOORCHANGE_WEST)
registerEnum(TILESTATE_TELEPORT)
registerEnum(TILESTATE_MAGICFIELD)
registerEnum(TILESTATE_MAILBOX)
registerEnum(TILESTATE_TRASHHOLDER)
registerEnum(TILESTATE_BED)
registerEnum(TILESTATE_DEPOT)
registerEnum(TILESTATE_BLOCKSOLID)
registerEnum(TILESTATE_BLOCKPATH)
registerEnum(TILESTATE_IMMOVABLEBLOCKSOLID)
registerEnum(TILESTATE_IMMOVABLEBLOCKPATH)
registerEnum(TILESTATE_IMMOVABLENOFIELDBLOCKPATH)
registerEnum(TILESTATE_NOFIELDBLOCKPATH)
registerEnum(TILESTATE_DYNAMIC_TILE)
registerEnum(TILESTATE_FLOORCHANGE_SOUTH_ALT)
registerEnum(TILESTATE_FLOORCHANGE_EAST_ALT)
registerEnum(TILESTATE_SUPPORTS_HANGABLE)
registerEnum(WEAPON_NONE)
registerEnum(WEAPON_SWORD)
registerEnum(WEAPON_CLUB)
registerEnum(WEAPON_AXE)
registerEnum(WEAPON_SHIELD)
registerEnum(WEAPON_DISTANCE)
registerEnum(WEAPON_WAND)
registerEnum(WEAPON_AMMO)
registerEnum(WORLD_TYPE_NO_PVP)
registerEnum(WORLD_TYPE_PVP)
registerEnum(WORLD_TYPE_PVP_ENFORCED)
// Use with container:addItem, container:addItemEx and possibly other functions.
registerEnum(FLAG_NOLIMIT)
registerEnum(FLAG_IGNOREBLOCKITEM)
registerEnum(FLAG_IGNOREBLOCKCREATURE)
registerEnum(FLAG_CHILDISOWNER)
registerEnum(FLAG_PATHFINDING)
registerEnum(FLAG_IGNOREFIELDDAMAGE)
registerEnum(FLAG_IGNORENOTMOVEABLE)
registerEnum(FLAG_IGNOREAUTOSTACK)
// Use with itemType:getSlotPosition
registerEnum(SLOTP_WHEREEVER)
registerEnum(SLOTP_HEAD)
registerEnum(SLOTP_NECKLACE)
registerEnum(SLOTP_BACKPACK)
registerEnum(SLOTP_ARMOR)
registerEnum(SLOTP_RIGHT)
registerEnum(SLOTP_LEFT)
registerEnum(SLOTP_LEGS)
registerEnum(SLOTP_FEET)
registerEnum(SLOTP_RING)
registerEnum(SLOTP_AMMO)
registerEnum(SLOTP_DEPOT)
registerEnum(SLOTP_TWO_HAND)
// Use with combat functions
registerEnum(ORIGIN_NONE)
registerEnum(ORIGIN_CONDITION)
registerEnum(ORIGIN_SPELL)
registerEnum(ORIGIN_MELEE)
registerEnum(ORIGIN_RANGED)
// Use with house:getAccessList, house:setAccessList
registerEnum(GUEST_LIST)
registerEnum(SUBOWNER_LIST)
// Use with npc:setSpeechBubble
registerEnum(SPEECHBUBBLE_NONE)
registerEnum(SPEECHBUBBLE_NORMAL)
registerEnum(SPEECHBUBBLE_TRADE)
registerEnum(SPEECHBUBBLE_QUEST)
registerEnum(SPEECHBUBBLE_QUESTTRADER)
// Use with player:addMapMark
registerEnum(MAPMARK_TICK)
registerEnum(MAPMARK_QUESTION)
registerEnum(MAPMARK_EXCLAMATION)
registerEnum(MAPMARK_STAR)
registerEnum(MAPMARK_CROSS)
registerEnum(MAPMARK_TEMPLE)
registerEnum(MAPMARK_KISS)
registerEnum(MAPMARK_SHOVEL)
registerEnum(MAPMARK_SWORD)
registerEnum(MAPMARK_FLAG)
registerEnum(MAPMARK_LOCK)
registerEnum(MAPMARK_BAG)
registerEnum(MAPMARK_SKULL)
registerEnum(MAPMARK_DOLLAR)
registerEnum(MAPMARK_REDNORTH)
registerEnum(MAPMARK_REDSOUTH)
registerEnum(MAPMARK_REDEAST)
registerEnum(MAPMARK_REDWEST)
registerEnum(MAPMARK_GREENNORTH)
registerEnum(MAPMARK_GREENSOUTH)
// Use with Game.getReturnMessage
registerEnum(RETURNVALUE_NOERROR)
registerEnum(RETURNVALUE_NOTPOSSIBLE)
registerEnum(RETURNVALUE_NOTENOUGHROOM)
registerEnum(RETURNVALUE_PLAYERISPZLOCKED)
registerEnum(RETURNVALUE_PLAYERISNOTINVITED)
registerEnum(RETURNVALUE_CANNOTTHROW)
registerEnum(RETURNVALUE_THEREISNOWAY)
registerEnum(RETURNVALUE_DESTINATIONOUTOFREACH)
registerEnum(RETURNVALUE_CREATUREBLOCK)
registerEnum(RETURNVALUE_NOTMOVEABLE)
registerEnum(RETURNVALUE_DROPTWOHANDEDITEM)
registerEnum(RETURNVALUE_BOTHHANDSNEEDTOBEFREE)
registerEnum(RETURNVALUE_CANONLYUSEONEWEAPON)
registerEnum(RETURNVALUE_NEEDEXCHANGE)
registerEnum(RETURNVALUE_CANNOTBEDRESSED)
registerEnum(RETURNVALUE_PUTTHISOBJECTINYOURHAND)
registerEnum(RETURNVALUE_PUTTHISOBJECTINBOTHHANDS)
registerEnum(RETURNVALUE_TOOFARAWAY)
registerEnum(RETURNVALUE_FIRSTGODOWNSTAIRS)
registerEnum(RETURNVALUE_FIRSTGOUPSTAIRS)
registerEnum(RETURNVALUE_CONTAINERNOTENOUGHROOM)
registerEnum(RETURNVALUE_NOTENOUGHCAPACITY)
registerEnum(RETURNVALUE_CANNOTPICKUP)
registerEnum(RETURNVALUE_THISISIMPOSSIBLE)
registerEnum(RETURNVALUE_DEPOTISFULL)
registerEnum(RETURNVALUE_CREATUREDOESNOTEXIST)
registerEnum(RETURNVALUE_CANNOTUSETHISOBJECT)
registerEnum(RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE)
registerEnum(RETURNVALUE_NOTREQUIREDLEVELTOUSERUNE)
registerEnum(RETURNVALUE_YOUAREALREADYTRADING)
registerEnum(RETURNVALUE_THISPLAYERISALREADYTRADING)
registerEnum(RETURNVALUE_YOUMAYNOTLOGOUTDURINGAFIGHT)
registerEnum(RETURNVALUE_DIRECTPLAYERSHOOT)
registerEnum(RETURNVALUE_NOTENOUGHLEVEL)
registerEnum(RETURNVALUE_NOTENOUGHMAGICLEVEL)
registerEnum(RETURNVALUE_NOTENOUGHMANA)
registerEnum(RETURNVALUE_NOTENOUGHSOUL)
registerEnum(RETURNVALUE_YOUAREEXHAUSTED)
registerEnum(RETURNVALUE_PLAYERISNOTREACHABLE)
registerEnum(RETURNVALUE_CANONLYUSETHISRUNEONCREATURES)
registerEnum(RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE)
registerEnum(RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER)
registerEnum(RETURNVALUE_YOUMAYNOTATTACKAPERSONINPROTECTIONZONE)
registerEnum(RETURNVALUE_YOUMAYNOTATTACKAPERSONWHILEINPROTECTIONZONE)
registerEnum(RETURNVALUE_YOUMAYNOTATTACKTHISCREATURE)
registerEnum(RETURNVALUE_YOUCANONLYUSEITONCREATURES)
registerEnum(RETURNVALUE_CREATUREISNOTREACHABLE)
registerEnum(RETURNVALUE_TURNSECUREMODETOATTACKUNMARKEDPLAYERS)
registerEnum(RETURNVALUE_YOUNEEDPREMIUMACCOUNT)
registerEnum(RETURNVALUE_YOUNEEDTOLEARNTHISSPELL)
registerEnum(RETURNVALUE_YOURVOCATIONCANNOTUSETHISSPELL)
registerEnum(RETURNVALUE_YOUNEEDAWEAPONTOUSETHISSPELL)
registerEnum(RETURNVALUE_PLAYERISPZLOCKEDLEAVEPVPZONE)
registerEnum(RETURNVALUE_PLAYERISPZLOCKEDENTERPVPZONE)
registerEnum(RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE)
registerEnum(RETURNVALUE_YOUCANNOTLOGOUTHERE)
registerEnum(RETURNVALUE_YOUNEEDAMAGICITEMTOCASTSPELL)
registerEnum(RETURNVALUE_CANNOTCONJUREITEMHERE)
registerEnum(RETURNVALUE_YOUNEEDTOSPLITYOURSPEARS)
registerEnum(RETURNVALUE_NAMEISTOOAMBIGIOUS)
registerEnum(RETURNVALUE_CANONLYUSEONESHIELD)
registerEnum(RETURNVALUE_NOPARTYMEMBERSINRANGE)
registerEnum(RETURNVALUE_YOUARENOTTHEOWNER)
// _G
registerGlobalVariable("INDEX_WHEREEVER", INDEX_WHEREEVER);
registerGlobalBoolean("VIRTUAL_PARENT", true);
registerGlobalMethod("isType", LuaScriptInterface::luaIsType);
registerGlobalMethod("rawgetmetatable", LuaScriptInterface::luaRawGetMetatable);
// configKeys
registerTable("configKeys");
registerEnumIn("configKeys", ConfigManager::ALLOW_CHANGEOUTFIT)
registerEnumIn("configKeys", ConfigManager::ONE_PLAYER_ON_ACCOUNT)
registerEnumIn("configKeys", ConfigManager::AIMBOT_HOTKEY_ENABLED)
registerEnumIn("configKeys", ConfigManager::REMOVE_RUNE_CHARGES)
registerEnumIn("configKeys", ConfigManager::EXPERIENCE_FROM_PLAYERS)
registerEnumIn("configKeys", ConfigManager::FREE_PREMIUM)
registerEnumIn("configKeys", ConfigManager::REPLACE_KICK_ON_LOGIN)
registerEnumIn("configKeys", ConfigManager::ALLOW_CLONES)
registerEnumIn("configKeys", ConfigManager::BIND_ONLY_GLOBAL_ADDRESS)
registerEnumIn("configKeys", ConfigManager::OPTIMIZE_DATABASE)
registerEnumIn("configKeys", ConfigManager::MARKET_PREMIUM)
registerEnumIn("configKeys", ConfigManager::EMOTE_SPELLS)
registerEnumIn("configKeys", ConfigManager::STAMINA_SYSTEM)
registerEnumIn("configKeys", ConfigManager::WARN_UNSAFE_SCRIPTS)
registerEnumIn("configKeys", ConfigManager::CONVERT_UNSAFE_SCRIPTS)
registerEnumIn("configKeys", ConfigManager::CLASSIC_EQUIPMENT_SLOTS)
registerEnumIn("configKeys", ConfigManager::MAP_NAME)
registerEnumIn("configKeys", ConfigManager::HOUSE_RENT_PERIOD)
registerEnumIn("configKeys", ConfigManager::SERVER_NAME)
registerEnumIn("configKeys", ConfigManager::OWNER_NAME)
registerEnumIn("configKeys", ConfigManager::OWNER_EMAIL)
registerEnumIn("configKeys", ConfigManager::URL)
registerEnumIn("configKeys", ConfigManager::LOCATION)
registerEnumIn("configKeys", ConfigManager::IP)
registerEnumIn("configKeys", ConfigManager::MOTD)
registerEnumIn("configKeys", ConfigManager::WORLD_TYPE)
registerEnumIn("configKeys", ConfigManager::MYSQL_HOST)
registerEnumIn("configKeys", ConfigManager::MYSQL_USER)
registerEnumIn("configKeys", ConfigManager::MYSQL_PASS)
registerEnumIn("configKeys", ConfigManager::MYSQL_DB)
registerEnumIn("configKeys", ConfigManager::MYSQL_SOCK)
registerEnumIn("configKeys", ConfigManager::DEFAULT_PRIORITY)
registerEnumIn("configKeys", ConfigManager::MAP_AUTHOR)
registerEnumIn("configKeys", ConfigManager::SQL_PORT)
registerEnumIn("configKeys", ConfigManager::MAX_PLAYERS)
registerEnumIn("configKeys", ConfigManager::PZ_LOCKED)
registerEnumIn("configKeys", ConfigManager::DEFAULT_DESPAWNRANGE)
registerEnumIn("configKeys", ConfigManager::DEFAULT_DESPAWNRADIUS)
registerEnumIn("configKeys", ConfigManager::RATE_EXPERIENCE)
registerEnumIn("configKeys", ConfigManager::RATE_SKILL)
registerEnumIn("configKeys", ConfigManager::RATE_LOOT)
registerEnumIn("configKeys", ConfigManager::RATE_MAGIC)
registerEnumIn("configKeys", ConfigManager::RATE_SPAWN)
registerEnumIn("configKeys", ConfigManager::HOUSE_PRICE)
registerEnumIn("configKeys", ConfigManager::KILLS_TO_RED)
registerEnumIn("configKeys", ConfigManager::KILLS_TO_BLACK)
registerEnumIn("configKeys", ConfigManager::MAX_MESSAGEBUFFER)
registerEnumIn("configKeys", ConfigManager::ACTIONS_DELAY_INTERVAL)
registerEnumIn("configKeys", ConfigManager::EX_ACTIONS_DELAY_INTERVAL)
registerEnumIn("configKeys", ConfigManager::KICK_AFTER_MINUTES)
registerEnumIn("configKeys", ConfigManager::PROTECTION_LEVEL)
registerEnumIn("configKeys", ConfigManager::DEATH_LOSE_PERCENT)
registerEnumIn("configKeys", ConfigManager::STATUSQUERY_TIMEOUT)
registerEnumIn("configKeys", ConfigManager::FRAG_TIME)
registerEnumIn("configKeys", ConfigManager::WHITE_SKULL_TIME)
registerEnumIn("configKeys", ConfigManager::GAME_PORT)
registerEnumIn("configKeys", ConfigManager::LOGIN_PORT)
registerEnumIn("configKeys", ConfigManager::STATUS_PORT)
registerEnumIn("configKeys", ConfigManager::STAIRHOP_DELAY)
registerEnumIn("configKeys", ConfigManager::MARKET_OFFER_DURATION)
registerEnumIn("configKeys", ConfigManager::CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES)
registerEnumIn("configKeys", ConfigManager::MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER)
registerEnumIn("configKeys", ConfigManager::EXP_FROM_PLAYERS_LEVEL_RANGE)
registerEnumIn("configKeys", ConfigManager::MAX_PACKETS_PER_SECOND)
// os
registerMethod("os", "mtime", LuaScriptInterface::luaSystemTime);
// table
registerMethod("table", "create", LuaScriptInterface::luaTableCreate);
// Game
registerTable("Game");
registerMethod("Game", "getSpectators", LuaScriptInterface::luaGameGetSpectators);
registerMethod("Game", "getPlayers", LuaScriptInterface::luaGameGetPlayers);
registerMethod("Game", "loadMap", LuaScriptInterface::luaGameLoadMap);
registerMethod("Game", "getExperienceStage", LuaScriptInterface::luaGameGetExperienceStage);
registerMethod("Game", "getMonsterCount", LuaScriptInterface::luaGameGetMonsterCount);
registerMethod("Game", "getPlayerCount", LuaScriptInterface::luaGameGetPlayerCount);
registerMethod("Game", "getNpcCount", LuaScriptInterface::luaGameGetNpcCount);
registerMethod("Game", "getTowns", LuaScriptInterface::luaGameGetTowns);
registerMethod("Game", "getHouses", LuaScriptInterface::luaGameGetHouses);
registerMethod("Game", "getGameState", LuaScriptInterface::luaGameGetGameState);
registerMethod("Game", "setGameState", LuaScriptInterface::luaGameSetGameState);
registerMethod("Game", "getWorldType", LuaScriptInterface::luaGameGetWorldType);
registerMethod("Game", "setWorldType", LuaScriptInterface::luaGameSetWorldType);
registerMethod("Game", "getReturnMessage", LuaScriptInterface::luaGameGetReturnMessage);
registerMethod("Game", "createItem", LuaScriptInterface::luaGameCreateItem);
registerMethod("Game", "createContainer", LuaScriptInterface::luaGameCreateContainer);
registerMethod("Game", "createMonster", LuaScriptInterface::luaGameCreateMonster);
registerMethod("Game", "createNpc", LuaScriptInterface::luaGameCreateNpc);
registerMethod("Game", "createTile", LuaScriptInterface::luaGameCreateTile);
registerMethod("Game", "startRaid", LuaScriptInterface::luaGameStartRaid);
// Variant
registerClass("Variant", "", LuaScriptInterface::luaVariantCreate);
registerMethod("Variant", "getNumber", LuaScriptInterface::luaVariantGetNumber);
registerMethod("Variant", "getString", LuaScriptInterface::luaVariantGetString);
registerMethod("Variant", "getPosition", LuaScriptInterface::luaVariantGetPosition);
// Position
registerClass("Position", "", LuaScriptInterface::luaPositionCreate);
registerMetaMethod("Position", "__add", LuaScriptInterface::luaPositionAdd);
registerMetaMethod("Position", "__sub", LuaScriptInterface::luaPositionSub);
registerMetaMethod("Position", "__eq", LuaScriptInterface::luaPositionCompare);
registerMethod("Position", "getDistance", LuaScriptInterface::luaPositionGetDistance);
registerMethod("Position", "isSightClear", LuaScriptInterface::luaPositionIsSightClear);
registerMethod("Position", "sendMagicEffect", LuaScriptInterface::luaPositionSendMagicEffect);
registerMethod("Position", "sendDistanceEffect", LuaScriptInterface::luaPositionSendDistanceEffect);
// Tile
registerClass("Tile", "", LuaScriptInterface::luaTileCreate);
registerMetaMethod("Tile", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Tile", "getPosition", LuaScriptInterface::luaTileGetPosition);
registerMethod("Tile", "getGround", LuaScriptInterface::luaTileGetGround);
registerMethod("Tile", "getThing", LuaScriptInterface::luaTileGetThing);
registerMethod("Tile", "getThingCount", LuaScriptInterface::luaTileGetThingCount);
registerMethod("Tile", "getTopVisibleThing", LuaScriptInterface::luaTileGetTopVisibleThing);
registerMethod("Tile", "getTopTopItem", LuaScriptInterface::luaTileGetTopTopItem);
registerMethod("Tile", "getTopDownItem", LuaScriptInterface::luaTileGetTopDownItem);
registerMethod("Tile", "getFieldItem", LuaScriptInterface::luaTileGetFieldItem);
registerMethod("Tile", "getItemById", LuaScriptInterface::luaTileGetItemById);
registerMethod("Tile", "getItemByType", LuaScriptInterface::luaTileGetItemByType);
registerMethod("Tile", "getItemByTopOrder", LuaScriptInterface::luaTileGetItemByTopOrder);
registerMethod("Tile", "getItemCountById", LuaScriptInterface::luaTileGetItemCountById);
registerMethod("Tile", "getBottomCreature", LuaScriptInterface::luaTileGetBottomCreature);
registerMethod("Tile", "getTopCreature", LuaScriptInterface::luaTileGetTopCreature);
registerMethod("Tile", "getBottomVisibleCreature", LuaScriptInterface::luaTileGetBottomVisibleCreature);
registerMethod("Tile", "getTopVisibleCreature", LuaScriptInterface::luaTileGetTopVisibleCreature);
registerMethod("Tile", "getItems", LuaScriptInterface::luaTileGetItems);
registerMethod("Tile", "getItemCount", LuaScriptInterface::luaTileGetItemCount);
registerMethod("Tile", "getDownItemCount", LuaScriptInterface::luaTileGetDownItemCount);
registerMethod("Tile", "getTopItemCount", LuaScriptInterface::luaTileGetTopItemCount);
registerMethod("Tile", "getCreatures", LuaScriptInterface::luaTileGetCreatures);
registerMethod("Tile", "getCreatureCount", LuaScriptInterface::luaTileGetCreatureCount);
registerMethod("Tile", "getThingIndex", LuaScriptInterface::luaTileGetThingIndex);
registerMethod("Tile", "hasProperty", LuaScriptInterface::luaTileHasProperty);
registerMethod("Tile", "hasFlag", LuaScriptInterface::luaTileHasFlag);
registerMethod("Tile", "queryAdd", LuaScriptInterface::luaTileQueryAdd);
registerMethod("Tile", "getHouse", LuaScriptInterface::luaTileGetHouse);
// NetworkMessage
registerClass("NetworkMessage", "", LuaScriptInterface::luaNetworkMessageCreate);
registerMetaMethod("NetworkMessage", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMetaMethod("NetworkMessage", "__gc", LuaScriptInterface::luaNetworkMessageDelete);
registerMethod("NetworkMessage", "delete", LuaScriptInterface::luaNetworkMessageDelete);
registerMethod("NetworkMessage", "getByte", LuaScriptInterface::luaNetworkMessageGetByte);
registerMethod("NetworkMessage", "getU16", LuaScriptInterface::luaNetworkMessageGetU16);
registerMethod("NetworkMessage", "getU32", LuaScriptInterface::luaNetworkMessageGetU32);
registerMethod("NetworkMessage", "getU64", LuaScriptInterface::luaNetworkMessageGetU64);
registerMethod("NetworkMessage", "getString", LuaScriptInterface::luaNetworkMessageGetString);
registerMethod("NetworkMessage", "getPosition", LuaScriptInterface::luaNetworkMessageGetPosition);
registerMethod("NetworkMessage", "addByte", LuaScriptInterface::luaNetworkMessageAddByte);
registerMethod("NetworkMessage", "addU16", LuaScriptInterface::luaNetworkMessageAddU16);
registerMethod("NetworkMessage", "addU32", LuaScriptInterface::luaNetworkMessageAddU32);
registerMethod("NetworkMessage", "addU64", LuaScriptInterface::luaNetworkMessageAddU64);
registerMethod("NetworkMessage", "addString", LuaScriptInterface::luaNetworkMessageAddString);
registerMethod("NetworkMessage", "addPosition", LuaScriptInterface::luaNetworkMessageAddPosition);
registerMethod("NetworkMessage", "addDouble", LuaScriptInterface::luaNetworkMessageAddDouble);
registerMethod("NetworkMessage", "addItem", LuaScriptInterface::luaNetworkMessageAddItem);
registerMethod("NetworkMessage", "addItemId", LuaScriptInterface::luaNetworkMessageAddItemId);
registerMethod("NetworkMessage", "reset", LuaScriptInterface::luaNetworkMessageReset);
registerMethod("NetworkMessage", "skipBytes", LuaScriptInterface::luaNetworkMessageSkipBytes);
registerMethod("NetworkMessage", "sendToPlayer", LuaScriptInterface::luaNetworkMessageSendToPlayer);
// ModalWindow
registerClass("ModalWindow", "", LuaScriptInterface::luaModalWindowCreate);
registerMetaMethod("ModalWindow", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMetaMethod("ModalWindow", "__gc", LuaScriptInterface::luaModalWindowDelete);
registerMethod("ModalWindow", "delete", LuaScriptInterface::luaModalWindowDelete);
registerMethod("ModalWindow", "getId", LuaScriptInterface::luaModalWindowGetId);
registerMethod("ModalWindow", "getTitle", LuaScriptInterface::luaModalWindowGetTitle);
registerMethod("ModalWindow", "getMessage", LuaScriptInterface::luaModalWindowGetMessage);
registerMethod("ModalWindow", "setTitle", LuaScriptInterface::luaModalWindowSetTitle);
registerMethod("ModalWindow", "setMessage", LuaScriptInterface::luaModalWindowSetMessage);
registerMethod("ModalWindow", "getButtonCount", LuaScriptInterface::luaModalWindowGetButtonCount);
registerMethod("ModalWindow", "getChoiceCount", LuaScriptInterface::luaModalWindowGetChoiceCount);
registerMethod("ModalWindow", "addButton", LuaScriptInterface::luaModalWindowAddButton);
registerMethod("ModalWindow", "addChoice", LuaScriptInterface::luaModalWindowAddChoice);
registerMethod("ModalWindow", "getDefaultEnterButton", LuaScriptInterface::luaModalWindowGetDefaultEnterButton);
registerMethod("ModalWindow", "setDefaultEnterButton", LuaScriptInterface::luaModalWindowSetDefaultEnterButton);
registerMethod("ModalWindow", "getDefaultEscapeButton", LuaScriptInterface::luaModalWindowGetDefaultEscapeButton);
registerMethod("ModalWindow", "setDefaultEscapeButton", LuaScriptInterface::luaModalWindowSetDefaultEscapeButton);
registerMethod("ModalWindow", "hasPriority", LuaScriptInterface::luaModalWindowHasPriority);
registerMethod("ModalWindow", "setPriority", LuaScriptInterface::luaModalWindowSetPriority);
registerMethod("ModalWindow", "sendToPlayer", LuaScriptInterface::luaModalWindowSendToPlayer);
// Item
registerClass("Item", "", LuaScriptInterface::luaItemCreate);
registerMetaMethod("Item", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Item", "isItem", LuaScriptInterface::luaItemIsItem);
registerMethod("Item", "getParent", LuaScriptInterface::luaItemGetParent);
registerMethod("Item", "getTopParent", LuaScriptInterface::luaItemGetTopParent);
registerMethod("Item", "getId", LuaScriptInterface::luaItemGetId);
registerMethod("Item", "clone", LuaScriptInterface::luaItemClone);
registerMethod("Item", "split", LuaScriptInterface::luaItemSplit);
registerMethod("Item", "remove", LuaScriptInterface::luaItemRemove);
registerMethod("Item", "getUniqueId", LuaScriptInterface::luaItemGetUniqueId);
registerMethod("Item", "getActionId", LuaScriptInterface::luaItemGetActionId);
registerMethod("Item", "setActionId", LuaScriptInterface::luaItemSetActionId);
registerMethod("Item", "getCount", LuaScriptInterface::luaItemGetCount);
registerMethod("Item", "getCharges", LuaScriptInterface::luaItemGetCharges);
registerMethod("Item", "getFluidType", LuaScriptInterface::luaItemGetFluidType);
registerMethod("Item", "getWeight", LuaScriptInterface::luaItemGetWeight);
registerMethod("Item", "getSubType", LuaScriptInterface::luaItemGetSubType);
registerMethod("Item", "getName", LuaScriptInterface::luaItemGetName);
registerMethod("Item", "getPluralName", LuaScriptInterface::luaItemGetPluralName);
registerMethod("Item", "getArticle", LuaScriptInterface::luaItemGetArticle);
registerMethod("Item", "getPosition", LuaScriptInterface::luaItemGetPosition);
registerMethod("Item", "getTile", LuaScriptInterface::luaItemGetTile);
registerMethod("Item", "hasAttribute", LuaScriptInterface::luaItemHasAttribute);
registerMethod("Item", "getAttribute", LuaScriptInterface::luaItemGetAttribute);
registerMethod("Item", "setAttribute", LuaScriptInterface::luaItemSetAttribute);
registerMethod("Item", "removeAttribute", LuaScriptInterface::luaItemRemoveAttribute);
registerMethod("Item", "moveTo", LuaScriptInterface::luaItemMoveTo);
registerMethod("Item", "transform", LuaScriptInterface::luaItemTransform);
registerMethod("Item", "decay", LuaScriptInterface::luaItemDecay);
registerMethod("Item", "getDescription", LuaScriptInterface::luaItemGetDescription);
registerMethod("Item", "hasProperty", LuaScriptInterface::luaItemHasProperty);
// Container
registerClass("Container", "Item", LuaScriptInterface::luaContainerCreate);
registerMetaMethod("Container", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Container", "getSize", LuaScriptInterface::luaContainerGetSize);
registerMethod("Container", "getCapacity", LuaScriptInterface::luaContainerGetCapacity);
registerMethod("Container", "getEmptySlots", LuaScriptInterface::luaContainerGetEmptySlots);
registerMethod("Container", "getItemHoldingCount", LuaScriptInterface::luaContainerGetItemHoldingCount);
registerMethod("Container", "getItemCountById", LuaScriptInterface::luaContainerGetItemCountById);
registerMethod("Container", "getItem", LuaScriptInterface::luaContainerGetItem);
registerMethod("Container", "hasItem", LuaScriptInterface::luaContainerHasItem);
registerMethod("Container", "addItem", LuaScriptInterface::luaContainerAddItem);
registerMethod("Container", "addItemEx", LuaScriptInterface::luaContainerAddItemEx);
// Teleport
registerClass("Teleport", "Item", LuaScriptInterface::luaTeleportCreate);
registerMetaMethod("Teleport", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Teleport", "getDestination", LuaScriptInterface::luaTeleportGetDestination);
registerMethod("Teleport", "setDestination", LuaScriptInterface::luaTeleportSetDestination);
// Creature
registerClass("Creature", "", LuaScriptInterface::luaCreatureCreate);
registerMetaMethod("Creature", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Creature", "registerEvent", LuaScriptInterface::luaCreatureRegisterEvent);
registerMethod("Creature", "unregisterEvent", LuaScriptInterface::luaCreatureUnregisterEvent);
registerMethod("Creature", "isRemoved", LuaScriptInterface::luaCreatureIsRemoved);
registerMethod("Creature", "isCreature", LuaScriptInterface::luaCreatureIsCreature);
registerMethod("Creature", "isInGhostMode", LuaScriptInterface::luaCreatureIsInGhostMode);
registerMethod("Creature", "isHealthHidden", LuaScriptInterface::luaCreatureIsHealthHidden);
registerMethod("Creature", "canSee", LuaScriptInterface::luaCreatureCanSee);
registerMethod("Creature", "canSeeCreature", LuaScriptInterface::luaCreatureCanSeeCreature);
registerMethod("Creature", "getParent", LuaScriptInterface::luaCreatureGetParent);
registerMethod("Creature", "getId", LuaScriptInterface::luaCreatureGetId);
registerMethod("Creature", "getName", LuaScriptInterface::luaCreatureGetName);
registerMethod("Creature", "getTarget", LuaScriptInterface::luaCreatureGetTarget);
registerMethod("Creature", "setTarget", LuaScriptInterface::luaCreatureSetTarget);
registerMethod("Creature", "getFollowCreature", LuaScriptInterface::luaCreatureGetFollowCreature);
registerMethod("Creature", "setFollowCreature", LuaScriptInterface::luaCreatureSetFollowCreature);
registerMethod("Creature", "getMaster", LuaScriptInterface::luaCreatureGetMaster);
registerMethod("Creature", "setMaster", LuaScriptInterface::luaCreatureSetMaster);
registerMethod("Creature", "getLight", LuaScriptInterface::luaCreatureGetLight);
registerMethod("Creature", "setLight", LuaScriptInterface::luaCreatureSetLight);
registerMethod("Creature", "getSpeed", LuaScriptInterface::luaCreatureGetSpeed);
registerMethod("Creature", "getBaseSpeed", LuaScriptInterface::luaCreatureGetBaseSpeed);
registerMethod("Creature", "changeSpeed", LuaScriptInterface::luaCreatureChangeSpeed);
registerMethod("Creature", "setDropLoot", LuaScriptInterface::luaCreatureSetDropLoot);
registerMethod("Creature", "getPosition", LuaScriptInterface::luaCreatureGetPosition);
registerMethod("Creature", "getTile", LuaScriptInterface::luaCreatureGetTile);
registerMethod("Creature", "getDirection", LuaScriptInterface::luaCreatureGetDirection);
registerMethod("Creature", "setDirection", LuaScriptInterface::luaCreatureSetDirection);
registerMethod("Creature", "getHealth", LuaScriptInterface::luaCreatureGetHealth);
registerMethod("Creature", "addHealth", LuaScriptInterface::luaCreatureAddHealth);
registerMethod("Creature", "getMaxHealth", LuaScriptInterface::luaCreatureGetMaxHealth);
registerMethod("Creature", "setMaxHealth", LuaScriptInterface::luaCreatureSetMaxHealth);
registerMethod("Creature", "setHiddenHealth", LuaScriptInterface::luaCreatureSetHiddenHealth);
registerMethod("Creature", "getMana", LuaScriptInterface::luaCreatureGetMana);
registerMethod("Creature", "addMana", LuaScriptInterface::luaCreatureAddMana);
registerMethod("Creature", "getMaxMana", LuaScriptInterface::luaCreatureGetMaxMana);
registerMethod("Creature", "getSkull", LuaScriptInterface::luaCreatureGetSkull);
registerMethod("Creature", "setSkull", LuaScriptInterface::luaCreatureSetSkull);
registerMethod("Creature", "getOutfit", LuaScriptInterface::luaCreatureGetOutfit);
registerMethod("Creature", "setOutfit", LuaScriptInterface::luaCreatureSetOutfit);
registerMethod("Creature", "getCondition", LuaScriptInterface::luaCreatureGetCondition);
registerMethod("Creature", "addCondition", LuaScriptInterface::luaCreatureAddCondition);
registerMethod("Creature", "removeCondition", LuaScriptInterface::luaCreatureRemoveCondition);
registerMethod("Creature", "remove", LuaScriptInterface::luaCreatureRemove);
registerMethod("Creature", "teleportTo", LuaScriptInterface::luaCreatureTeleportTo);
registerMethod("Creature", "say", LuaScriptInterface::luaCreatureSay);
registerMethod("Creature", "getDamageMap", LuaScriptInterface::luaCreatureGetDamageMap);
registerMethod("Creature", "getSummons", LuaScriptInterface::luaCreatureGetSummons);
registerMethod("Creature", "getDescription", LuaScriptInterface::luaCreatureGetDescription);
registerMethod("Creature", "getPathTo", LuaScriptInterface::luaCreatureGetPathTo);
// Player
registerClass("Player", "Creature", LuaScriptInterface::luaPlayerCreate);
registerMetaMethod("Player", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Player", "isPlayer", LuaScriptInterface::luaPlayerIsPlayer);
registerMethod("Player", "getGuid", LuaScriptInterface::luaPlayerGetGuid);
registerMethod("Player", "getIp", LuaScriptInterface::luaPlayerGetIp);
registerMethod("Player", "getAccountId", LuaScriptInterface::luaPlayerGetAccountId);
registerMethod("Player", "getLastLoginSaved", LuaScriptInterface::luaPlayerGetLastLoginSaved);
registerMethod("Player", "getLastLogout", LuaScriptInterface::luaPlayerGetLastLogout);
registerMethod("Player", "getAccountType", LuaScriptInterface::luaPlayerGetAccountType);
registerMethod("Player", "setAccountType", LuaScriptInterface::luaPlayerSetAccountType);
registerMethod("Player", "getCapacity", LuaScriptInterface::luaPlayerGetCapacity);
registerMethod("Player", "setCapacity", LuaScriptInterface::luaPlayerSetCapacity);
registerMethod("Player", "getFreeCapacity", LuaScriptInterface::luaPlayerGetFreeCapacity);
registerMethod("Player", "getDepotChest", LuaScriptInterface::luaPlayerGetDepotChest);
registerMethod("Player", "getInbox", LuaScriptInterface::luaPlayerGetInbox);
registerMethod("Player", "getSkullTime", LuaScriptInterface::luaPlayerGetSkullTime);
registerMethod("Player", "setSkullTime", LuaScriptInterface::luaPlayerSetSkullTime);
registerMethod("Player", "getDeathPenalty", LuaScriptInterface::luaPlayerGetDeathPenalty);
registerMethod("Player", "getExperience", LuaScriptInterface::luaPlayerGetExperience);
registerMethod("Player", "addExperience", LuaScriptInterface::luaPlayerAddExperience);
registerMethod("Player", "removeExperience", LuaScriptInterface::luaPlayerRemoveExperience);
registerMethod("Player", "getLevel", LuaScriptInterface::luaPlayerGetLevel);
registerMethod("Player", "getMagicLevel", LuaScriptInterface::luaPlayerGetMagicLevel);
registerMethod("Player", "getBaseMagicLevel", LuaScriptInterface::luaPlayerGetBaseMagicLevel);
registerMethod("Player", "setMaxMana", LuaScriptInterface::luaPlayerSetMaxMana);
registerMethod("Player", "getManaSpent", LuaScriptInterface::luaPlayerGetManaSpent);
registerMethod("Player", "addManaSpent", LuaScriptInterface::luaPlayerAddManaSpent);
registerMethod("Player", "getSkillLevel", LuaScriptInterface::luaPlayerGetSkillLevel);
registerMethod("Player", "getEffectiveSkillLevel", LuaScriptInterface::luaPlayerGetEffectiveSkillLevel);
registerMethod("Player", "getSkillPercent", LuaScriptInterface::luaPlayerGetSkillPercent);
registerMethod("Player", "getSkillTries", LuaScriptInterface::luaPlayerGetSkillTries);
registerMethod("Player", "addSkillTries", LuaScriptInterface::luaPlayerAddSkillTries);
registerMethod("Player", "getItemCount", LuaScriptInterface::luaPlayerGetItemCount);
registerMethod("Player", "getItemById", LuaScriptInterface::luaPlayerGetItemById);
registerMethod("Player", "getVocation", LuaScriptInterface::luaPlayerGetVocation);
registerMethod("Player", "setVocation", LuaScriptInterface::luaPlayerSetVocation);
registerMethod("Player", "getSex", LuaScriptInterface::luaPlayerGetSex);
registerMethod("Player", "setSex", LuaScriptInterface::luaPlayerSetSex);
registerMethod("Player", "getTown", LuaScriptInterface::luaPlayerGetTown);
registerMethod("Player", "setTown", LuaScriptInterface::luaPlayerSetTown);
registerMethod("Player", "getGuild", LuaScriptInterface::luaPlayerGetGuild);
registerMethod("Player", "setGuild", LuaScriptInterface::luaPlayerSetGuild);
registerMethod("Player", "getGuildLevel", LuaScriptInterface::luaPlayerGetGuildLevel);
registerMethod("Player", "setGuildLevel", LuaScriptInterface::luaPlayerSetGuildLevel);
registerMethod("Player", "getGuildNick", LuaScriptInterface::luaPlayerGetGuildNick);
registerMethod("Player", "setGuildNick", LuaScriptInterface::luaPlayerSetGuildNick);
registerMethod("Player", "getGroup", LuaScriptInterface::luaPlayerGetGroup);
registerMethod("Player", "setGroup", LuaScriptInterface::luaPlayerSetGroup);
registerMethod("Player", "getStamina", LuaScriptInterface::luaPlayerGetStamina);
registerMethod("Player", "setStamina", LuaScriptInterface::luaPlayerSetStamina);
registerMethod("Player", "getSoul", LuaScriptInterface::luaPlayerGetSoul);
registerMethod("Player", "addSoul", LuaScriptInterface::luaPlayerAddSoul);
registerMethod("Player", "getMaxSoul", LuaScriptInterface::luaPlayerGetMaxSoul);
registerMethod("Player", "getBankBalance", LuaScriptInterface::luaPlayerGetBankBalance);
registerMethod("Player", "setBankBalance", LuaScriptInterface::luaPlayerSetBankBalance);
registerMethod("Player", "getStorageValue", LuaScriptInterface::luaPlayerGetStorageValue);
registerMethod("Player", "setStorageValue", LuaScriptInterface::luaPlayerSetStorageValue);
registerMethod("Player", "addItem", LuaScriptInterface::luaPlayerAddItem);
registerMethod("Player", "addItemEx", LuaScriptInterface::luaPlayerAddItemEx);
registerMethod("Player", "removeItem", LuaScriptInterface::luaPlayerRemoveItem);
registerMethod("Player", "getMoney", LuaScriptInterface::luaPlayerGetMoney);
registerMethod("Player", "addMoney", LuaScriptInterface::luaPlayerAddMoney);
registerMethod("Player", "removeMoney", LuaScriptInterface::luaPlayerRemoveMoney);
registerMethod("Player", "showTextDialog", LuaScriptInterface::luaPlayerShowTextDialog);
registerMethod("Player", "sendTextMessage", LuaScriptInterface::luaPlayerSendTextMessage);
registerMethod("Player", "sendChannelMessage", LuaScriptInterface::luaPlayerSendChannelMessage);
registerMethod("Player", "sendPrivateMessage", LuaScriptInterface::luaPlayerSendPrivateMessage);
registerMethod("Player", "channelSay", LuaScriptInterface::luaPlayerChannelSay);
registerMethod("Player", "openChannel", LuaScriptInterface::luaPlayerOpenChannel);
registerMethod("Player", "getSlotItem", LuaScriptInterface::luaPlayerGetSlotItem);
registerMethod("Player", "getParty", LuaScriptInterface::luaPlayerGetParty);
registerMethod("Player", "addOutfit", LuaScriptInterface::luaPlayerAddOutfit);
registerMethod("Player", "addOutfitAddon", LuaScriptInterface::luaPlayerAddOutfitAddon);
registerMethod("Player", "removeOutfit", LuaScriptInterface::luaPlayerRemoveOutfit);
registerMethod("Player", "removeOutfitAddon", LuaScriptInterface::luaPlayerRemoveOutfitAddon);
registerMethod("Player", "hasOutfit", LuaScriptInterface::luaPlayerHasOutfit);
registerMethod("Player", "sendOutfitWindow", LuaScriptInterface::luaPlayerSendOutfitWindow);
registerMethod("Player", "addMount", LuaScriptInterface::luaPlayerAddMount);
registerMethod("Player", "removeMount", LuaScriptInterface::luaPlayerRemoveMount);
registerMethod("Player", "hasMount", LuaScriptInterface::luaPlayerHasMount);
registerMethod("Player", "getPremiumDays", LuaScriptInterface::luaPlayerGetPremiumDays);
registerMethod("Player", "addPremiumDays", LuaScriptInterface::luaPlayerAddPremiumDays);
registerMethod("Player", "removePremiumDays", LuaScriptInterface::luaPlayerRemovePremiumDays);
registerMethod("Player", "hasBlessing", LuaScriptInterface::luaPlayerHasBlessing);
registerMethod("Player", "addBlessing", LuaScriptInterface::luaPlayerAddBlessing);
registerMethod("Player", "removeBlessing", LuaScriptInterface::luaPlayerRemoveBlessing);
registerMethod("Player", "canLearnSpell", LuaScriptInterface::luaPlayerCanLearnSpell);
registerMethod("Player", "learnSpell", LuaScriptInterface::luaPlayerLearnSpell);
registerMethod("Player", "forgetSpell", LuaScriptInterface::luaPlayerForgetSpell);
registerMethod("Player", "hasLearnedSpell", LuaScriptInterface::luaPlayerHasLearnedSpell);
registerMethod("Player", "sendTutorial", LuaScriptInterface::luaPlayerSendTutorial);
registerMethod("Player", "addMapMark", LuaScriptInterface::luaPlayerAddMapMark);
registerMethod("Player", "save", LuaScriptInterface::luaPlayerSave);
registerMethod("Player", "popupFYI", LuaScriptInterface::luaPlayerPopupFYI);
registerMethod("Player", "isPzLocked", LuaScriptInterface::luaPlayerIsPzLocked);
registerMethod("Player", "getClient", LuaScriptInterface::luaPlayerGetClient);
registerMethod("Player", "getHouse", LuaScriptInterface::luaPlayerGetHouse);
registerMethod("Player", "setGhostMode", LuaScriptInterface::luaPlayerSetGhostMode);
registerMethod("Player", "getContainerId", LuaScriptInterface::luaPlayerGetContainerId);
registerMethod("Player", "getContainerById", LuaScriptInterface::luaPlayerGetContainerById);
registerMethod("Player", "getContainerIndex", LuaScriptInterface::luaPlayerGetContainerIndex);
// Monster
registerClass("Monster", "Creature", LuaScriptInterface::luaMonsterCreate);
registerMetaMethod("Monster", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Monster", "isMonster", LuaScriptInterface::luaMonsterIsMonster);
registerMethod("Monster", "getType", LuaScriptInterface::luaMonsterGetType);
registerMethod("Monster", "getSpawnPosition", LuaScriptInterface::luaMonsterGetSpawnPosition);
registerMethod("Monster", "isInSpawnRange", LuaScriptInterface::luaMonsterIsInSpawnRange);
registerMethod("Monster", "isIdle", LuaScriptInterface::luaMonsterIsIdle);
registerMethod("Monster", "setIdle", LuaScriptInterface::luaMonsterSetIdle);
registerMethod("Monster", "isTarget", LuaScriptInterface::luaMonsterIsTarget);
registerMethod("Monster", "isOpponent", LuaScriptInterface::luaMonsterIsOpponent);
registerMethod("Monster", "isFriend", LuaScriptInterface::luaMonsterIsFriend);
registerMethod("Monster", "addFriend", LuaScriptInterface::luaMonsterAddFriend);
registerMethod("Monster", "removeFriend", LuaScriptInterface::luaMonsterRemoveFriend);
registerMethod("Monster", "getFriendList", LuaScriptInterface::luaMonsterGetFriendList);
registerMethod("Monster", "getFriendCount", LuaScriptInterface::luaMonsterGetFriendCount);
registerMethod("Monster", "addTarget", LuaScriptInterface::luaMonsterAddTarget);
registerMethod("Monster", "removeTarget", LuaScriptInterface::luaMonsterRemoveTarget);
registerMethod("Monster", "getTargetList", LuaScriptInterface::luaMonsterGetTargetList);
registerMethod("Monster", "getTargetCount", LuaScriptInterface::luaMonsterGetTargetCount);
registerMethod("Monster", "selectTarget", LuaScriptInterface::luaMonsterSelectTarget);
registerMethod("Monster", "searchTarget", LuaScriptInterface::luaMonsterSearchTarget);
// Npc
registerClass("Npc", "Creature", LuaScriptInterface::luaNpcCreate);
registerMetaMethod("Npc", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Npc", "isNpc", LuaScriptInterface::luaNpcIsNpc);
registerMethod("Npc", "setMasterPos", LuaScriptInterface::luaNpcSetMasterPos);
registerMethod("Npc", "getSpeechBubble", LuaScriptInterface::luaNpcGetSpeechBubble);
registerMethod("Npc", "setSpeechBubble", LuaScriptInterface::luaNpcSetSpeechBubble);
// Guild
registerClass("Guild", "", LuaScriptInterface::luaGuildCreate);
registerMetaMethod("Guild", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Guild", "getId", LuaScriptInterface::luaGuildGetId);
registerMethod("Guild", "getName", LuaScriptInterface::luaGuildGetName);
registerMethod("Guild", "getMembersOnline", LuaScriptInterface::luaGuildGetMembersOnline);
registerMethod("Guild", "addMember", LuaScriptInterface::luaGuildAddMember);
registerMethod("Guild", "removeMember", LuaScriptInterface::luaGuildRemoveMember);
registerMethod("Guild", "addRank", LuaScriptInterface::luaGuildAddRank);
registerMethod("Guild", "getRankById", LuaScriptInterface::luaGuildGetRankById);
registerMethod("Guild", "getRankByLevel", LuaScriptInterface::luaGuildGetRankByLevel);
registerMethod("Guild", "getMotd", LuaScriptInterface::luaGuildGetMotd);
registerMethod("Guild", "setMotd", LuaScriptInterface::luaGuildSetMotd);
// Group
registerClass("Group", "", LuaScriptInterface::luaGroupCreate);
registerMetaMethod("Group", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Group", "getId", LuaScriptInterface::luaGroupGetId);
registerMethod("Group", "getName", LuaScriptInterface::luaGroupGetName);
registerMethod("Group", "getFlags", LuaScriptInterface::luaGroupGetFlags);
registerMethod("Group", "getAccess", LuaScriptInterface::luaGroupGetAccess);
registerMethod("Group", "getMaxDepotItems", LuaScriptInterface::luaGroupGetMaxDepotItems);
registerMethod("Group", "getMaxVipEntries", LuaScriptInterface::luaGroupGetMaxVipEntries);
// Vocation
registerClass("Vocation", "", LuaScriptInterface::luaVocationCreate);
registerMetaMethod("Vocation", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Vocation", "getId", LuaScriptInterface::luaVocationGetId);
registerMethod("Vocation", "getClientId", LuaScriptInterface::luaVocationGetClientId);
registerMethod("Vocation", "getName", LuaScriptInterface::luaVocationGetName);
registerMethod("Vocation", "getDescription", LuaScriptInterface::luaVocationGetDescription);
registerMethod("Vocation", "getRequiredSkillTries", LuaScriptInterface::luaVocationGetRequiredSkillTries);
registerMethod("Vocation", "getRequiredManaSpent", LuaScriptInterface::luaVocationGetRequiredManaSpent);
registerMethod("Vocation", "getCapacityGain", LuaScriptInterface::luaVocationGetCapacityGain);
registerMethod("Vocation", "getHealthGain", LuaScriptInterface::luaVocationGetHealthGain);
registerMethod("Vocation", "getHealthGainTicks", LuaScriptInterface::luaVocationGetHealthGainTicks);
registerMethod("Vocation", "getHealthGainAmount", LuaScriptInterface::luaVocationGetHealthGainAmount);
registerMethod("Vocation", "getManaGain", LuaScriptInterface::luaVocationGetManaGain);
registerMethod("Vocation", "getManaGainTicks", LuaScriptInterface::luaVocationGetManaGainTicks);
registerMethod("Vocation", "getManaGainAmount", LuaScriptInterface::luaVocationGetManaGainAmount);
registerMethod("Vocation", "getMaxSoul", LuaScriptInterface::luaVocationGetMaxSoul);
registerMethod("Vocation", "getSoulGainTicks", LuaScriptInterface::luaVocationGetSoulGainTicks);
registerMethod("Vocation", "getAttackSpeed", LuaScriptInterface::luaVocationGetAttackSpeed);
registerMethod("Vocation", "getBaseSpeed", LuaScriptInterface::luaVocationGetBaseSpeed);
registerMethod("Vocation", "getDemotion", LuaScriptInterface::luaVocationGetDemotion);
registerMethod("Vocation", "getPromotion", LuaScriptInterface::luaVocationGetPromotion);
// Town
registerClass("Town", "", LuaScriptInterface::luaTownCreate);
registerMetaMethod("Town", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Town", "getId", LuaScriptInterface::luaTownGetId);
registerMethod("Town", "getName", LuaScriptInterface::luaTownGetName);
registerMethod("Town", "getTemplePosition", LuaScriptInterface::luaTownGetTemplePosition);
// House
registerClass("House", "", LuaScriptInterface::luaHouseCreate);
registerMetaMethod("House", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("House", "getId", LuaScriptInterface::luaHouseGetId);
registerMethod("House", "getName", LuaScriptInterface::luaHouseGetName);
registerMethod("House", "getTown", LuaScriptInterface::luaHouseGetTown);
registerMethod("House", "getExitPosition", LuaScriptInterface::luaHouseGetExitPosition);
registerMethod("House", "getRent", LuaScriptInterface::luaHouseGetRent);
registerMethod("House", "getOwnerGuid", LuaScriptInterface::luaHouseGetOwnerGuid);
registerMethod("House", "setOwnerGuid", LuaScriptInterface::luaHouseSetOwnerGuid);
registerMethod("House", "getBeds", LuaScriptInterface::luaHouseGetBeds);
registerMethod("House", "getBedCount", LuaScriptInterface::luaHouseGetBedCount);
registerMethod("House", "getDoors", LuaScriptInterface::luaHouseGetDoors);
registerMethod("House", "getDoorCount", LuaScriptInterface::luaHouseGetDoorCount);
registerMethod("House", "getTiles", LuaScriptInterface::luaHouseGetTiles);
registerMethod("House", "getTileCount", LuaScriptInterface::luaHouseGetTileCount);
registerMethod("House", "getAccessList", LuaScriptInterface::luaHouseGetAccessList);
registerMethod("House", "setAccessList", LuaScriptInterface::luaHouseSetAccessList);
// ItemType
registerClass("ItemType", "", LuaScriptInterface::luaItemTypeCreate);
registerMetaMethod("ItemType", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("ItemType", "isCorpse", LuaScriptInterface::luaItemTypeIsCorpse);
registerMethod("ItemType", "isDoor", LuaScriptInterface::luaItemTypeIsDoor);
registerMethod("ItemType", "isContainer", LuaScriptInterface::luaItemTypeIsContainer);
registerMethod("ItemType", "isFluidContainer", LuaScriptInterface::luaItemTypeIsFluidContainer);
registerMethod("ItemType", "isMovable", LuaScriptInterface::luaItemTypeIsMovable);
registerMethod("ItemType", "isRune", LuaScriptInterface::luaItemTypeIsRune);
registerMethod("ItemType", "isStackable", LuaScriptInterface::luaItemTypeIsStackable);
registerMethod("ItemType", "isReadable", LuaScriptInterface::luaItemTypeIsReadable);
registerMethod("ItemType", "isWritable", LuaScriptInterface::luaItemTypeIsWritable);
registerMethod("ItemType", "getType", LuaScriptInterface::luaItemTypeGetType);
registerMethod("ItemType", "getId", LuaScriptInterface::luaItemTypeGetId);
registerMethod("ItemType", "getClientId", LuaScriptInterface::luaItemTypeGetClientId);
registerMethod("ItemType", "getName", LuaScriptInterface::luaItemTypeGetName);
registerMethod("ItemType", "getPluralName", LuaScriptInterface::luaItemTypeGetPluralName);
registerMethod("ItemType", "getArticle", LuaScriptInterface::luaItemTypeGetArticle);
registerMethod("ItemType", "getDescription", LuaScriptInterface::luaItemTypeGetDescription);
registerMethod("ItemType", "getSlotPosition", LuaScriptInterface::luaItemTypeGetSlotPosition);
registerMethod("ItemType", "getCharges", LuaScriptInterface::luaItemTypeGetCharges);
registerMethod("ItemType", "getFluidSource", LuaScriptInterface::luaItemTypeGetFluidSource);
registerMethod("ItemType", "getCapacity", LuaScriptInterface::luaItemTypeGetCapacity);
registerMethod("ItemType", "getWeight", LuaScriptInterface::luaItemTypeGetWeight);
registerMethod("ItemType", "getHitChance", LuaScriptInterface::luaItemTypeGetHitChance);
registerMethod("ItemType", "getShootRange", LuaScriptInterface::luaItemTypeGetShootRange);
registerMethod("ItemType", "getAttack", LuaScriptInterface::luaItemTypeGetAttack);
registerMethod("ItemType", "getDefense", LuaScriptInterface::luaItemTypeGetDefense);
registerMethod("ItemType", "getExtraDefense", LuaScriptInterface::luaItemTypeGetExtraDefense);
registerMethod("ItemType", "getArmor", LuaScriptInterface::luaItemTypeGetArmor);
registerMethod("ItemType", "getWeaponType", LuaScriptInterface::luaItemTypeGetWeaponType);
registerMethod("ItemType", "getElementType", LuaScriptInterface::luaItemTypeGetElementType);
registerMethod("ItemType", "getElementDamage", LuaScriptInterface::luaItemTypeGetElementDamage);
registerMethod("ItemType", "getTransformEquipId", LuaScriptInterface::luaItemTypeGetTransformEquipId);
registerMethod("ItemType", "getTransformDeEquipId", LuaScriptInterface::luaItemTypeGetTransformDeEquipId);
registerMethod("ItemType", "getDestroyId", LuaScriptInterface::luaItemTypeGetDestroyId);
registerMethod("ItemType", "getDecayId", LuaScriptInterface::luaItemTypeGetDecayId);
registerMethod("ItemType", "getRequiredLevel", LuaScriptInterface::luaItemTypeGetRequiredLevel);
registerMethod("ItemType", "hasSubType", LuaScriptInterface::luaItemTypeHasSubType);
// Combat
registerClass("Combat", "", LuaScriptInterface::luaCombatCreate);
registerMetaMethod("Combat", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Combat", "setParameter", LuaScriptInterface::luaCombatSetParameter);
registerMethod("Combat", "setFormula", LuaScriptInterface::luaCombatSetFormula);
registerMethod("Combat", "setArea", LuaScriptInterface::luaCombatSetArea);
registerMethod("Combat", "setCondition", LuaScriptInterface::luaCombatSetCondition);
registerMethod("Combat", "setCallback", LuaScriptInterface::luaCombatSetCallback);
registerMethod("Combat", "setOrigin", LuaScriptInterface::luaCombatSetOrigin);
registerMethod("Combat", "execute", LuaScriptInterface::luaCombatExecute);
// Condition
registerClass("Condition", "", LuaScriptInterface::luaConditionCreate);
registerMetaMethod("Condition", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMetaMethod("Condition", "__gc", LuaScriptInterface::luaConditionDelete);
registerMethod("Condition", "delete", LuaScriptInterface::luaConditionDelete);
registerMethod("Condition", "getId", LuaScriptInterface::luaConditionGetId);
registerMethod("Condition", "getSubId", LuaScriptInterface::luaConditionGetSubId);
registerMethod("Condition", "getType", LuaScriptInterface::luaConditionGetType);
registerMethod("Condition", "getIcons", LuaScriptInterface::luaConditionGetIcons);
registerMethod("Condition", "getEndTime", LuaScriptInterface::luaConditionGetEndTime);
registerMethod("Condition", "clone", LuaScriptInterface::luaConditionClone);
registerMethod("Condition", "getTicks", LuaScriptInterface::luaConditionGetTicks);
registerMethod("Condition", "setTicks", LuaScriptInterface::luaConditionSetTicks);
registerMethod("Condition", "setParameter", LuaScriptInterface::luaConditionSetParameter);
registerMethod("Condition", "setFormula", LuaScriptInterface::luaConditionSetFormula);
registerMethod("Condition", "setOutfit", LuaScriptInterface::luaConditionSetOutfit);
registerMethod("Condition", "addDamage", LuaScriptInterface::luaConditionAddDamage);
// MonsterType
registerClass("MonsterType", "", LuaScriptInterface::luaMonsterTypeCreate);
registerMetaMethod("MonsterType", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("MonsterType", "isAttackable", LuaScriptInterface::luaMonsterTypeIsAttackable);
registerMethod("MonsterType", "isConvinceable", LuaScriptInterface::luaMonsterTypeIsConvinceable);
registerMethod("MonsterType", "isSummonable", LuaScriptInterface::luaMonsterTypeIsSummonable);
registerMethod("MonsterType", "isIllusionable", LuaScriptInterface::luaMonsterTypeIsIllusionable);
registerMethod("MonsterType", "isHostile", LuaScriptInterface::luaMonsterTypeIsHostile);
registerMethod("MonsterType", "isPushable", LuaScriptInterface::luaMonsterTypeIsPushable);
registerMethod("MonsterType", "isHealthShown", LuaScriptInterface::luaMonsterTypeIsHealthShown);
registerMethod("MonsterType", "canPushItems", LuaScriptInterface::luaMonsterTypeCanPushItems);
registerMethod("MonsterType", "canPushCreatures", LuaScriptInterface::luaMonsterTypeCanPushCreatures);
registerMethod("MonsterType", "getName", LuaScriptInterface::luaMonsterTypeGetName);
registerMethod("MonsterType", "getNameDescription", LuaScriptInterface::luaMonsterTypeGetNameDescription);
registerMethod("MonsterType", "getHealth", LuaScriptInterface::luaMonsterTypeGetHealth);
registerMethod("MonsterType", "getMaxHealth", LuaScriptInterface::luaMonsterTypeGetMaxHealth);
registerMethod("MonsterType", "getRunHealth", LuaScriptInterface::luaMonsterTypeGetRunHealth);
registerMethod("MonsterType", "getExperience", LuaScriptInterface::luaMonsterTypeGetExperience);
registerMethod("MonsterType", "getCombatImmunities", LuaScriptInterface::luaMonsterTypeGetCombatImmunities);
registerMethod("MonsterType", "getConditionImmunities", LuaScriptInterface::luaMonsterTypeGetConditionImmunities);
registerMethod("MonsterType", "getAttackList", LuaScriptInterface::luaMonsterTypeGetAttackList);
registerMethod("MonsterType", "getDefenseList", LuaScriptInterface::luaMonsterTypeGetDefenseList);
registerMethod("MonsterType", "getElementList", LuaScriptInterface::luaMonsterTypeGetElementList);
registerMethod("MonsterType", "getVoices", LuaScriptInterface::luaMonsterTypeGetVoices);
registerMethod("MonsterType", "getLoot", LuaScriptInterface::luaMonsterTypeGetLoot);
registerMethod("MonsterType", "getCreatureEvents", LuaScriptInterface::luaMonsterTypeGetCreatureEvents);
registerMethod("MonsterType", "getSummonList", LuaScriptInterface::luaMonsterTypeGetSummonList);
registerMethod("MonsterType", "getMaxSummons", LuaScriptInterface::luaMonsterTypeGetMaxSummons);
registerMethod("MonsterType", "getArmor", LuaScriptInterface::luaMonsterTypeGetArmor);
registerMethod("MonsterType", "getDefense", LuaScriptInterface::luaMonsterTypeGetDefense);
registerMethod("MonsterType", "getOutfit", LuaScriptInterface::luaMonsterTypeGetOutfit);
registerMethod("MonsterType", "getRace", LuaScriptInterface::luaMonsterTypeGetRace);
registerMethod("MonsterType", "getCorpseId", LuaScriptInterface::luaMonsterTypeGetCorpseId);
registerMethod("MonsterType", "getManaCost", LuaScriptInterface::luaMonsterTypeGetManaCost);
registerMethod("MonsterType", "getBaseSpeed", LuaScriptInterface::luaMonsterTypeGetBaseSpeed);
registerMethod("MonsterType", "getLight", LuaScriptInterface::luaMonsterTypeGetLight);
registerMethod("MonsterType", "getStaticAttackChance", LuaScriptInterface::luaMonsterTypeGetStaticAttackChance);
registerMethod("MonsterType", "getTargetDistance", LuaScriptInterface::luaMonsterTypeGetTargetDistance);
registerMethod("MonsterType", "getYellChance", LuaScriptInterface::luaMonsterTypeGetYellChance);
registerMethod("MonsterType", "getYellSpeedTicks", LuaScriptInterface::luaMonsterTypeGetYellSpeedTicks);
registerMethod("MonsterType", "getChangeTargetChance", LuaScriptInterface::luaMonsterTypeGetChangeTargetChance);
registerMethod("MonsterType", "getChangeTargetSpeed", LuaScriptInterface::luaMonsterTypeGetChangeTargetSpeed);
// Party
registerClass("Party", "", nullptr);
registerMetaMethod("Party", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Party", "disband", LuaScriptInterface::luaPartyDisband);
registerMethod("Party", "getLeader", LuaScriptInterface::luaPartyGetLeader);
registerMethod("Party", "setLeader", LuaScriptInterface::luaPartySetLeader);
registerMethod("Party", "getMembers", LuaScriptInterface::luaPartyGetMembers);
registerMethod("Party", "getMemberCount", LuaScriptInterface::luaPartyGetMemberCount);
registerMethod("Party", "getInvitees", LuaScriptInterface::luaPartyGetInvitees);
registerMethod("Party", "getInviteeCount", LuaScriptInterface::luaPartyGetInviteeCount);
registerMethod("Party", "addInvite", LuaScriptInterface::luaPartyAddInvite);
registerMethod("Party", "removeInvite", LuaScriptInterface::luaPartyRemoveInvite);
registerMethod("Party", "addMember", LuaScriptInterface::luaPartyAddMember);
registerMethod("Party", "removeMember", LuaScriptInterface::luaPartyRemoveMember);
registerMethod("Party", "isSharedExperienceActive", LuaScriptInterface::luaPartyIsSharedExperienceActive);
registerMethod("Party", "isSharedExperienceEnabled", LuaScriptInterface::luaPartyIsSharedExperienceEnabled);
registerMethod("Party", "shareExperience", LuaScriptInterface::luaPartyShareExperience);
registerMethod("Party", "setSharedExperience", LuaScriptInterface::luaPartySetSharedExperience);
}
#undef registerEnum
#undef registerEnumIn
void LuaScriptInterface::registerClass(const std::string& className, const std::string& baseClass, lua_CFunction newFunction/* = nullptr*/)
{
// className = {}
lua_newtable(m_luaState);
lua_pushvalue(m_luaState, -1);
lua_setglobal(m_luaState, className.c_str());
int methods = lua_gettop(m_luaState);
// methodsTable = {}
lua_newtable(m_luaState);
int methodsTable = lua_gettop(m_luaState);
if (newFunction) {
// className.__call = newFunction
lua_pushcfunction(m_luaState, newFunction);
lua_setfield(m_luaState, methodsTable, "__call");
}
uint32_t parents = 0;
if (!baseClass.empty()) {
lua_getglobal(m_luaState, baseClass.c_str());
lua_rawgeti(m_luaState, -1, 'p');
parents = getNumber<uint32_t>(m_luaState, -1) + 1;
lua_pop(m_luaState, 1);
lua_setfield(m_luaState, methodsTable, "__index");
}
// setmetatable(className, methodsTable)
lua_setmetatable(m_luaState, methods);
// className.metatable = {}
luaL_newmetatable(m_luaState, className.c_str());
int metatable = lua_gettop(m_luaState);
// className.metatable.__metatable = className
lua_pushvalue(m_luaState, methods);
lua_setfield(m_luaState, metatable, "__metatable");
// className.metatable.__index = className
lua_pushvalue(m_luaState, methods);
lua_setfield(m_luaState, metatable, "__index");
// className.metatable['h'] = hash
lua_pushnumber(m_luaState, std::hash<std::string>()(className));
lua_rawseti(m_luaState, metatable, 'h');
// className.metatable['p'] = parents
lua_pushnumber(m_luaState, parents);
lua_rawseti(m_luaState, metatable, 'p');
// className.metatable['t'] = type
if (className == "Item") {
lua_pushnumber(m_luaState, LuaData_Item);
} else if (className == "Container") {
lua_pushnumber(m_luaState, LuaData_Container);
} else if (className == "Teleport") {
lua_pushnumber(m_luaState, LuaData_Teleport);
} else if (className == "Player") {
lua_pushnumber(m_luaState, LuaData_Player);
} else if (className == "Monster") {
lua_pushnumber(m_luaState, LuaData_Monster);
} else if (className == "Npc") {
lua_pushnumber(m_luaState, LuaData_Npc);
} else if (className == "Tile") {
lua_pushnumber(m_luaState, LuaData_Tile);
} else {
lua_pushnumber(m_luaState, LuaData_Unknown);
}
lua_rawseti(m_luaState, metatable, 't');
// pop className, className.metatable
lua_pop(m_luaState, 2);
}
void LuaScriptInterface::registerTable(const std::string& tableName)
{
// _G[tableName] = {}
lua_newtable(m_luaState);
lua_setglobal(m_luaState, tableName.c_str());
}
void LuaScriptInterface::registerMethod(const std::string& globalName, const std::string& methodName, lua_CFunction func)
{
// globalName.methodName = func
lua_getglobal(m_luaState, globalName.c_str());
lua_pushcfunction(m_luaState, func);
lua_setfield(m_luaState, -2, methodName.c_str());
// pop globalName
lua_pop(m_luaState, 1);
}
void LuaScriptInterface::registerMetaMethod(const std::string& className, const std::string& methodName, lua_CFunction func)
{
// className.metatable.methodName = func
luaL_getmetatable(m_luaState, className.c_str());
lua_pushcfunction(m_luaState, func);
lua_setfield(m_luaState, -2, methodName.c_str());
// pop className.metatable
lua_pop(m_luaState, 1);
}
void LuaScriptInterface::registerGlobalMethod(const std::string& functionName, lua_CFunction func)
{
// _G[functionName] = func
lua_pushcfunction(m_luaState, func);
lua_setglobal(m_luaState, functionName.c_str());
}
void LuaScriptInterface::registerVariable(const std::string& tableName, const std::string& name, lua_Number value)
{
// tableName.name = value
lua_getglobal(m_luaState, tableName.c_str());
setField(m_luaState, name.c_str(), value);
// pop tableName
lua_pop(m_luaState, 1);
}
void LuaScriptInterface::registerGlobalVariable(const std::string& name, lua_Number value)
{
// _G[name] = value
lua_pushnumber(m_luaState, value);
lua_setglobal(m_luaState, name.c_str());
}
void LuaScriptInterface::registerGlobalBoolean(const std::string& name, bool value)
{
// _G[name] = value
pushBoolean(m_luaState, value);
lua_setglobal(m_luaState, name.c_str());
}
int LuaScriptInterface::luaGetPlayerFlagValue(lua_State* L)
{
//getPlayerFlagValue(cid, flag)
Player* player = getPlayer(L, 1);
if (player) {
PlayerFlags flag = getNumber<PlayerFlags>(L, 2);
pushBoolean(L, player->hasFlag(flag));
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaGetPlayerInstantSpellCount(lua_State* L)
{
//getPlayerInstantSpellCount(cid)
Player* player = getPlayer(L, 1);
if (player) {
lua_pushnumber(L, g_spells->getInstantSpellCount(player));
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaGetPlayerInstantSpellInfo(lua_State* L)
{
//getPlayerInstantSpellInfo(cid, index)
Player* player = getPlayer(L, 1);
if (!player) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t index = getNumber<uint32_t>(L, 2);
InstantSpell* spell = g_spells->getInstantSpellByIndex(player, index);
if (!spell) {
reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
lua_createtable(L, 0, 6);
setField(L, "name", spell->getName());
setField(L, "words", spell->getWords());
setField(L, "level", spell->getLevel());
setField(L, "mlevel", spell->getMagicLevel());
setField(L, "mana", spell->getManaCost(player));
setField(L, "manapercent", spell->getManaPercent());
return 1;
}
int LuaScriptInterface::luaDoPlayerAddItem(lua_State* L)
{
//doPlayerAddItem(cid, itemid, <optional: default: 1> count/subtype, <optional: default: 1> canDropOnMap)
//doPlayerAddItem(cid, itemid, <optional: default: 1> count, <optional: default: 1> canDropOnMap, <optional: default: 1>subtype)
Player* player = getPlayer(L, 1);
if (!player) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint16_t itemId = getNumber<uint16_t>(L, 2);
int32_t count = getNumber<int32_t>(L, 3, 1);
bool canDropOnMap = getBoolean(L, 4, true);
uint16_t subType = getNumber<uint16_t>(L, 5, 1);
const ItemType& it = Item::items[itemId];
int32_t itemCount;
auto parameters = lua_gettop(L);
if (parameters > 4) {
//subtype already supplied, count then is the amount
itemCount = std::max<int32_t>(1, count);
} else if (it.hasSubType()) {
if (it.stackable) {
itemCount = static_cast<int32_t>(std::ceil(static_cast<float>(count) / 100));
} else {
itemCount = 1;
}
subType = count;
} else {
itemCount = std::max<int32_t>(1, count);
}
while (itemCount > 0) {
uint16_t stackCount = subType;
if (it.stackable && stackCount > 100) {
stackCount = 100;
}
Item* newItem = Item::CreateItem(itemId, stackCount);
if (!newItem) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (it.stackable) {
subType -= stackCount;
}
ReturnValue ret = g_game.internalPlayerAddItem(player, newItem, canDropOnMap);
if (ret != RETURNVALUE_NOERROR) {
delete newItem;
pushBoolean(L, false);
return 1;
}
if (--itemCount == 0) {
if (newItem->getParent()) {
uint32_t uid = getScriptEnv()->addThing(newItem);
lua_pushnumber(L, uid);
return 1;
} else {
//stackable item stacked with existing object, newItem will be released
pushBoolean(L, false);
return 1;
}
}
}
pushBoolean(L, false);
return 1;
}
int LuaScriptInterface::luaDoTileAddItemEx(lua_State* L)
{
//doTileAddItemEx(pos, uid)
const Position& pos = getPosition(L, 1);
Tile* tile = g_game.map.getTile(pos);
if (!tile) {
std::ostringstream ss;
ss << pos << ' ' << getErrorDesc(LUA_ERROR_TILE_NOT_FOUND);
reportErrorFunc(ss.str());
pushBoolean(L, false);
return 1;
}
uint32_t uid = getNumber<uint32_t>(L, 2);
Item* item = getScriptEnv()->getItemByUID(uid);
if (!item) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (item->getParent() != VirtualCylinder::virtualCylinder) {
reportErrorFunc("Item already has a parent");
pushBoolean(L, false);
return 1;
}
lua_pushnumber(L, g_game.internalAddItem(tile, item));
return 1;
}
int LuaScriptInterface::luaDoCreateItem(lua_State* L)
{
//doCreateItem(itemid, <optional> type/count, pos)
//Returns uid of the created item, only works on tiles.
const Position& pos = getPosition(L, 3);
Tile* tile = g_game.map.getTile(pos);
if (!tile) {
std::ostringstream ss;
ss << pos << ' ' << getErrorDesc(LUA_ERROR_TILE_NOT_FOUND);
reportErrorFunc(ss.str());
pushBoolean(L, false);
return 1;
}
ScriptEnvironment* env = getScriptEnv();
int32_t itemCount = 1;
int32_t subType = 1;
uint16_t itemId = getNumber<uint16_t>(L, 1);
uint32_t count = getNumber<uint32_t>(L, 2, 1);
const ItemType& it = Item::items[itemId];
if (it.hasSubType()) {
if (it.stackable) {
itemCount = static_cast<int32_t>(std::ceil(static_cast<float>(count) / 100));
}
subType = count;
} else {
itemCount = std::max<int32_t>(1, count);
}
while (itemCount > 0) {
int32_t stackCount = std::min<int32_t>(100, subType);
Item* newItem = Item::CreateItem(itemId, stackCount);
if (!newItem) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (it.stackable) {
subType -= stackCount;
}
ReturnValue ret = g_game.internalAddItem(tile, newItem, INDEX_WHEREEVER, FLAG_NOLIMIT);
if (ret != RETURNVALUE_NOERROR) {
delete newItem;
pushBoolean(L, false);
return 1;
}
if (--itemCount == 0) {
if (newItem->getParent()) {
uint32_t uid = env->addThing(newItem);
lua_pushnumber(L, uid);
return 1;
} else {
//stackable item stacked with existing object, newItem will be released
pushBoolean(L, false);
return 1;
}
}
}
pushBoolean(L, false);
return 1;
}
int LuaScriptInterface::luaDoCreateItemEx(lua_State* L)
{
//doCreateItemEx(itemid, <optional> count/subtype)
//Returns uid of the created item
uint16_t itemId = getNumber<uint16_t>(L, 1);
uint32_t count = getNumber<uint32_t>(L, 2, 1);
const ItemType& it = Item::items[itemId];
if (it.stackable && count > 100) {
reportErrorFunc("Stack count cannot be higher than 100.");
count = 100;
}
Item* newItem = Item::CreateItem(itemId, count);
if (!newItem) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
newItem->setParent(VirtualCylinder::virtualCylinder);
ScriptEnvironment* env = getScriptEnv();
env->addTempItem(newItem);
uint32_t uid = env->addThing(newItem);
lua_pushnumber(L, uid);
return 1;
}
int LuaScriptInterface::luaDebugPrint(lua_State* L)
{
//debugPrint(text)
reportErrorFunc(getString(L, -1));
return 0;
}
int LuaScriptInterface::luaGetWorldTime(lua_State* L)
{
//getWorldTime()
uint32_t time = g_game.getLightHour();
lua_pushnumber(L, time);
return 1;
}
int LuaScriptInterface::luaGetWorldLight(lua_State* L)
{
//getWorldLight()
LightInfo lightInfo;
g_game.getWorldLightInfo(lightInfo);
lua_pushnumber(L, lightInfo.level);
lua_pushnumber(L, lightInfo.color);
return 2;
}
int LuaScriptInterface::luaGetWorldUpTime(lua_State* L)
{
//getWorldUpTime()
uint64_t uptime = (OTSYS_TIME() - ProtocolStatus::start) / 1000;
lua_pushnumber(L, uptime);
return 1;
}
int LuaScriptInterface::luaCreateCombatObject(lua_State* L)
{
//createCombatObject()
ScriptEnvironment* env = getScriptEnv();
if (env->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
lua_pushnumber(L, g_luaEnvironment.createCombatObject(env->getScriptInterface()));
return 1;
}
bool LuaScriptInterface::getArea(lua_State* L, std::list<uint32_t>& list, uint32_t& rows)
{
lua_pushnil(L);
for (rows = 0; lua_next(L, -2) != 0; ++rows) {
if (!isTable(L, -1)) {
return false;
}
lua_pushnil(L);
while (lua_next(L, -2) != 0) {
if (!isNumber(L, -1)) {
return false;
}
list.push_back(getNumber<uint32_t>(L, -1));
lua_pop(L, 1);
}
lua_pop(L, 1);
}
lua_pop(L, 1);
return (rows != 0);
}
int LuaScriptInterface::luaCreateCombatArea(lua_State* L)
{
//createCombatArea( {area}, <optional> {extArea} )
ScriptEnvironment* env = getScriptEnv();
if (env->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
uint32_t areaId = g_luaEnvironment.createAreaObject(env->getScriptInterface());
AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
int parameters = lua_gettop(L);
if (parameters >= 2) {
uint32_t rowsExtArea;
std::list<uint32_t> listExtArea;
if (!getArea(L, listExtArea, rowsExtArea)) {
reportErrorFunc("Invalid extended area table.");
pushBoolean(L, false);
return 1;
}
area->setupExtArea(listExtArea, rowsExtArea);
}
uint32_t rowsArea = 0;
std::list<uint32_t> listArea;
if (!getArea(L, listArea, rowsArea)) {
reportErrorFunc("Invalid area table.");
pushBoolean(L, false);
return 1;
}
area->setupArea(listArea, rowsArea);
lua_pushnumber(L, areaId);
return 1;
}
int LuaScriptInterface::luaCreateConditionObject(lua_State* L)
{
//createConditionObject(type)
ScriptEnvironment* env = getScriptEnv();
if (env->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
ConditionType_t type = getNumber<ConditionType_t>(L, -1);
uint32_t id;
if (g_luaEnvironment.createConditionObject(type, CONDITIONID_COMBAT, id)) {
lua_pushnumber(L, id);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaSetCombatArea(lua_State* L)
{
//setCombatArea(combat, area)
if (getScriptEnv()->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
uint32_t combatId = getNumber<uint32_t>(L, 1);
Combat* combat = g_luaEnvironment.getCombatObject(combatId);
if (!combat) {
reportErrorFunc(getErrorDesc(LUA_ERROR_COMBAT_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 2);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (!area) {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
combat->setArea(new AreaCombat(*area));
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaSetCombatCondition(lua_State* L)
{
//setCombatCondition(combat, condition)
if (getScriptEnv()->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
uint32_t combatId = getNumber<uint32_t>(L, 1);
Combat* combat = g_luaEnvironment.getCombatObject(combatId);
if (!combat) {
reportErrorFunc(getErrorDesc(LUA_ERROR_COMBAT_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t conditionId = getNumber<uint32_t>(L, 2);
const Condition* condition = g_luaEnvironment.getConditionObject(conditionId);
if (!condition) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
combat->setCondition(condition->clone());
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaSetCombatParam(lua_State* L)
{
//setCombatParam(combat, key, value)
if (getScriptEnv()->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
uint32_t combatId = getNumber<uint32_t>(L, 1);
Combat* combat = g_luaEnvironment.getCombatObject(combatId);
if (combat) {
CombatParam_t key = getNumber<CombatParam_t>(L, 2);
uint32_t value = getNumber<uint32_t>(L, 3);
combat->setParam(key, value);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_COMBAT_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaSetConditionParam(lua_State* L)
{
//setConditionParam(condition, key, value)
if (getScriptEnv()->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
uint32_t conditionId = getNumber<uint32_t>(L, 1);
Condition* condition = g_luaEnvironment.getConditionObject(conditionId);
if (!condition) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
ConditionParam_t key = getNumber<ConditionParam_t>(L, 2);
int32_t value;
if (isBoolean(L, 3)) {
value = getBoolean(L, 3) ? 1 : 0;
} else {
value = getNumber<int32_t>(L, 3);
}
condition->setParam(key, value);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaAddDamageCondition(lua_State* L)
{
//addDamageCondition(condition, rounds, time, value)
if (getScriptEnv()->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
uint32_t conditionId = getNumber<uint32_t>(L, 1);
ConditionDamage* condition = dynamic_cast<ConditionDamage*>(g_luaEnvironment.getConditionObject(conditionId));
if (condition) {
int32_t rounds = getNumber<int32_t>(L, 2);
int32_t time = getNumber<int32_t>(L, 3);
int32_t value = getNumber<int32_t>(L, 4);
condition->addDamage(rounds, time, value);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaAddOutfitCondition(lua_State* L)
{
//addOutfitCondition(condition, lookTypeEx, lookType, lookHead, lookBody, lookLegs, lookFeet[, lookAddons, lookMount])
if (getScriptEnv()->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
uint32_t conditionId = getNumber<uint32_t>(L, 1);
ConditionOutfit* condition = dynamic_cast<ConditionOutfit*>(g_luaEnvironment.getConditionObject(conditionId));
if (condition) {
Outfit_t outfit;
outfit.lookTypeEx = getNumber<uint32_t>(L, 2);
outfit.lookType = getNumber<uint32_t>(L, 3);
outfit.lookHead = getNumber<uint32_t>(L, 4);
outfit.lookBody = getNumber<uint32_t>(L, 5);
outfit.lookLegs = getNumber<uint32_t>(L, 6);
outfit.lookFeet = getNumber<uint32_t>(L, 7);
outfit.lookAddons = getNumber<uint32_t>(L, 8, outfit.lookAddons);
outfit.lookMount = getNumber<uint32_t>(L, 9, outfit.lookMount);
condition->setOutfit(outfit);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaSetCombatCallBack(lua_State* L)
{
//setCombatCallBack(combat, key, function_name)
ScriptEnvironment* env = getScriptEnv();
if (env->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
uint32_t combatId = getNumber<uint32_t>(L, 1);
Combat* combat = g_luaEnvironment.getCombatObject(combatId);
if (!combat) {
reportErrorFunc(getErrorDesc(LUA_ERROR_COMBAT_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CallBackParam_t key = getNumber<CallBackParam_t>(L, 2);
combat->setCallback(key);
CallBack* callback = combat->getCallback(key);
if (!callback) {
std::ostringstream ss;
ss << key << " is not a valid callback key.";
reportErrorFunc(ss.str());
pushBoolean(L, false);
return 1;
}
std::string function = getString(L, 3);
if (!callback->loadCallBack(env->getScriptInterface(), function)) {
reportErrorFunc("Can not load callback");
pushBoolean(L, false);
return 1;
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaSetCombatFormula(lua_State* L)
{
//setCombatFormula(combat, type, mina, minb, maxa, maxb)
if (getScriptEnv()->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
uint32_t combatId = getNumber<uint32_t>(L, 1);
Combat* combat = g_luaEnvironment.getCombatObject(combatId);
if (combat) {
combat->setPlayerCombatValues(
getNumber<formulaType_t>(L, 2),
getNumber<float>(L, 3),
getNumber<float>(L, 4),
getNumber<float>(L, 5),
getNumber<float>(L, 6)
);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_COMBAT_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaSetConditionFormula(lua_State* L)
{
//setConditionFormula(condition, mina, minb, maxa, maxb)
if (getScriptEnv()->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
uint32_t conditionId = getNumber<uint32_t>(L, 1);
ConditionSpeed* condition = dynamic_cast<ConditionSpeed*>(g_luaEnvironment.getConditionObject(conditionId));
if (condition) {
condition->setFormulaVars(
getNumber<double>(L, 2),
getNumber<double>(L, 3),
getNumber<double>(L, 4),
getNumber<double>(L, 5)
);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoCombat(lua_State* L)
{
//doCombat(cid, combat, param)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t combatId = getNumber<uint32_t>(L, 2);
const Combat* combat = g_luaEnvironment.getCombatObject(combatId);
if (!combat) {
reportErrorFunc(getErrorDesc(LUA_ERROR_COMBAT_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
const LuaVariant& var = getVariant(L, 3);
switch (var.type) {
case VARIANT_NUMBER: {
Creature* target = g_game.getCreatureByID(var.number);
if (!target) {
pushBoolean(L, false);
return 1;
}
if (combat->hasArea()) {
combat->doCombat(creature, target->getPosition());
//std::cout << "Combat->hasArea()" << std::endl;
} else {
combat->doCombat(creature, target);
}
break;
}
case VARIANT_POSITION: {
combat->doCombat(creature, var.pos);
break;
}
case VARIANT_TARGETPOSITION: {
if (combat->hasArea()) {
combat->doCombat(creature, var.pos);
} else {
combat->postCombatEffects(creature, var.pos);
g_game.addMagicEffect(var.pos, CONST_ME_POFF);
}
break;
}
case VARIANT_STRING: {
Player* target = g_game.getPlayerByName(var.text);
if (!target) {
pushBoolean(L, false);
return 1;
}
combat->doCombat(creature, target);
break;
}
case VARIANT_NONE: {
reportErrorFunc(getErrorDesc(LUA_ERROR_VARIANT_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
default: {
reportErrorFunc(getErrorDesc(LUA_ERROR_VARIANT_UNKNOWN));
pushBoolean(L, false);
return 1;
}
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoAreaCombatHealth(lua_State* L)
{
//doAreaCombatHealth(cid, type, pos, area, min, max, effect[, origin = ORIGIN_SPELL])
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 4);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (area || areaId == 0) {
CombatType_t combatType = getNumber<CombatType_t>(L, 2);
CombatParams params;
params.combatType = combatType;
params.impactEffect = getNumber<uint8_t>(L, 7);
CombatDamage damage;
damage.origin = getNumber<CombatOrigin>(L, 8, ORIGIN_SPELL);
damage.primary.type = combatType;
damage.primary.value = normal_random(getNumber<int32_t>(L, 6), getNumber<int32_t>(L, 5));
Combat::doCombatHealth(creature, getPosition(L, 3), area, damage, params);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoTargetCombatHealth(lua_State* L)
{
//doTargetCombatHealth(cid, target, type, min, max, effect[, origin = ORIGIN_SPELL])
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CombatType_t combatType = getNumber<CombatType_t>(L, 3);
CombatParams params;
params.combatType = combatType;
params.impactEffect = getNumber<uint8_t>(L, 6);
CombatDamage damage;
damage.origin = getNumber<CombatOrigin>(L, 7, ORIGIN_SPELL);
damage.primary.type = combatType;
damage.primary.value = normal_random(getNumber<int32_t>(L, 4), getNumber<int32_t>(L, 5));
Combat::doCombatHealth(creature, target, damage, params);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoAreaCombatMana(lua_State* L)
{
//doAreaCombatMana(cid, pos, area, min, max, effect[, origin = ORIGIN_SPELL])
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 3);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (area || areaId == 0) {
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 6);
CombatDamage damage;
damage.origin = getNumber<CombatOrigin>(L, 7, ORIGIN_SPELL);
damage.primary.type = COMBAT_MANADRAIN;
damage.primary.value = normal_random(getNumber<int32_t>(L, 4), getNumber<int32_t>(L, 5));
Position pos = getPosition(L, 2);
Combat::doCombatMana(creature, pos, area, damage, params);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoTargetCombatMana(lua_State* L)
{
//doTargetCombatMana(cid, target, min, max, effect[, origin = ORIGIN_SPELL)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 5);
CombatDamage damage;
damage.origin = getNumber<CombatOrigin>(L, 6, ORIGIN_SPELL);
damage.primary.type = COMBAT_MANADRAIN;
damage.primary.value = normal_random(getNumber<int32_t>(L, 3), getNumber<int32_t>(L, 4));
Combat::doCombatMana(creature, target, damage, params);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoAreaCombatCondition(lua_State* L)
{
//doAreaCombatCondition(cid, pos, area, condition, effect)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t conditionId = getNumber<uint32_t>(L, 4);
const Condition* condition = g_luaEnvironment.getConditionObject(conditionId);
if (!condition) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 3);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (area || areaId == 0) {
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 5);
params.conditionList.push_front(condition);
Combat::doCombatCondition(creature, getPosition(L, 2), area, params);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoTargetCombatCondition(lua_State* L)
{
//doTargetCombatCondition(cid, target, condition, effect)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t conditionId = getNumber<uint32_t>(L, 3);
const Condition* condition = g_luaEnvironment.getConditionObject(conditionId);
if (!condition) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 4);
params.conditionList.push_front(condition);
Combat::doCombatCondition(creature, target, params);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoAreaCombatDispel(lua_State* L)
{
//doAreaCombatDispel(cid, pos, area, type, effect)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 3);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (area || areaId == 0) {
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 5);
params.dispelType = getNumber<ConditionType_t>(L, 4);
Combat::doCombatDispel(creature, getPosition(L, 2), area, params);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoTargetCombatDispel(lua_State* L)
{
//doTargetCombatDispel(cid, target, type, effect)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CombatParams params;
params.dispelType = getNumber<ConditionType_t>(L, 3);
params.impactEffect = getNumber<uint8_t>(L, 4);
Combat::doCombatDispel(creature, target, params);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoChallengeCreature(lua_State* L)
{
//doChallengeCreature(cid, target)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
target->challengeCreature(creature);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaSetCreatureOutfit(lua_State* L)
{
//doSetCreatureOutfit(cid, outfit, time)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Outfit_t outfit = getOutfit(L, 2);
int32_t time = getNumber<int32_t>(L, 3);
pushBoolean(L, Spell::CreateIllusion(creature, outfit, time) == RETURNVALUE_NOERROR);
return 1;
}
int LuaScriptInterface::luaSetMonsterOutfit(lua_State* L)
{
//doSetMonsterOutfit(cid, name, time)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
std::string name = getString(L, 2);
int32_t time = getNumber<int32_t>(L, 3);
pushBoolean(L, Spell::CreateIllusion(creature, name, time) == RETURNVALUE_NOERROR);
return 1;
}
int LuaScriptInterface::luaSetItemOutfit(lua_State* L)
{
//doSetItemOutfit(cid, item, time)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t item = getNumber<uint32_t>(L, 2);
int32_t time = getNumber<int32_t>(L, 3);
pushBoolean(L, Spell::CreateIllusion(creature, item, time) == RETURNVALUE_NOERROR);
return 1;
}
int LuaScriptInterface::luaDoMoveCreature(lua_State* L)
{
//doMoveCreature(cid, direction)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Direction direction = getNumber<Direction>(L, 2);
if (direction > DIRECTION_LAST) {
reportErrorFunc("No valid direction");
pushBoolean(L, false);
return 1;
}
ReturnValue ret = g_game.internalMoveCreature(creature, direction, FLAG_NOLIMIT);
lua_pushnumber(L, ret);
return 1;
}
int LuaScriptInterface::luaIsValidUID(lua_State* L)
{
//isValidUID(uid)
pushBoolean(L, getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, -1)) != nullptr);
return 1;
}
int LuaScriptInterface::luaIsDepot(lua_State* L)
{
//isDepot(uid)
Container* container = getScriptEnv()->getContainerByUID(getNumber<uint32_t>(L, -1));
pushBoolean(L, container && container->getDepotLocker());
return 1;
}
int LuaScriptInterface::luaIsMoveable(lua_State* L)
{
//isMoveable(uid)
//isMovable(uid)
Thing* thing = getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, -1));
pushBoolean(L, thing && thing->isPushable());
return 1;
}
int LuaScriptInterface::luaDoAddContainerItem(lua_State* L)
{
//doAddContainerItem(uid, itemid, <optional> count/subtype)
uint32_t uid = getNumber<uint32_t>(L, 1);
ScriptEnvironment* env = getScriptEnv();
Container* container = env->getContainerByUID(uid);
if (!container) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONTAINER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint16_t itemId = getNumber<uint16_t>(L, 2);
const ItemType& it = Item::items[itemId];
int32_t itemCount = 1;
int32_t subType = 1;
uint32_t count = getNumber<uint32_t>(L, 3, 1);
if (it.hasSubType()) {
if (it.stackable) {
itemCount = static_cast<int32_t>(std::ceil(static_cast<float>(count) / 100));
}
subType = count;
} else {
itemCount = std::max<int32_t>(1, count);
}
while (itemCount > 0) {
int32_t stackCount = std::min<int32_t>(100, subType);
Item* newItem = Item::CreateItem(itemId, stackCount);
if (!newItem) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (it.stackable) {
subType -= stackCount;
}
ReturnValue ret = g_game.internalAddItem(container, newItem);
if (ret != RETURNVALUE_NOERROR) {
delete newItem;
pushBoolean(L, false);
return 1;
}
if (--itemCount == 0) {
if (newItem->getParent()) {
lua_pushnumber(L, env->addThing(newItem));
} else {
//stackable item stacked with existing object, newItem will be released
pushBoolean(L, false);
}
return 1;
}
}
pushBoolean(L, false);
return 1;
}
int LuaScriptInterface::luaGetDepotId(lua_State* L)
{
//getDepotId(uid)
uint32_t uid = getNumber<uint32_t>(L, -1);
Container* container = getScriptEnv()->getContainerByUID(uid);
if (!container) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONTAINER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
DepotLocker* depotLocker = container->getDepotLocker();
if (!depotLocker) {
reportErrorFunc("Depot not found");
pushBoolean(L, false);
return 1;
}
lua_pushnumber(L, depotLocker->getDepotId());
return 1;
}
int LuaScriptInterface::luaIsInArray(lua_State* L)
{
//isInArray(array, value)
if (!isTable(L, 1)) {
pushBoolean(L, false);
return 1;
}
lua_pushnil(L);
while (lua_next(L, 1)) {
if (lua_equal(L, 2, -1) != 0) {
pushBoolean(L, true);
return 1;
}
lua_pop(L, 1);
}
pushBoolean(L, false);
return 1;
}
int LuaScriptInterface::luaDoSetCreatureLight(lua_State* L)
{
//doSetCreatureLight(cid, lightLevel, lightColor, time)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint16_t level = getNumber<uint16_t>(L, 2);
uint16_t color = getNumber<uint16_t>(L, 3);
uint32_t time = getNumber<uint32_t>(L, 4);
Condition* condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_LIGHT, time, level | (color << 8));
creature->addCondition(condition);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaAddEvent(lua_State* L)
{
//addEvent(callback, delay, ...)
lua_State* globalState = g_luaEnvironment.getLuaState();
if (!globalState) {
reportErrorFunc("No valid script interface!");
pushBoolean(L, false);
return 1;
} else if (globalState != L) {
lua_xmove(L, globalState, lua_gettop(L));
}
int parameters = lua_gettop(globalState);
if (!isFunction(globalState, -parameters)) { //-parameters means the first parameter from left to right
reportErrorFunc("callback parameter should be a function.");
pushBoolean(L, false);
return 1;
}
if (g_config.getBoolean(ConfigManager::WARN_UNSAFE_SCRIPTS) || g_config.getBoolean(ConfigManager::CONVERT_UNSAFE_SCRIPTS)) {
std::vector<std::pair<int32_t, LuaDataType>> indexes;
for (int i = 3; i <= parameters; ++i) {
if (lua_getmetatable(globalState, i) == 0) {
continue;
}
lua_rawgeti(L, -1, 't');
LuaDataType type = getNumber<LuaDataType>(L, -1);
if (type != LuaData_Unknown && type != LuaData_Tile) {
indexes.push_back({i, type});
}
lua_pop(globalState, 2);
}
if (!indexes.empty()) {
if (g_config.getBoolean(ConfigManager::WARN_UNSAFE_SCRIPTS)) {
bool plural = indexes.size() > 1;
std::string warningString = "Argument";
if (plural) {
warningString += 's';
}
for (const auto& entry : indexes) {
if (entry == indexes.front()) {
warningString += ' ';
} else if (entry == indexes.back()) {
warningString += " and ";
} else {
warningString += ", ";
}
warningString += '#';
warningString += std::to_string(entry.first);
}
if (plural) {
warningString += " are unsafe";
} else {
warningString += " is unsafe";
}
reportErrorFunc(warningString);
}
if (g_config.getBoolean(ConfigManager::CONVERT_UNSAFE_SCRIPTS)) {
for (const auto& entry : indexes) {
switch (entry.second) {
case LuaData_Item:
case LuaData_Container:
case LuaData_Teleport: {
lua_getglobal(globalState, "Item");
lua_getfield(globalState, -1, "getUniqueId");
break;
}
case LuaData_Player:
case LuaData_Monster:
case LuaData_Npc: {
lua_getglobal(globalState, "Creature");
lua_getfield(globalState, -1, "getId");
break;
}
default:
break;
}
lua_replace(globalState, -2);
lua_pushvalue(globalState, entry.first);
lua_call(globalState, 1, 1);
lua_replace(globalState, entry.first);
}
}
}
}
LuaTimerEventDesc eventDesc;
for (int i = 0; i < parameters - 2; ++i) { //-2 because addEvent needs at least two parameters
eventDesc.parameters.push_back(luaL_ref(globalState, LUA_REGISTRYINDEX));
}
uint32_t delay = std::max<uint32_t>(100, getNumber<uint32_t>(globalState, 2));
lua_pop(globalState, 1);
eventDesc.function = luaL_ref(globalState, LUA_REGISTRYINDEX);
eventDesc.scriptId = getScriptEnv()->getScriptId();
auto& lastTimerEventId = g_luaEnvironment.m_lastEventTimerId;
eventDesc.eventId = g_scheduler.addEvent(createSchedulerTask(
delay, std::bind(&LuaEnvironment::executeTimerEvent, &g_luaEnvironment, lastTimerEventId)
));
g_luaEnvironment.m_timerEvents.emplace(lastTimerEventId, std::move(eventDesc));
lua_pushnumber(L, lastTimerEventId++);
return 1;
}
int LuaScriptInterface::luaStopEvent(lua_State* L)
{
//stopEvent(eventid)
lua_State* globalState = g_luaEnvironment.getLuaState();
if (!globalState) {
reportErrorFunc("No valid script interface!");
pushBoolean(L, false);
return 1;
}
uint32_t eventId = getNumber<uint32_t>(L, 1);
auto& timerEvents = g_luaEnvironment.m_timerEvents;
auto it = timerEvents.find(eventId);
if (it == timerEvents.end()) {
pushBoolean(L, false);
return 1;
}
LuaTimerEventDesc timerEventDesc = std::move(it->second);
timerEvents.erase(it);
g_scheduler.stopEvent(timerEventDesc.eventId);
luaL_unref(globalState, LUA_REGISTRYINDEX, timerEventDesc.function);
for (auto parameter : timerEventDesc.parameters) {
luaL_unref(globalState, LUA_REGISTRYINDEX, parameter);
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaGetCreatureCondition(lua_State* L)
{
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
ConditionType_t condition = getNumber<ConditionType_t>(L, 2);
uint32_t subId = getNumber<uint32_t>(L, 3, 0);
pushBoolean(L, creature->hasCondition(condition, subId));
return 1;
}
int LuaScriptInterface::luaSaveServer(lua_State* L)
{
g_game.saveGameState();
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCleanMap(lua_State* L)
{
lua_pushnumber(L, g_game.map.clean());
return 1;
}
int LuaScriptInterface::luaIsInWar(lua_State* L)
{
//isInWar(cid, target)
Player* player = getPlayer(L, 1);
if (!player) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Player* targetPlayer = getPlayer(L, 2);
if (!targetPlayer) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
pushBoolean(L, player->isInWar(targetPlayer));
return 1;
}
int LuaScriptInterface::luaDoPlayerSetOfflineTrainingSkill(lua_State* L)
{
//doPlayerSetOfflineTrainingSkill(cid, skillid)
Player* player = getPlayer(L, 1);
if (player) {
uint32_t skillid = getNumber<uint32_t>(L, 2);
player->setOfflineTrainingSkill(skillid);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaGetWaypointPositionByName(lua_State* L)
{
//getWaypointPositionByName(name)
auto& waypoints = g_game.map.waypoints;
auto it = waypoints.find(getString(L, -1));
if (it != waypoints.end()) {
pushPosition(L, it->second);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaSendChannelMessage(lua_State* L)
{
//sendChannelMessage(channelId, type, message)
uint32_t channelId = getNumber<uint32_t>(L, 1);
ChatChannel* channel = g_chat->getChannelById(channelId);
if (!channel) {
pushBoolean(L, false);
return 1;
}
SpeakClasses type = getNumber<SpeakClasses>(L, 2);
std::string message = getString(L, 3);
channel->sendToAll(message, type);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaSendGuildChannelMessage(lua_State* L)
{
//sendGuildChannelMessage(guildId, type, message)
uint32_t guildId = getNumber<uint32_t>(L, 1);
ChatChannel* channel = g_chat->getGuildChannelById(guildId);
if (!channel) {
pushBoolean(L, false);
return 1;
}
SpeakClasses type = getNumber<SpeakClasses>(L, 2);
std::string message = getString(L, 3);
channel->sendToAll(message, type);
pushBoolean(L, true);
return 1;
}
std::string LuaScriptInterface::escapeString(const std::string& string)
{
std::string s = string;
replaceString(s, "\\", "\\\\");
replaceString(s, "\"", "\\\"");
replaceString(s, "'", "\\'");
replaceString(s, "[[", "\\[[");
return s;
}
#ifndef LUAJIT_VERSION
const luaL_Reg LuaScriptInterface::luaBitReg[] = {
//{"tobit", LuaScriptInterface::luaBitToBit},
{"bnot", LuaScriptInterface::luaBitNot},
{"band", LuaScriptInterface::luaBitAnd},
{"bor", LuaScriptInterface::luaBitOr},
{"bxor", LuaScriptInterface::luaBitXor},
{"lshift", LuaScriptInterface::luaBitLeftShift},
{"rshift", LuaScriptInterface::luaBitRightShift},
//{"arshift", LuaScriptInterface::luaBitArithmeticalRightShift},
//{"rol", LuaScriptInterface::luaBitRotateLeft},
//{"ror", LuaScriptInterface::luaBitRotateRight},
//{"bswap", LuaScriptInterface::luaBitSwapEndian},
//{"tohex", LuaScriptInterface::luaBitToHex},
{nullptr, nullptr}
};
int LuaScriptInterface::luaBitNot(lua_State* L)
{
lua_pushnumber(L, ~getNumber<uint32_t>(L, -1));
return 1;
}
#define MULTIOP(name, op) \
int LuaScriptInterface::luaBit##name(lua_State* L) \
{ \
int n = lua_gettop(L); \
uint32_t w = getNumber<uint32_t>(L, -1); \
for (int i = 1; i < n; ++i) \
w op getNumber<uint32_t>(L, i); \
lua_pushnumber(L, w); \
return 1; \
}
MULTIOP(And, &= )
MULTIOP(Or, |= )
MULTIOP(Xor, ^= )
#define SHIFTOP(name, op) \
int LuaScriptInterface::luaBit##name(lua_State* L) \
{ \
uint32_t n1 = getNumber<uint32_t>(L, 1), n2 = getNumber<uint32_t>(L, 2); \
lua_pushnumber(L, (n1 op n2)); \
return 1; \
}
SHIFTOP(LeftShift, << )
SHIFTOP(RightShift, >> )
#endif
const luaL_Reg LuaScriptInterface::luaConfigManagerTable[] = {
{"getString", LuaScriptInterface::luaConfigManagerGetString},
{"getNumber", LuaScriptInterface::luaConfigManagerGetNumber},
{"getBoolean", LuaScriptInterface::luaConfigManagerGetBoolean},
{nullptr, nullptr}
};
int LuaScriptInterface::luaConfigManagerGetString(lua_State* L)
{
pushString(L, g_config.getString(getNumber<ConfigManager::string_config_t>(L, -1)));
return 1;
}
int LuaScriptInterface::luaConfigManagerGetNumber(lua_State* L)
{
lua_pushnumber(L, g_config.getNumber(getNumber<ConfigManager::integer_config_t>(L, -1)));
return 1;
}
int LuaScriptInterface::luaConfigManagerGetBoolean(lua_State* L)
{
pushBoolean(L, g_config.getBoolean(getNumber<ConfigManager::boolean_config_t>(L, -1)));
return 1;
}
const luaL_Reg LuaScriptInterface::luaDatabaseTable[] = {
{"query", LuaScriptInterface::luaDatabaseExecute},
{"asyncQuery", LuaScriptInterface::luaDatabaseAsyncExecute},
{"storeQuery", LuaScriptInterface::luaDatabaseStoreQuery},
{"asyncStoreQuery", LuaScriptInterface::luaDatabaseAsyncStoreQuery},
{"escapeString", LuaScriptInterface::luaDatabaseEscapeString},
{"escapeBlob", LuaScriptInterface::luaDatabaseEscapeBlob},
{"lastInsertId", LuaScriptInterface::luaDatabaseLastInsertId},
{"tableExists", LuaScriptInterface::luaDatabaseTableExists},
{nullptr, nullptr}
};
int LuaScriptInterface::luaDatabaseExecute(lua_State* L)
{
pushBoolean(L, Database::getInstance()->executeQuery(getString(L, -1)));
return 1;
}
int LuaScriptInterface::luaDatabaseAsyncExecute(lua_State* L)
{
std::function<void(DBResult_ptr, bool)> callback;
if (lua_gettop(L) > 1) {
int32_t ref = luaL_ref(L, LUA_REGISTRYINDEX);
callback = [ref](DBResult_ptr, bool success) {
lua_State* luaState = g_luaEnvironment.getLuaState();
if (!luaState) {
return;
}
if (!LuaScriptInterface::reserveScriptEnv()) {
luaL_unref(luaState, LUA_REGISTRYINDEX, ref);
return;
}
lua_rawgeti(luaState, LUA_REGISTRYINDEX, ref);
pushBoolean(luaState, success);
g_luaEnvironment.callFunction(1);
luaL_unref(luaState, LUA_REGISTRYINDEX, ref);
};
}
g_databaseTasks.addTask(getString(L, -1), callback);
return 0;
}
int LuaScriptInterface::luaDatabaseStoreQuery(lua_State* L)
{
if (DBResult_ptr res = Database::getInstance()->storeQuery(getString(L, -1))) {
lua_pushnumber(L, ScriptEnvironment::addResult(res));
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDatabaseAsyncStoreQuery(lua_State* L)
{
std::function<void(DBResult_ptr, bool)> callback;
if (lua_gettop(L) > 1) {
int32_t ref = luaL_ref(L, LUA_REGISTRYINDEX);
callback = [ref](DBResult_ptr result, bool) {
lua_State* luaState = g_luaEnvironment.getLuaState();
if (!luaState) {
return;
}
if (!LuaScriptInterface::reserveScriptEnv()) {
luaL_unref(luaState, LUA_REGISTRYINDEX, ref);
return;
}
lua_rawgeti(luaState, LUA_REGISTRYINDEX, ref);
if (result) {
lua_pushnumber(luaState, ScriptEnvironment::addResult(result));
} else {
pushBoolean(luaState, false);
}
g_luaEnvironment.callFunction(1);
luaL_unref(luaState, LUA_REGISTRYINDEX, ref);
};
}
g_databaseTasks.addTask(getString(L, -1), callback, true);
return 0;
}
int LuaScriptInterface::luaDatabaseEscapeString(lua_State* L)
{
pushString(L, Database::getInstance()->escapeString(getString(L, -1)));
return 1;
}
int LuaScriptInterface::luaDatabaseEscapeBlob(lua_State* L)
{
uint32_t length = getNumber<uint32_t>(L, 2);
pushString(L, Database::getInstance()->escapeBlob(getString(L, 1).c_str(), length));
return 1;
}
int LuaScriptInterface::luaDatabaseLastInsertId(lua_State* L)
{
lua_pushnumber(L, Database::getInstance()->getLastInsertId());
return 1;
}
int LuaScriptInterface::luaDatabaseTableExists(lua_State* L)
{
pushBoolean(L, DatabaseManager::tableExists(getString(L, -1)));
return 1;
}
const luaL_Reg LuaScriptInterface::luaResultTable[] = {
{"getNumber", LuaScriptInterface::luaResultGetNumber},
{"getString", LuaScriptInterface::luaResultGetString},
{"getStream", LuaScriptInterface::luaResultGetStream},
{"next", LuaScriptInterface::luaResultNext},
{"free", LuaScriptInterface::luaResultFree},
{nullptr, nullptr}
};
int LuaScriptInterface::luaResultGetNumber(lua_State* L)
{
DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1));
if (!res) {
pushBoolean(L, false);
return 1;
}
const std::string& s = getString(L, 2);
lua_pushnumber(L, res->getNumber<int64_t>(s));
return 1;
}
int LuaScriptInterface::luaResultGetString(lua_State* L)
{
DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1));
if (!res) {
pushBoolean(L, false);
return 1;
}
const std::string& s = getString(L, 2);
pushString(L, res->getString(s));
return 1;
}
int LuaScriptInterface::luaResultGetStream(lua_State* L)
{
DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1));
if (!res) {
pushBoolean(L, false);
return 1;
}
unsigned long length;
const char* stream = res->getStream(getString(L, 2), length);
lua_pushlstring(L, stream, length);
lua_pushnumber(L, length);
return 2;
}
int LuaScriptInterface::luaResultNext(lua_State* L)
{
DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, -1));
if (!res) {
pushBoolean(L, false);
return 1;
}
pushBoolean(L, res->next());
return 1;
}
int LuaScriptInterface::luaResultFree(lua_State* L)
{
pushBoolean(L, ScriptEnvironment::removeResult(getNumber<uint32_t>(L, -1)));
return 1;
}
// Userdata
int LuaScriptInterface::luaUserdataCompare(lua_State* L)
{
// userdataA == userdataB
pushBoolean(L, getUserdata<void>(L, 1) == getUserdata<void>(L, 2));
return 1;
}
// _G
int LuaScriptInterface::luaIsType(lua_State* L)
{
// isType(derived, base)
lua_getmetatable(L, -2);
lua_getmetatable(L, -2);
lua_rawgeti(L, -2, 'p');
uint_fast8_t parentsB = getNumber<uint_fast8_t>(L, 1);
lua_rawgeti(L, -3, 'h');
size_t hashB = getNumber<size_t>(L, 1);
lua_rawgeti(L, -3, 'p');
uint_fast8_t parentsA = getNumber<uint_fast8_t>(L, 1);
for (uint_fast8_t i = parentsA; i < parentsB; ++i) {
lua_getfield(L, -3, "__index");
lua_replace(L, -4);
}
lua_rawgeti(L, -4, 'h');
size_t hashA = getNumber<size_t>(L, 1);
pushBoolean(L, hashA == hashB);
return 1;
}
int LuaScriptInterface::luaRawGetMetatable(lua_State* L)
{
// rawgetmetatable(metatableName)
luaL_getmetatable(L, getString(L, 1).c_str());
return 1;
}
// os
int LuaScriptInterface::luaSystemTime(lua_State* L)
{
// os.mtime()
lua_pushnumber(L, OTSYS_TIME());
return 1;
}
// table
int LuaScriptInterface::luaTableCreate(lua_State* L)
{
// table.create(arrayLength, keyLength)
lua_createtable(L, getNumber<int32_t>(L, 1), getNumber<int32_t>(L, 2));
return 1;
}
// Game
int LuaScriptInterface::luaGameGetSpectators(lua_State* L)
{
// Game.getSpectators(position[, multifloor = false[, onlyPlayer = false[, minRangeX = 0[, maxRangeX = 0[, minRangeY = 0[, maxRangeY = 0]]]]]])
const Position& position = getPosition(L, 1);
bool multifloor = getBoolean(L, 2, false);
bool onlyPlayers = getBoolean(L, 3, false);
int32_t minRangeX = getNumber<int32_t>(L, 4, 0);
int32_t maxRangeX = getNumber<int32_t>(L, 5, 0);
int32_t minRangeY = getNumber<int32_t>(L, 6, 0);
int32_t maxRangeY = getNumber<int32_t>(L, 7, 0);
SpectatorVec spectators;
g_game.map.getSpectators(spectators, position, multifloor, onlyPlayers, minRangeX, maxRangeX, minRangeY, maxRangeY);
lua_createtable(L, spectators.size(), 0);
int index = 0;
for (Creature* creature : spectators) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGameGetPlayers(lua_State* L)
{
// Game.getPlayers()
lua_createtable(L, g_game.getPlayersOnline(), 0);
int index = 0;
for (const auto& playerEntry : g_game.getPlayers()) {
pushUserdata<Player>(L, playerEntry.second);
setMetatable(L, -1, "Player");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGameLoadMap(lua_State* L)
{
// Game.loadMap(path)
const std::string& path = getString(L, 1);
g_dispatcher.addTask(createTask(std::bind(&Game::loadMap, &g_game, path)));
return 0;
}
int LuaScriptInterface::luaGameGetExperienceStage(lua_State* L)
{
// Game.getExperienceStage(level)
uint32_t level = getNumber<uint32_t>(L, 1);
lua_pushnumber(L, g_game.getExperienceStage(level));
return 1;
}
int LuaScriptInterface::luaGameGetMonsterCount(lua_State* L)
{
// Game.getMonsterCount()
lua_pushnumber(L, g_game.getMonstersOnline());
return 1;
}
int LuaScriptInterface::luaGameGetPlayerCount(lua_State* L)
{
// Game.getPlayerCount()
lua_pushnumber(L, g_game.getPlayersOnline());
return 1;
}
int LuaScriptInterface::luaGameGetNpcCount(lua_State* L)
{
// Game.getNpcCount()
lua_pushnumber(L, g_game.getNpcsOnline());
return 1;
}
int LuaScriptInterface::luaGameGetTowns(lua_State* L)
{
// Game.getTowns()
const auto& towns = g_game.map.towns.getTowns();
lua_createtable(L, towns.size(), 0);
int index = 0;
for (auto townEntry : towns) {
pushUserdata<Town>(L, townEntry.second);
setMetatable(L, -1, "Town");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGameGetHouses(lua_State* L)
{
// Game.getHouses()
const auto& houses = g_game.map.houses.getHouses();
lua_createtable(L, houses.size(), 0);
int index = 0;
for (auto houseEntry : houses) {
pushUserdata<House>(L, houseEntry.second);
setMetatable(L, -1, "House");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGameGetGameState(lua_State* L)
{
// Game.getGameState()
lua_pushnumber(L, g_game.getGameState());
return 1;
}
int LuaScriptInterface::luaGameSetGameState(lua_State* L)
{
// Game.setGameState(state)
GameState_t state = getNumber<GameState_t>(L, 1);
g_game.setGameState(state);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaGameGetWorldType(lua_State* L)
{
// Game.getWorldType()
lua_pushnumber(L, g_game.getWorldType());
return 1;
}
int LuaScriptInterface::luaGameSetWorldType(lua_State* L)
{
// Game.setWorldType(type)
WorldType_t type = getNumber<WorldType_t>(L, 1);
g_game.setWorldType(type);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaGameGetReturnMessage(lua_State* L)
{
// Game.getReturnMessage(value)
ReturnValue value = getNumber<ReturnValue>(L, 1);
pushString(L, getReturnMessage(value));
return 1;
}
int LuaScriptInterface::luaGameCreateItem(lua_State* L)
{
// Game.createItem(itemId[, count[, position]])
uint16_t count = getNumber<uint16_t>(L, 2, 1);
uint16_t id;
if (isNumber(L, 1)) {
id = getNumber<uint16_t>(L, 1);
} else {
id = Item::items.getItemIdByName(getString(L, 1));
if (id == 0) {
lua_pushnil(L);
return 1;
}
}
const ItemType& it = Item::items[id];
if (it.stackable) {
count = std::min<uint16_t>(count, 100);
}
Item* item = Item::CreateItem(id, count);
if (!item) {
lua_pushnil(L);
return 1;
}
if (lua_gettop(L) >= 3) {
const Position& position = getPosition(L, 3);
Tile* tile = g_game.map.getTile(position);
if (!tile) {
delete item;
lua_pushnil(L);
return 1;
}
g_game.internalAddItem(tile, item, INDEX_WHEREEVER, FLAG_NOLIMIT);
} else {
getScriptEnv()->addTempItem(item);
item->setParent(VirtualCylinder::virtualCylinder);
}
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
return 1;
}
int LuaScriptInterface::luaGameCreateContainer(lua_State* L)
{
// Game.createContainer(itemId, size[, position])
uint16_t size = getNumber<uint16_t>(L, 2);
uint16_t id;
if (isNumber(L, 1)) {
id = getNumber<uint16_t>(L, 1);
} else {
id = Item::items.getItemIdByName(getString(L, 1));
if (id == 0) {
lua_pushnil(L);
return 1;
}
}
Container* container = Item::CreateItemAsContainer(id, size);
if (!container) {
lua_pushnil(L);
return 1;
}
if (lua_gettop(L) >= 3) {
const Position& position = getPosition(L, 3);
Tile* tile = g_game.map.getTile(position);
if (!tile) {
delete container;
lua_pushnil(L);
return 1;
}
g_game.internalAddItem(tile, container, INDEX_WHEREEVER, FLAG_NOLIMIT);
} else {
getScriptEnv()->addTempItem(container);
container->setParent(VirtualCylinder::virtualCylinder);
}
pushUserdata<Container>(L, container);
setMetatable(L, -1, "Container");
return 1;
}
int LuaScriptInterface::luaGameCreateMonster(lua_State* L)
{
// Game.createMonster(monsterName, position[, extended = false[, force = false]])
Monster* monster = Monster::createMonster(getString(L, 1));
if (!monster) {
lua_pushnil(L);
return 1;
}
const Position& position = getPosition(L, 2);
bool extended = getBoolean(L, 3, false);
bool force = getBoolean(L, 4, false);
if (g_game.placeCreature(monster, position, extended, force)) {
pushUserdata<Monster>(L, monster);
setMetatable(L, -1, "Monster");
} else {
delete monster;
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGameCreateNpc(lua_State* L)
{
// Game.createNpc(npcName, position[, extended = false[, force = false]])
Npc* npc = Npc::createNpc(getString(L, 1));
if (!npc) {
lua_pushnil(L);
return 1;
}
const Position& position = getPosition(L, 2);
bool extended = getBoolean(L, 3, false);
bool force = getBoolean(L, 4, false);
if (g_game.placeCreature(npc, position, extended, force)) {
pushUserdata<Npc>(L, npc);
setMetatable(L, -1, "Npc");
} else {
delete npc;
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGameCreateTile(lua_State* L)
{
// Game.createTile(x, y, z[, isDynamic = false])
// Game.createTile(position[, isDynamic = false])
Position position;
bool isDynamic;
if (isTable(L, 1)) {
position = getPosition(L, 1);
isDynamic = getBoolean(L, 2, false);
} else {
position.x = getNumber<uint16_t>(L, 1);
position.y = getNumber<uint16_t>(L, 2);
position.z = getNumber<uint16_t>(L, 3);
isDynamic = getBoolean(L, 4, false);
}
Tile* tile = g_game.map.getTile(position);
if (!tile) {
if (isDynamic) {
tile = new DynamicTile(position.x, position.y, position.z);
} else {
tile = new StaticTile(position.x, position.y, position.z);
}
g_game.map.setTile(position, tile);
}
pushUserdata(L, tile);
setMetatable(L, -1, "Tile");
return 1;
}
int LuaScriptInterface::luaGameStartRaid(lua_State* L)
{
// Game.startRaid(raidName)
const std::string& raidName = getString(L, 1);
Raid* raid = g_game.raids.getRaidByName(raidName);
if (raid) {
raid->startRaid();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
// Variant
int LuaScriptInterface::luaVariantCreate(lua_State* L)
{
// Variant(number or string or position or thing)
LuaVariant variant;
if (isUserdata(L, 2)) {
if (Thing* thing = getThing(L, 2)) {
variant.type = VARIANT_TARGETPOSITION;
variant.pos = thing->getPosition();
}
} else if (isTable(L, 2)) {
variant.type = VARIANT_POSITION;
variant.pos = getPosition(L, 2);
} else if (isNumber(L, 2)) {
variant.type = VARIANT_NUMBER;
variant.number = getNumber<uint32_t>(L, 2);
} else if (isString(L, 2)) {
variant.type = VARIANT_STRING;
variant.text = getString(L, 2);
}
pushVariant(L, variant);
return 1;
}
int LuaScriptInterface::luaVariantGetNumber(lua_State* L)
{
// Variant:getNumber()
const LuaVariant& variant = getVariant(L, 1);
if (variant.type == VARIANT_NUMBER) {
lua_pushnumber(L, variant.number);
} else {
lua_pushnumber(L, 0);
}
return 1;
}
int LuaScriptInterface::luaVariantGetString(lua_State* L)
{
// Variant:getString()
const LuaVariant& variant = getVariant(L, 1);
if (variant.type == VARIANT_STRING) {
pushString(L, variant.text);
} else {
pushString(L, std::string());
}
return 1;
}
int LuaScriptInterface::luaVariantGetPosition(lua_State* L)
{
// Variant:getPosition()
const LuaVariant& variant = getVariant(L, 1);
if (variant.type == VARIANT_POSITION || variant.type == VARIANT_TARGETPOSITION) {
pushPosition(L, variant.pos);
} else {
pushPosition(L, Position());
}
return 1;
}
// Position
int LuaScriptInterface::luaPositionCreate(lua_State* L)
{
// Position([x = 0[, y = 0[, z = 0[, stackpos = 0]]]])
// Position([position])
if (lua_gettop(L) <= 1) {
pushPosition(L, Position());
return 1;
}
int32_t stackpos;
if (isTable(L, 2)) {
const Position& position = getPosition(L, 2, stackpos);
pushPosition(L, position, stackpos);
} else {
uint16_t x = getNumber<uint16_t>(L, 2, 0);
uint16_t y = getNumber<uint16_t>(L, 3, 0);
uint8_t z = getNumber<uint8_t>(L, 4, 0);
stackpos = getNumber<int32_t>(L, 5, 0);
pushPosition(L, Position(x, y, z), stackpos);
}
return 1;
}
int LuaScriptInterface::luaPositionAdd(lua_State* L)
{
// positionValue = position + positionEx
int32_t stackpos;
const Position& position = getPosition(L, 1, stackpos);
Position positionEx;
if (stackpos == 0) {
positionEx = getPosition(L, 2, stackpos);
} else {
positionEx = getPosition(L, 2);
}
pushPosition(L, position + positionEx, stackpos);
return 1;
}
int LuaScriptInterface::luaPositionSub(lua_State* L)
{
// positionValue = position - positionEx
int32_t stackpos;
const Position& position = getPosition(L, 1, stackpos);
Position positionEx;
if (stackpos == 0) {
positionEx = getPosition(L, 2, stackpos);
} else {
positionEx = getPosition(L, 2);
}
pushPosition(L, position - positionEx, stackpos);
return 1;
}
int LuaScriptInterface::luaPositionCompare(lua_State* L)
{
// position == positionEx
const Position& positionEx = getPosition(L, 2);
const Position& position = getPosition(L, 1);
pushBoolean(L, position == positionEx);
return 1;
}
int LuaScriptInterface::luaPositionGetDistance(lua_State* L)
{
// position:getDistance(positionEx)
const Position& positionEx = getPosition(L, 2);
const Position& position = getPosition(L, 1);
lua_pushnumber(L, std::max<int32_t>(
std::max<int32_t>(
std::abs(Position::getDistanceX(position, positionEx)),
std::abs(Position::getDistanceY(position, positionEx))
),
std::abs(Position::getDistanceZ(position, positionEx))
));
return 1;
}
int LuaScriptInterface::luaPositionIsSightClear(lua_State* L)
{
// position:isSightClear(positionEx[, sameFloor = true])
bool sameFloor = getBoolean(L, 3, true);
const Position& positionEx = getPosition(L, 2);
const Position& position = getPosition(L, 1);
pushBoolean(L, g_game.isSightClear(position, positionEx, sameFloor));
return 1;
}
int LuaScriptInterface::luaPositionSendMagicEffect(lua_State* L)
{
// position:sendMagicEffect(magicEffect[, player = nullptr])
SpectatorVec list;
if (lua_gettop(L) >= 3) {
Player* player = getPlayer(L, 3);
if (player) {
list.insert(player);
}
}
MagicEffectClasses magicEffect = getNumber<MagicEffectClasses>(L, 2);
const Position& position = getPosition(L, 1);
if (!list.empty()) {
Game::addMagicEffect(list, position, magicEffect);
} else {
g_game.addMagicEffect(position, magicEffect);
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPositionSendDistanceEffect(lua_State* L)
{
// position:sendDistanceEffect(positionEx, distanceEffect[, player = nullptr])
SpectatorVec list;
if (lua_gettop(L) >= 4) {
Player* player = getPlayer(L, 4);
if (player) {
list.insert(player);
}
}
ShootType_t distanceEffect = getNumber<ShootType_t>(L, 3);
const Position& positionEx = getPosition(L, 2);
const Position& position = getPosition(L, 1);
if (!list.empty()) {
Game::addDistanceEffect(list, position, positionEx, distanceEffect);
} else {
g_game.addDistanceEffect(position, positionEx, distanceEffect);
}
pushBoolean(L, true);
return 1;
}
// Tile
int LuaScriptInterface::luaTileCreate(lua_State* L)
{
// Tile(x, y, z)
// Tile(position)
Tile* tile;
if (isTable(L, 2)) {
tile = g_game.map.getTile(getPosition(L, 2));
} else {
uint8_t z = getNumber<uint8_t>(L, 4);
uint16_t y = getNumber<uint16_t>(L, 3);
uint16_t x = getNumber<uint16_t>(L, 2);
tile = g_game.map.getTile(x, y, z);
}
if (tile) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetPosition(lua_State* L)
{
// tile:getPosition()
Tile* tile = getUserdata<Tile>(L, 1);
if (tile) {
pushPosition(L, tile->getPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetGround(lua_State* L)
{
// tile:getGround()
Tile* tile = getUserdata<Tile>(L, 1);
if (tile && tile->getGround()) {
pushUserdata<Item>(L, tile->getGround());
setItemMetatable(L, -1, tile->getGround());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetThing(lua_State* L)
{
// tile:getThing(index)
int32_t index = getNumber<int32_t>(L, 2);
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Thing* thing = tile->getThing(index);
if (!thing) {
lua_pushnil(L);
return 1;
}
if (Creature* creature = thing->getCreature()) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else if (Item* item = thing->getItem()) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetThingCount(lua_State* L)
{
// tile:getThingCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (tile) {
lua_pushnumber(L, tile->getThingCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopVisibleThing(lua_State* L)
{
// tile:getTopVisibleThing(creature)
Creature* creature = getCreature(L, 2);
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Thing* thing = tile->getTopVisibleThing(creature);
if (!thing) {
lua_pushnil(L);
return 1;
}
if (Creature* visibleCreature = thing->getCreature()) {
pushUserdata<Creature>(L, visibleCreature);
setCreatureMetatable(L, -1, visibleCreature);
} else if (Item* visibleItem = thing->getItem()) {
pushUserdata<Item>(L, visibleItem);
setItemMetatable(L, -1, visibleItem);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopTopItem(lua_State* L)
{
// tile:getTopTopItem()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Item* item = tile->getTopTopItem();
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopDownItem(lua_State* L)
{
// tile:getTopDownItem()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Item* item = tile->getTopDownItem();
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetFieldItem(lua_State* L)
{
// tile:getFieldItem()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Item* item = tile->getFieldItem();
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetItemById(lua_State* L)
{
// tile:getItemById(itemId[, subType = -1])
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
Item* item = g_game.findItemOfType(tile, itemId, false, subType);
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetItemByType(lua_State* L)
{
// tile:getItemByType(itemType)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
bool found;
ItemTypes_t itemType = getNumber<ItemTypes_t>(L, 2);
switch (itemType) {
case ITEM_TYPE_TELEPORT:
found = tile->hasFlag(TILESTATE_TELEPORT);
break;
case ITEM_TYPE_MAGICFIELD:
found = tile->hasFlag(TILESTATE_MAGICFIELD);
break;
case ITEM_TYPE_MAILBOX:
found = tile->hasFlag(TILESTATE_MAILBOX);
break;
case ITEM_TYPE_TRASHHOLDER:
found = tile->hasFlag(TILESTATE_TRASHHOLDER);
break;
case ITEM_TYPE_BED:
found = tile->hasFlag(TILESTATE_BED);
break;
case ITEM_TYPE_DEPOT:
found = tile->hasFlag(TILESTATE_DEPOT);
break;
default:
found = true;
break;
}
if (!found) {
lua_pushnil(L);
return 1;
}
if (Item* item = tile->getGround()) {
const ItemType& it = Item::items[item->getID()];
if (it.type == itemType) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
return 1;
}
}
if (const TileItemVector* items = tile->getItemList()) {
for (Item* item : *items) {
const ItemType& it = Item::items[item->getID()];
if (it.type == itemType) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
return 1;
}
}
}
lua_pushnil(L);
return 1;
}
int LuaScriptInterface::luaTileGetItemByTopOrder(lua_State* L)
{
// tile:getItemByTopOrder(topOrder)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
int32_t topOrder = getNumber<int32_t>(L, 2);
Item* item = tile->getItemByTopOrder(topOrder);
if (!item) {
lua_pushnil(L);
return 1;
}
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
return 1;
}
int LuaScriptInterface::luaTileGetItemCountById(lua_State* L)
{
// tile:getItemCountById(itemId[, subType = -1])
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
lua_pushnumber(L, tile->getItemTypeCount(itemId, subType));
return 1;
}
int LuaScriptInterface::luaTileGetBottomCreature(lua_State* L)
{
// tile:getBottomCreature()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
const Creature* creature = tile->getBottomCreature();
if (!creature) {
lua_pushnil(L);
return 1;
}
pushUserdata<const Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
return 1;
}
int LuaScriptInterface::luaTileGetTopCreature(lua_State* L)
{
// tile:getTopCreature()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Creature* creature = tile->getTopCreature();
if (!creature) {
lua_pushnil(L);
return 1;
}
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
return 1;
}
int LuaScriptInterface::luaTileGetBottomVisibleCreature(lua_State* L)
{
// tile:getBottomVisibleCreature(creature)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Creature* creature = getCreature(L, 2);
if (!creature) {
lua_pushnil(L);
return 1;
}
const Creature* visibleCreature = tile->getBottomVisibleCreature(creature);
if (visibleCreature) {
pushUserdata<const Creature>(L, visibleCreature);
setCreatureMetatable(L, -1, visibleCreature);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopVisibleCreature(lua_State* L)
{
// tile:getTopVisibleCreature(creature)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Creature* creature = getCreature(L, 2);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* visibleCreature = tile->getTopVisibleCreature(creature);
if (visibleCreature) {
pushUserdata<Creature>(L, visibleCreature);
setCreatureMetatable(L, -1, visibleCreature);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetItems(lua_State* L)
{
// tile:getItems()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
TileItemVector* itemVector = tile->getItemList();
if (!itemVector) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, itemVector->size(), 0);
int index = 0;
for (Item* item : *itemVector) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaTileGetItemCount(lua_State* L)
{
// tile:getItemCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, tile->getItemCount());
return 1;
}
int LuaScriptInterface::luaTileGetDownItemCount(lua_State* L)
{
// tile:getDownItemCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (tile) {
lua_pushnumber(L, tile->getDownItemCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopItemCount(lua_State* L)
{
// tile:getTopItemCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, tile->getTopItemCount());
return 1;
}
int LuaScriptInterface::luaTileGetCreatures(lua_State* L)
{
// tile:getCreatures()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
CreatureVector* creatureVector = tile->getCreatures();
if (!creatureVector) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, creatureVector->size(), 0);
int index = 0;
for (Creature* creature : *creatureVector) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaTileGetCreatureCount(lua_State* L)
{
// tile:getCreatureCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, tile->getCreatureCount());
return 1;
}
int LuaScriptInterface::luaTileHasProperty(lua_State* L)
{
// tile:hasProperty(property[, item])
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Item* item;
if (lua_gettop(L) >= 3) {
item = getUserdata<Item>(L, 3);
} else {
item = nullptr;
}
ITEMPROPERTY property = getNumber<ITEMPROPERTY>(L, 2);
if (item) {
pushBoolean(L, tile->hasProperty(item, property));
} else {
pushBoolean(L, tile->hasProperty(property));
}
return 1;
}
int LuaScriptInterface::luaTileGetThingIndex(lua_State* L)
{
// tile:getThingIndex(thing)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Thing* thing = getThing(L, 2);
if (thing) {
lua_pushnumber(L, tile->getThingIndex(thing));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileHasFlag(lua_State* L)
{
// tile:hasFlag(flag)
Tile* tile = getUserdata<Tile>(L, 1);
if (tile) {
tileflags_t flag = getNumber<tileflags_t>(L, 2);
pushBoolean(L, tile->hasFlag(flag));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileQueryAdd(lua_State* L)
{
// tile:queryAdd(thing[, flags])
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Thing* thing = getThing(L, 2);
if (thing) {
uint32_t flags = getNumber<uint32_t>(L, 3, 0);
lua_pushnumber(L, tile->queryAdd(0, *thing, 1, flags));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetHouse(lua_State* L)
{
// tile:getHouse()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
if (HouseTile* houseTile = dynamic_cast<HouseTile*>(tile)) {
pushUserdata<House>(L, houseTile->getHouse());
setMetatable(L, -1, "House");
} else {
lua_pushnil(L);
}
return 1;
}
// NetworkMessage
int LuaScriptInterface::luaNetworkMessageCreate(lua_State* L)
{
// NetworkMessage()
pushUserdata<NetworkMessage>(L, new NetworkMessage);
setMetatable(L, -1, "NetworkMessage");
return 1;
}
int LuaScriptInterface::luaNetworkMessageDelete(lua_State* L)
{
NetworkMessage** messagePtr = getRawUserdata<NetworkMessage>(L, 1);
if (messagePtr && *messagePtr) {
delete *messagePtr;
*messagePtr = nullptr;
}
return 0;
}
int LuaScriptInterface::luaNetworkMessageGetByte(lua_State* L)
{
// networkMessage:getByte()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
lua_pushnumber(L, message->getByte());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetU16(lua_State* L)
{
// networkMessage:getU16()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
lua_pushnumber(L, message->get<uint16_t>());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetU32(lua_State* L)
{
// networkMessage:getU32()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
lua_pushnumber(L, message->get<uint32_t>());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetU64(lua_State* L)
{
// networkMessage:getU64()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
lua_pushnumber(L, message->get<uint64_t>());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetString(lua_State* L)
{
// networkMessage:getString()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
pushString(L, message->getString());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetPosition(lua_State* L)
{
// networkMessage:getPosition()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
pushPosition(L, message->getPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddByte(lua_State* L)
{
// networkMessage:addByte(number)
uint8_t number = getNumber<uint8_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addByte(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddU16(lua_State* L)
{
// networkMessage:addU16(number)
uint16_t number = getNumber<uint16_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->add<uint16_t>(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddU32(lua_State* L)
{
// networkMessage:addU32(number)
uint32_t number = getNumber<uint32_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->add<uint32_t>(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddU64(lua_State* L)
{
// networkMessage:addU64(number)
uint64_t number = getNumber<uint64_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->add<uint64_t>(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddString(lua_State* L)
{
// networkMessage:addString(string)
const std::string& string = getString(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addString(string);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddPosition(lua_State* L)
{
// networkMessage:addPosition(position)
const Position& position = getPosition(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addPosition(position);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddDouble(lua_State* L)
{
// networkMessage:addDouble(number)
double number = getNumber<double>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addDouble(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddItem(lua_State* L)
{
// networkMessage:addItem(item)
Item* item = getUserdata<Item>(L, 2);
if (!item) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
lua_pushnil(L);
return 1;
}
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addItem(item);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddItemId(lua_State* L)
{
// networkMessage:addItemId(itemId)
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (!message) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
message->addItemId(itemId);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaNetworkMessageReset(lua_State* L)
{
// networkMessage:reset()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->reset();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageSkipBytes(lua_State* L)
{
// networkMessage:skipBytes(number)
int16_t number = getNumber<int16_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->skipBytes(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageSendToPlayer(lua_State* L)
{
// networkMessage:sendToPlayer(player)
Player* player = getPlayer(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (player) {
if (message) {
player->sendNetworkMessage(*message);
}
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
lua_pushnil(L);
}
return 1;
}
// ModalWindow
int LuaScriptInterface::luaModalWindowCreate(lua_State* L)
{
// ModalWindow(id, title, message)
const std::string& message = getString(L, 4);
const std::string& title = getString(L, 3);
uint32_t id = getNumber<uint32_t>(L, 2);
pushUserdata<ModalWindow>(L, new ModalWindow(id, title, message));
setMetatable(L, -1, "ModalWindow");
return 1;
}
int LuaScriptInterface::luaModalWindowDelete(lua_State* L)
{
ModalWindow** windowPtr = getRawUserdata<ModalWindow>(L, 1);
if (windowPtr && *windowPtr) {
delete *windowPtr;
*windowPtr = nullptr;
}
return 0;
}
int LuaScriptInterface::luaModalWindowGetId(lua_State* L)
{
// modalWindow:getId()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->id);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetTitle(lua_State* L)
{
// modalWindow:getTitle()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
pushString(L, window->title);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetMessage(lua_State* L)
{
// modalWindow:getMessage()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
pushString(L, window->message);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetTitle(lua_State* L)
{
// modalWindow:setTitle(text)
const std::string& text = getString(L, 2);
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->title = text;
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetMessage(lua_State* L)
{
// modalWindow:setMessage(text)
const std::string& text = getString(L, 2);
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->message = text;
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetButtonCount(lua_State* L)
{
// modalWindow:getButtonCount()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->buttons.size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetChoiceCount(lua_State* L)
{
// modalWindow:getChoiceCount()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->choices.size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowAddButton(lua_State* L)
{
// modalWindow:addButton(id, text)
const std::string& text = getString(L, 3);
uint8_t id = getNumber<uint8_t>(L, 2);
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->buttons.emplace_back(text, id);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowAddChoice(lua_State* L)
{
// modalWindow:addChoice(id, text)
const std::string& text = getString(L, 3);
uint8_t id = getNumber<uint8_t>(L, 2);
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->choices.emplace_back(text, id);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetDefaultEnterButton(lua_State* L)
{
// modalWindow:getDefaultEnterButton()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->defaultEnterButton);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetDefaultEnterButton(lua_State* L)
{
// modalWindow:setDefaultEnterButton(buttonId)
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->defaultEnterButton = getNumber<uint8_t>(L, 2);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetDefaultEscapeButton(lua_State* L)
{
// modalWindow:getDefaultEscapeButton()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->defaultEscapeButton);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetDefaultEscapeButton(lua_State* L)
{
// modalWindow:setDefaultEscapeButton(buttonId)
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->defaultEscapeButton = getNumber<uint8_t>(L, 2);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowHasPriority(lua_State* L)
{
// modalWindow:hasPriority()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
pushBoolean(L, window->priority);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetPriority(lua_State* L)
{
// modalWindow:setPriority(priority)
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->priority = getBoolean(L, 2);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSendToPlayer(lua_State* L)
{
// modalWindow:sendToPlayer(player)
Player* player = getPlayer(L, 2);
if (!player) {
lua_pushnil(L);
return 1;
}
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
if (!player->hasModalWindowOpen(window->id)) {
player->sendModalWindow(*window);
}
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
// Item
int LuaScriptInterface::luaItemCreate(lua_State* L)
{
// Item(uid)
uint32_t id = getNumber<uint32_t>(L, 2);
Item* item = getScriptEnv()->getItemByUID(id);
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemIsItem(lua_State* L)
{
// item:isItem()
pushBoolean(L, getUserdata<const Item>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaItemGetParent(lua_State* L)
{
// item:getParent()
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
Cylinder* parent = item->getParent();
if (!parent) {
lua_pushnil(L);
return 1;
}
if (Creature* creature = parent->getCreature()) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else if (Item* item = parent->getItem()) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else if (Tile* tile = parent->getTile()) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else if (parent == VirtualCylinder::virtualCylinder) {
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetTopParent(lua_State* L)
{
// item:getTopParent()
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
Cylinder* topParent = item->getTopParent();
if (!topParent) {
lua_pushnil(L);
return 1;
}
if (Creature* creature = topParent->getCreature()) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else if (Item* item = topParent->getItem()) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else if (Tile* tile = topParent->getTile()) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else if (topParent == VirtualCylinder::virtualCylinder) {
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetId(lua_State* L)
{
// item:getId()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getID());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemClone(lua_State* L)
{
// item:clone()
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
Item* clone = item->clone();
if (!clone) {
lua_pushnil(L);
return 1;
}
getScriptEnv()->addTempItem(clone);
clone->setParent(VirtualCylinder::virtualCylinder);
pushUserdata<Item>(L, clone);
setItemMetatable(L, -1, clone);
return 1;
}
int LuaScriptInterface::luaItemSplit(lua_State* L)
{
// item:split([count = 1])
Item** itemPtr = getRawUserdata<Item>(L, 1);
if (!itemPtr) {
lua_pushnil(L);
return 1;
}
Item* item = *itemPtr;
if (!item || !item->isStackable()) {
lua_pushnil(L);
return 1;
}
uint16_t count = std::min<uint16_t>(getNumber<uint16_t>(L, 2, 1), item->getItemCount());
uint16_t diff = item->getItemCount() - count;
Item* splitItem = item->clone();
if (!splitItem) {
lua_pushnil(L);
return 1;
}
ScriptEnvironment* env = getScriptEnv();
uint32_t uid = env->addThing(item);
Item* newItem = g_game.transformItem(item, item->getID(), diff);
if (item->isRemoved()) {
env->removeItemByUID(uid);
}
if (newItem && newItem != item) {
env->insertItem(uid, newItem);
}
*itemPtr = newItem;
splitItem->setParent(VirtualCylinder::virtualCylinder);
env->addTempItem(splitItem);
pushUserdata<Item>(L, splitItem);
setItemMetatable(L, -1, splitItem);
return 1;
}
int LuaScriptInterface::luaItemRemove(lua_State* L)
{
// item:remove([count = -1])
Item* item = getUserdata<Item>(L, 1);
if (item) {
int32_t count = getNumber<int32_t>(L, 2, -1);
pushBoolean(L, g_game.internalRemoveItem(item, count) == RETURNVALUE_NOERROR);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetUniqueId(lua_State* L)
{
// item:getUniqueId()
Item* item = getUserdata<Item>(L, 1);
if (item) {
uint32_t uniqueId = item->getUniqueId();
if (uniqueId == 0) {
uniqueId = getScriptEnv()->addThing(item);
}
lua_pushnumber(L, uniqueId);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetActionId(lua_State* L)
{
// item:getActionId()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getActionId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemSetActionId(lua_State* L)
{
// item:setActionId(actionId)
uint16_t actionId = getNumber<uint16_t>(L, 2);
Item* item = getUserdata<Item>(L, 1);
if (item) {
item->setActionId(actionId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetCount(lua_State* L)
{
// item:getCount()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getItemCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetCharges(lua_State* L)
{
// item:getCharges()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getCharges());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetFluidType(lua_State* L)
{
// item:getFluidType()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getFluidType());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetWeight(lua_State* L)
{
// item:getWeight()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getWeight());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetSubType(lua_State* L)
{
// item:getSubType()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getSubType());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetName(lua_State* L)
{
// item:getName()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushString(L, item->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetPluralName(lua_State* L)
{
// item:getPluralName()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushString(L, item->getPluralName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetArticle(lua_State* L)
{
// item:getArticle()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushString(L, item->getArticle());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetPosition(lua_State* L)
{
// item:getPosition()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushPosition(L, item->getPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetTile(lua_State* L)
{
// item:getTile()
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
Tile* tile = item->getTile();
if (tile) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemHasAttribute(lua_State* L)
{
// item:hasAttribute(key)
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
itemAttrTypes attribute;
if (isNumber(L, 2)) {
attribute = getNumber<itemAttrTypes>(L, 2);
} else if (isString(L, 2)) {
attribute = stringToItemAttribute(getString(L, 2));
} else {
attribute = ITEM_ATTRIBUTE_NONE;
}
pushBoolean(L, item->hasAttribute(attribute));
return 1;
}
int LuaScriptInterface::luaItemGetAttribute(lua_State* L)
{
// item:getAttribute(key)
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
itemAttrTypes attribute;
if (isNumber(L, 2)) {
attribute = getNumber<itemAttrTypes>(L, 2);
} else if (isString(L, 2)) {
attribute = stringToItemAttribute(getString(L, 2));
} else {
attribute = ITEM_ATTRIBUTE_NONE;
}
if (ItemAttributes::isIntAttrType(attribute)) {
lua_pushnumber(L, item->getIntAttr(attribute));
} else if (ItemAttributes::isStrAttrType(attribute)) {
pushString(L, item->getStrAttr(attribute));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemSetAttribute(lua_State* L)
{
// item:setAttribute(key, value)
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
itemAttrTypes attribute;
if (isNumber(L, 2)) {
attribute = getNumber<itemAttrTypes>(L, 2);
} else if (isString(L, 2)) {
attribute = stringToItemAttribute(getString(L, 2));
} else {
attribute = ITEM_ATTRIBUTE_NONE;
}
if (ItemAttributes::isIntAttrType(attribute)) {
if (attribute == ITEM_ATTRIBUTE_UNIQUEID) {
reportErrorFunc("Attempt to set protected key \"uid\"");
pushBoolean(L, false);
return 1;
}
item->setIntAttr(attribute, getNumber<int32_t>(L, 3));
pushBoolean(L, true);
} else if (ItemAttributes::isStrAttrType(attribute)) {
item->setStrAttr(attribute, getString(L, 3));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemRemoveAttribute(lua_State* L)
{
// item:removeAttribute(key)
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
itemAttrTypes attribute;
if (isNumber(L, 2)) {
attribute = getNumber<itemAttrTypes>(L, 2);
} else if (isString(L, 2)) {
attribute = stringToItemAttribute(getString(L, 2));
} else {
attribute = ITEM_ATTRIBUTE_NONE;
}
bool ret = attribute != ITEM_ATTRIBUTE_UNIQUEID;
if (ret) {
item->removeAttribute(attribute);
} else {
reportErrorFunc("Attempt to erase protected key \"uid\"");
}
pushBoolean(L, ret);
return 1;
}
int LuaScriptInterface::luaItemMoveTo(lua_State* L)
{
// item:moveTo(position or cylinder)
Item** itemPtr = getRawUserdata<Item>(L, 1);
if (!itemPtr) {
lua_pushnil(L);
return 1;
}
Item* item = *itemPtr;
if (!item || item->isRemoved()) {
lua_pushnil(L);
return 1;
}
Cylinder* toCylinder;
if (isUserdata(L, 2)) {
const LuaDataType type = getUserdataType(L, 2);
switch (type) {
case LuaData_Container:
toCylinder = getUserdata<Container>(L, 2);
break;
case LuaData_Player:
toCylinder = getUserdata<Player>(L, 2);
break;
case LuaData_Tile:
toCylinder = getUserdata<Tile>(L, 2);
break;
default:
toCylinder = nullptr;
break;
}
} else {
toCylinder = g_game.map.getTile(getPosition(L, 2));
}
if (!toCylinder) {
lua_pushnil(L);
return 1;
}
if (item->getParent() == toCylinder) {
pushBoolean(L, true);
return 1;
}
if (item->getParent() == VirtualCylinder::virtualCylinder) {
pushBoolean(L, g_game.internalAddItem(toCylinder, item) == RETURNVALUE_NOERROR);
} else {
Item* moveItem = nullptr;
ReturnValue ret = g_game.internalMoveItem(item->getParent(), toCylinder, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem, FLAG_NOLIMIT | FLAG_IGNOREBLOCKITEM | FLAG_IGNOREBLOCKCREATURE | FLAG_IGNORENOTMOVEABLE);
if (moveItem) {
*itemPtr = moveItem;
}
pushBoolean(L, ret == RETURNVALUE_NOERROR);
}
return 1;
}
int LuaScriptInterface::luaItemTransform(lua_State* L)
{
// item:transform(itemId[, count/subType = -1])
Item** itemPtr = getRawUserdata<Item>(L, 1);
if (!itemPtr) {
lua_pushnil(L);
return 1;
}
Item*& item = *itemPtr;
if (!item) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
if (item->getID() == itemId && (subType == -1 || subType == item->getSubType())) {
pushBoolean(L, true);
return 1;
}
const ItemType& it = Item::items[itemId];
if (it.stackable) {
subType = std::min<int32_t>(subType, 100);
}
ScriptEnvironment* env = getScriptEnv();
uint32_t uid = env->addThing(item);
Item* newItem = g_game.transformItem(item, itemId, subType);
if (item->isRemoved()) {
env->removeItemByUID(uid);
}
if (newItem && newItem != item) {
env->insertItem(uid, newItem);
}
item = newItem;
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaItemDecay(lua_State* L)
{
// item:decay()
Item* item = getUserdata<Item>(L, 1);
if (item) {
g_game.startDecay(item);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetDescription(lua_State* L)
{
// item:getDescription(distance)
Item* item = getUserdata<Item>(L, 1);
if (item) {
int32_t distance = getNumber<int32_t>(L, 2);
pushString(L, item->getDescription(distance));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemHasProperty(lua_State* L)
{
// item:hasProperty(property)
Item* item = getUserdata<Item>(L, 1);
if (item) {
ITEMPROPERTY property = getNumber<ITEMPROPERTY>(L, 2);
pushBoolean(L, item->hasProperty(property));
} else {
lua_pushnil(L);
}
return 1;
}
// Container
int LuaScriptInterface::luaContainerCreate(lua_State* L)
{
// Container(uid)
uint32_t id = getNumber<uint32_t>(L, 2);
Container* container = getScriptEnv()->getContainerByUID(id);
if (container) {
pushUserdata(L, container);
setMetatable(L, -1, "Container");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerGetSize(lua_State* L)
{
// container:getSize()
Container* container = getUserdata<Container>(L, 1);
if (container) {
lua_pushnumber(L, container->size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerGetCapacity(lua_State* L)
{
// container:getCapacity()
Container* container = getUserdata<Container>(L, 1);
if (container) {
lua_pushnumber(L, container->capacity());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerGetEmptySlots(lua_State* L)
{
// container:getEmptySlots([recursive = false])
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
uint32_t slots = container->capacity() - container->size();
bool recursive = getBoolean(L, 2, false);
if (recursive) {
for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) {
if (Container* tmpContainer = (*it)->getContainer()) {
slots += tmpContainer->capacity() - tmpContainer->size();
}
}
}
lua_pushnumber(L, slots);
return 1;
}
int LuaScriptInterface::luaContainerGetItemHoldingCount(lua_State* L)
{
// container:getItemHoldingCount()
Container* container = getUserdata<Container>(L, 1);
if (container) {
lua_pushnumber(L, container->getItemHoldingCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerGetItem(lua_State* L)
{
// container:getItem(index)
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
uint32_t index = getNumber<uint32_t>(L, 2);
Item* item = container->getItemByIndex(index);
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerHasItem(lua_State* L)
{
// container:hasItem(item)
Item* item = getUserdata<Item>(L, 2);
Container* container = getUserdata<Container>(L, 1);
if (container) {
pushBoolean(L, container->isHoldingItem(item));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerAddItem(lua_State* L)
{
// container:addItem(itemId[, count/subType = 1[, index = INDEX_WHEREEVER[, flags = 0]]])
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
uint32_t subType = getNumber<uint32_t>(L, 3, 1);
Item* item = Item::CreateItem(itemId, std::min<uint32_t>(subType, 100));
if (!item) {
lua_pushnil(L);
return 1;
}
int32_t index = getNumber<int32_t>(L, 4, INDEX_WHEREEVER);
uint32_t flags = getNumber<uint32_t>(L, 5, 0);
ReturnValue ret = g_game.internalAddItem(container, item, index, flags);
if (ret == RETURNVALUE_NOERROR) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
delete item;
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerAddItemEx(lua_State* L)
{
// container:addItemEx(item[, index = INDEX_WHEREEVER[, flags = 0]])
Item* item = getUserdata<Item>(L, 2);
if (!item) {
lua_pushnil(L);
return 1;
}
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
if (item->getParent() != VirtualCylinder::virtualCylinder) {
reportErrorFunc("Item already has a parent");
lua_pushnil(L);
return 1;
}
int32_t index = getNumber<int32_t>(L, 3, INDEX_WHEREEVER);
uint32_t flags = getNumber<uint32_t>(L, 4, 0);
ReturnValue ret = g_game.internalAddItem(container, item, index, flags);
if (ret == RETURNVALUE_NOERROR) {
ScriptEnvironment::removeTempItem(item);
}
lua_pushnumber(L, ret);
return 1;
}
int LuaScriptInterface::luaContainerGetItemCountById(lua_State* L)
{
// container:getItemCountById(itemId[, subType = -1])
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
lua_pushnumber(L, container->getItemTypeCount(itemId, subType));
return 1;
}
// Teleport
int LuaScriptInterface::luaTeleportCreate(lua_State* L)
{
// Teleport(uid)
uint32_t id = getNumber<uint32_t>(L, 2);
Item* item = getScriptEnv()->getItemByUID(id);
if (item && item->getTeleport()) {
pushUserdata(L, item);
setMetatable(L, -1, "Teleport");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTeleportGetDestination(lua_State* L)
{
// teleport:getDestination()
Teleport* teleport = getUserdata<Teleport>(L, 1);
if (teleport) {
pushPosition(L, teleport->getDestPos());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTeleportSetDestination(lua_State* L)
{
// teleport:setDestination(position)
Teleport* teleport = getUserdata<Teleport>(L, 1);
if (teleport) {
teleport->setDestPos(getPosition(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
// Creature
int LuaScriptInterface::luaCreatureCreate(lua_State* L)
{
// Creature(id or name or userdata)
Creature* creature;
if (isNumber(L, 2)) {
creature = g_game.getCreatureByID(getNumber<uint32_t>(L, 2));
} else if (isString(L, 2)) {
creature = g_game.getCreatureByName(getString(L, 2));
} else if (isUserdata(L, 2)) {
LuaDataType type = getUserdataType(L, 2);
if (type != LuaData_Player && type != LuaData_Monster && type != LuaData_Npc) {
lua_pushnil(L);
return 1;
}
creature = getUserdata<Creature>(L, 2);
} else {
creature = nullptr;
}
if (creature) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureRegisterEvent(lua_State* L)
{
// creature:registerEvent(name)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
const std::string& name = getString(L, 2);
pushBoolean(L, creature->registerCreatureEvent(name));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureUnregisterEvent(lua_State* L)
{
// creature:unregisterEvent(name)
const std::string& name = getString(L, 2);
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
pushBoolean(L, creature->unregisterCreatureEvent(name));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureIsRemoved(lua_State* L)
{
// creature:isRemoved()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushBoolean(L, creature->isRemoved());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureIsCreature(lua_State* L)
{
// creature:isCreature()
pushBoolean(L, getUserdata<const Creature>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaCreatureIsInGhostMode(lua_State* L)
{
// creature:isInGhostMode()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushBoolean(L, creature->isInGhostMode());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureIsHealthHidden(lua_State* L)
{
// creature:isHealthHidden()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushBoolean(L, creature->isHealthHidden());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureCanSee(lua_State* L)
{
// creature:canSee(position)
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
const Position& position = getPosition(L, 2);
pushBoolean(L, creature->canSee(position));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureCanSeeCreature(lua_State* L)
{
// creature:canSeeCreature(creature)
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
const Creature* otherCreature = getCreature(L, 2);
pushBoolean(L, creature->canSeeCreature(otherCreature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetParent(lua_State* L)
{
// creature:getParent()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Cylinder* parent = creature->getParent();
if (!parent) {
lua_pushnil(L);
return 1;
}
if (Creature* creature = parent->getCreature()) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else if (Item* item = parent->getItem()) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else if (Tile* tile = parent->getTile()) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetId(lua_State* L)
{
// creature:getId()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getID());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetName(lua_State* L)
{
// creature:getName()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushString(L, creature->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetTarget(lua_State* L)
{
// creature:getTarget()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* target = creature->getAttackedCreature();
if (target) {
pushUserdata<Creature>(L, target);
setCreatureMetatable(L, -1, target);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetTarget(lua_State* L)
{
// creature:setTarget(target)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
Creature* target = getCreature(L, 2);
pushBoolean(L, creature->setAttackedCreature(target));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetFollowCreature(lua_State* L)
{
// creature:getFollowCreature()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* followCreature = creature->getFollowCreature();
if (followCreature) {
pushUserdata<Creature>(L, followCreature);
setCreatureMetatable(L, -1, followCreature);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetFollowCreature(lua_State* L)
{
// creature:setFollowCreature(followedCreature)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
Creature* followCreature = getCreature(L, 2);
pushBoolean(L, creature->setFollowCreature(followCreature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetMaster(lua_State* L)
{
// creature:getMaster()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* master = creature->getMaster();
if (!master) {
lua_pushnil(L);
return 1;
}
pushUserdata<Creature>(L, master);
setCreatureMetatable(L, -1, master);
return 1;
}
int LuaScriptInterface::luaCreatureSetMaster(lua_State* L)
{
// creature:setMaster(master)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* master = getCreature(L, 2);
if (master) {
pushBoolean(L, creature->convinceCreature(master));
} else {
master = creature->getMaster();
if (master) {
master->removeSummon(creature);
creature->incrementReferenceCounter();
creature->setDropLoot(true);
}
pushBoolean(L, true);
}
g_game.updateCreatureType(creature);
return 1;
}
int LuaScriptInterface::luaCreatureGetLight(lua_State* L)
{
// creature:getLight()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
LightInfo light;
creature->getCreatureLight(light);
lua_pushnumber(L, light.level);
lua_pushnumber(L, light.color);
return 2;
}
int LuaScriptInterface::luaCreatureSetLight(lua_State* L)
{
// creature:setLight(color, level)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
LightInfo light;
light.color = getNumber<uint8_t>(L, 2);
light.level = getNumber<uint8_t>(L, 3);
creature->setCreatureLight(light);
g_game.changeLight(creature);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureGetSpeed(lua_State* L)
{
// creature:getSpeed()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getSpeed());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetBaseSpeed(lua_State* L)
{
// creature:getBaseSpeed()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getBaseSpeed());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureChangeSpeed(lua_State* L)
{
// creature:changeSpeed(delta)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
int32_t delta = getNumber<int32_t>(L, 2);
g_game.changeSpeed(creature, delta);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureSetDropLoot(lua_State* L)
{
// creature:setDropLoot(doDrop)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->setDropLoot(getBoolean(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetPosition(lua_State* L)
{
// creature:getPosition()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushPosition(L, creature->getPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetTile(lua_State* L)
{
// creature:getTile()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Tile* tile = creature->getTile();
if (tile) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetDirection(lua_State* L)
{
// creature:getDirection()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getDirection());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetDirection(lua_State* L)
{
// creature:setDirection(direction)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
pushBoolean(L, g_game.internalCreatureTurn(creature, getNumber<Direction>(L, 2)));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetHealth(lua_State* L)
{
// creature:getHealth()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getHealth());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureAddHealth(lua_State* L)
{
// creature:addHealth(healthChange)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
CombatDamage damage;
damage.primary.value = getNumber<int32_t>(L, 2);
if (damage.primary.value >= 0) {
damage.primary.type = COMBAT_HEALING;
} else {
damage.primary.type = COMBAT_UNDEFINEDDAMAGE;
}
pushBoolean(L, g_game.combatChangeHealth(nullptr, creature, damage));
return 1;
}
int LuaScriptInterface::luaCreatureGetMaxHealth(lua_State* L)
{
// creature:getMaxHealth()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getMaxHealth());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetMaxHealth(lua_State* L)
{
// creature:setMaxHealth(maxHealth)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
creature->healthMax = getNumber<uint32_t>(L, 2);
creature->health = std::min<int32_t>(creature->health, creature->healthMax);
g_game.addCreatureHealth(creature);
Player* player = creature->getPlayer();
if (player) {
player->sendStats();
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureSetHiddenHealth(lua_State* L)
{
// creature:setHiddenHealth(hide)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->setHiddenHealth(getBoolean(L, 2));
g_game.addCreatureHealth(creature);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetMana(lua_State* L)
{
// creature:getMana()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getMana());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureAddMana(lua_State* L)
{
// creature:addMana(manaChange[, animationOnLoss = false])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
int32_t manaChange = getNumber<int32_t>(L, 2);
bool animationOnLoss = getBoolean(L, 3, false);
if (!animationOnLoss && manaChange < 0) {
creature->changeMana(manaChange);
} else {
g_game.combatChangeMana(nullptr, creature, manaChange, ORIGIN_NONE);
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureGetMaxMana(lua_State* L)
{
// creature:getMaxMana()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getMaxMana());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetSkull(lua_State* L)
{
// creature:getSkull()
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getSkull());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetSkull(lua_State* L)
{
// creature:setSkull(skull)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->setSkull(getNumber<Skulls_t>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetOutfit(lua_State* L)
{
// creature:getOutfit()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushOutfit(L, creature->getCurrentOutfit());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetOutfit(lua_State* L)
{
// creature:setOutfit(outfit)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->defaultOutfit = getOutfit(L, 2);
g_game.internalCreatureChangeOutfit(creature, creature->defaultOutfit);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetCondition(lua_State* L)
{
// creature:getCondition(conditionType[, conditionId = CONDITIONID_COMBAT[, subId = 0]])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2);
ConditionId_t conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT);
uint32_t subId = getNumber<uint32_t>(L, 4, 0);
Condition* condition = creature->getCondition(conditionType, conditionId, subId);
if (condition) {
pushUserdata<Condition>(L, condition);
setWeakMetatable(L, -1, "Condition");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureAddCondition(lua_State* L)
{
// creature:addCondition(condition[, force = false])
Condition* condition;
if (isNumber(L, 2)) {
condition = g_luaEnvironment.getConditionObject(getNumber<uint32_t>(L, 2));
} else {
condition = getUserdata<Condition>(L, 2);
}
Creature* creature = getUserdata<Creature>(L, 1);
if (creature && condition) {
bool force = getBoolean(L, 3, false);
pushBoolean(L, creature->addCondition(condition->clone(), force));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureRemoveCondition(lua_State* L)
{
// creature:removeCondition(conditionType[, conditionId = CONDITIONID_COMBAT[, subId = 0[, force = false]]])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2);
ConditionId_t conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT);
uint32_t subId = getNumber<uint32_t>(L, 4, 0);
Condition* condition = creature->getCondition(conditionType, conditionId, subId);
if (condition) {
bool force = getBoolean(L, 5, false);
creature->removeCondition(condition, force);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureRemove(lua_State* L)
{
// creature:remove()
Creature** creaturePtr = getRawUserdata<Creature>(L, 1);
if (!creaturePtr) {
lua_pushnil(L);
return 1;
}
Creature* creature = *creaturePtr;
if (!creature) {
lua_pushnil(L);
return 1;
}
Player* player = creature->getPlayer();
if (player) {
player->kickPlayer(true);
} else {
g_game.removeCreature(creature);
}
*creaturePtr = nullptr;
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureTeleportTo(lua_State* L)
{
// creature:teleportTo(position[, pushMovement = false])
bool pushMovement = getBoolean(L, 3, false);
const Position& position = getPosition(L, 2);
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
const Position oldPosition = creature->getPosition();
if (g_game.internalTeleport(creature, position, pushMovement) != RETURNVALUE_NOERROR) {
pushBoolean(L, false);
return 1;
}
if (!pushMovement) {
if (oldPosition.x == position.x) {
if (oldPosition.y < position.y) {
g_game.internalCreatureTurn(creature, DIRECTION_SOUTH);
} else {
g_game.internalCreatureTurn(creature, DIRECTION_NORTH);
}
} else if (oldPosition.x > position.x) {
g_game.internalCreatureTurn(creature, DIRECTION_WEST);
} else if (oldPosition.x < position.x) {
g_game.internalCreatureTurn(creature, DIRECTION_EAST);
}
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureSay(lua_State* L)
{
// creature:say(text, type[, ghost = false[, target = nullptr[, position]]])
int parameters = lua_gettop(L);
Position position;
if (parameters >= 6) {
position = getPosition(L, 6);
if (!position.x || !position.y) {
reportErrorFunc("Invalid position specified.");
pushBoolean(L, false);
return 1;
}
}
Creature* target = nullptr;
if (parameters >= 5) {
target = getCreature(L, 5);
}
bool ghost = getBoolean(L, 4, false);
SpeakClasses type = getNumber<SpeakClasses>(L, 3);
const std::string& text = getString(L, 2);
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
SpectatorVec list;
if (target) {
list.insert(target);
}
if (position.x != 0) {
pushBoolean(L, g_game.internalCreatureSay(creature, type, text, ghost, &list, &position));
} else {
pushBoolean(L, g_game.internalCreatureSay(creature, type, text, ghost, &list));
}
return 1;
}
int LuaScriptInterface::luaCreatureGetDamageMap(lua_State* L)
{
// creature:getDamageMap()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, creature->damageMap.size(), 0);
for (auto damageEntry : creature->damageMap) {
lua_createtable(L, 0, 2);
setField(L, "total", damageEntry.second.total);
setField(L, "ticks", damageEntry.second.ticks);
lua_rawseti(L, -2, damageEntry.first);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetSummons(lua_State* L)
{
// creature:getSummons()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, creature->getSummonCount(), 0);
int index = 0;
for (Creature* summon : creature->getSummons()) {
pushUserdata<Creature>(L, summon);
setCreatureMetatable(L, -1, summon);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetDescription(lua_State* L)
{
// creature:getDescription(distance)
int32_t distance = getNumber<int32_t>(L, 2);
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
pushString(L, creature->getDescription(distance));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetPathTo(lua_State* L)
{
// creature:getPathTo(pos[, minTargetDist = 0[, maxTargetDist = 1[, fullPathSearch = true[, clearSight = true[, maxSearchDist = 0]]]]])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
const Position& position = getPosition(L, 2);
FindPathParams fpp;
fpp.minTargetDist = getNumber<int32_t>(L, 3, 0);
fpp.maxTargetDist = getNumber<int32_t>(L, 4, 1);
fpp.fullPathSearch = getBoolean(L, 5, fpp.fullPathSearch);
fpp.clearSight = getBoolean(L, 6, fpp.clearSight);
fpp.maxSearchDist = getNumber<int32_t>(L, 7, fpp.maxSearchDist);
std::forward_list<Direction> dirList;
if (creature->getPathTo(position, dirList, fpp)) {
lua_newtable(L);
int index = 0;
for (Direction dir : dirList) {
lua_pushnumber(L, dir);
lua_rawseti(L, -2, ++index);
}
} else {
pushBoolean(L, false);
}
return 1;
}
// Player
int LuaScriptInterface::luaPlayerCreate(lua_State* L)
{
// Player(id or name or userdata)
Player* player;
if (isNumber(L, 2)) {
player = g_game.getPlayerByID(getNumber<uint32_t>(L, 2));
} else if (isString(L, 2)) {
ReturnValue ret = g_game.getPlayerByNameWildcard(getString(L, 2), player);
if (ret != RETURNVALUE_NOERROR) {
lua_pushnil(L);
lua_pushnumber(L, ret);
return 2;
}
} else if (isUserdata(L, 2)) {
if (getUserdataType(L, 2) != LuaData_Player) {
lua_pushnil(L);
return 1;
}
player = getUserdata<Player>(L, 2);
} else {
player = nullptr;
}
if (player) {
pushUserdata<Player>(L, player);
setMetatable(L, -1, "Player");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerIsPlayer(lua_State* L)
{
// player:isPlayer()
pushBoolean(L, getUserdata<const Player>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaPlayerGetGuid(lua_State* L)
{
// player:getGuid()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getGUID());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetIp(lua_State* L)
{
// player:getIp()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getIP());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetAccountId(lua_State* L)
{
// player:getAccountId()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getAccount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetLastLoginSaved(lua_State* L)
{
// player:getLastLoginSaved()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getLastLoginSaved());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetLastLogout(lua_State* L)
{
// player:getLastLogout()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getLastLogout());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetAccountType(lua_State* L)
{
// player:getAccountType()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getAccountType());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetAccountType(lua_State* L)
{
// player:setAccountType(accountType)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->accountType = getNumber<AccountType_t>(L, 2);
IOLoginData::setAccountType(player->getAccount(), player->accountType);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetCapacity(lua_State* L)
{
// player:getCapacity()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getCapacity());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetCapacity(lua_State* L)
{
// player:setCapacity(capacity)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->capacity = getNumber<uint32_t>(L, 2);
player->sendStats();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetFreeCapacity(lua_State* L)
{
// player:getFreeCapacity()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getFreeCapacity());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetDepotChest(lua_State* L)
{
// player:getDepotChest(depotId[, autoCreate = false])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint32_t depotId = getNumber<uint32_t>(L, 2);
bool autoCreate = getBoolean(L, 3, false);
DepotChest* depotChest = player->getDepotChest(depotId, autoCreate);
if (depotChest) {
pushUserdata<Item>(L, depotChest);
setItemMetatable(L, -1, depotChest);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetInbox(lua_State* L)
{
// player:getInbox()
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Inbox* inbox = player->getInbox();
if (inbox) {
pushUserdata<Item>(L, inbox);
setItemMetatable(L, -1, inbox);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSkullTime(lua_State* L)
{
// player:getSkullTime()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getSkullTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetSkullTime(lua_State* L)
{
// player:setSkullTime(skullTime)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setSkullTicks(getNumber<int64_t>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetDeathPenalty(lua_State* L)
{
// player:getDeathPenalty()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, static_cast<uint32_t>(player->getLostPercent() * 100));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetExperience(lua_State* L)
{
// player:getExperience()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getExperience());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddExperience(lua_State* L)
{
// player:addExperience(experience[, sendText = false])
Player* player = getUserdata<Player>(L, 1);
if (player) {
int64_t experience = getNumber<int64_t>(L, 2);
bool sendText = getBoolean(L, 3, false);
player->addExperience(nullptr, experience, sendText);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveExperience(lua_State* L)
{
// player:removeExperience(experience[, sendText = false])
Player* player = getUserdata<Player>(L, 1);
if (player) {
int64_t experience = getNumber<int64_t>(L, 2);
bool sendText = getBoolean(L, 3, false);
player->removeExperience(experience, sendText);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetLevel(lua_State* L)
{
// player:getLevel()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getLevel());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetMagicLevel(lua_State* L)
{
// player:getMagicLevel()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getMagicLevel());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetBaseMagicLevel(lua_State* L)
{
// player:getBaseMagicLevel()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getBaseMagicLevel());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetMaxMana(lua_State* L)
{
// player:setMaxMana(maxMana)
Player* player = getPlayer(L, 1);
if (player) {
player->manaMax = getNumber<int32_t>(L, 2);
player->mana = std::min<int32_t>(player->mana, player->manaMax);
player->sendStats();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetManaSpent(lua_State* L)
{
// player:getManaSpent()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getSpentMana());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddManaSpent(lua_State* L)
{
// player:addManaSpent(amount)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->addManaSpent(getNumber<uint64_t>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSkillLevel(lua_State* L)
{
// player:getSkillLevel(skillType)
skills_t skillType = getNumber<skills_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player && skillType <= SKILL_LAST) {
lua_pushnumber(L, player->skills[skillType].level);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetEffectiveSkillLevel(lua_State* L)
{
// player:getEffectiveSkillLevel(skillType)
skills_t skillType = getNumber<skills_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player && skillType <= SKILL_LAST) {
lua_pushnumber(L, player->getSkillLevel(skillType));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSkillPercent(lua_State* L)
{
// player:getSkillPercent(skillType)
skills_t skillType = getNumber<skills_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player && skillType <= SKILL_LAST) {
lua_pushnumber(L, player->skills[skillType].percent);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSkillTries(lua_State* L)
{
// player:getSkillTries(skillType)
skills_t skillType = getNumber<skills_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player && skillType <= SKILL_LAST) {
lua_pushnumber(L, player->skills[skillType].tries);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddSkillTries(lua_State* L)
{
// player:addSkillTries(skillType, tries)
Player* player = getUserdata<Player>(L, 1);
if (player) {
skills_t skillType = getNumber<skills_t>(L, 2);
uint64_t tries = getNumber<uint64_t>(L, 3);
player->addSkillAdvance(skillType, tries);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetItemCount(lua_State* L)
{
// player:getItemCount(itemId[, subType = -1])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
lua_pushnumber(L, player->getItemTypeCount(itemId, subType));
return 1;
}
int LuaScriptInterface::luaPlayerGetItemById(lua_State* L)
{
// player:getItemById(itemId, deepSearch[, subType = -1])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
bool deepSearch = getBoolean(L, 3);
int32_t subType = getNumber<int32_t>(L, 4, -1);
Item* item = g_game.findItemOfType(player, itemId, deepSearch, subType);
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetVocation(lua_State* L)
{
// player:getVocation()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushUserdata<Vocation>(L, player->getVocation());
setMetatable(L, -1, "Vocation");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetVocation(lua_State* L)
{
// player:setVocation(id or name or userdata)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Vocation* vocation;
if (isNumber(L, 2)) {
vocation = g_vocations.getVocation(getNumber<uint16_t>(L, 2));
} else if (isString(L, 2)) {
vocation = g_vocations.getVocation(g_vocations.getVocationId(getString(L, 2)));
} else if (isUserdata(L, 2)) {
vocation = getUserdata<Vocation>(L, 2);
} else {
vocation = nullptr;
}
if (!vocation) {
pushBoolean(L, false);
return 1;
}
player->setVocation(vocation->getId());
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerGetSex(lua_State* L)
{
// player:getSex()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getSex());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetSex(lua_State* L)
{
// player:setSex(newSex)
Player* player = getUserdata<Player>(L, 1);
if (player) {
PlayerSex_t newSex = getNumber<PlayerSex_t>(L, 2);
player->setSex(newSex);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetTown(lua_State* L)
{
// player:getTown()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushUserdata<Town>(L, player->getTown());
setMetatable(L, -1, "Town");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetTown(lua_State* L)
{
// player:setTown(town)
Town* town = getUserdata<Town>(L, 2);
if (!town) {
pushBoolean(L, false);
return 1;
}
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setTown(town);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetGuild(lua_State* L)
{
// player:getGuild()
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Guild* guild = player->getGuild();
if (!guild) {
lua_pushnil(L);
return 1;
}
pushUserdata<Guild>(L, guild);
setMetatable(L, -1, "Guild");
return 1;
}
int LuaScriptInterface::luaPlayerSetGuild(lua_State* L)
{
// player:setGuild(guild)
Guild* guild = getUserdata<Guild>(L, 2);
if (!guild) {
pushBoolean(L, false);
return 1;
}
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setGuild(guild);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetGuildLevel(lua_State* L)
{
// player:getGuildLevel()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getGuildLevel());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetGuildLevel(lua_State* L)
{
// player:setGuildLevel(level)
uint8_t level = getNumber<uint8_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setGuildLevel(level);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetGuildNick(lua_State* L)
{
// player:getGuildNick()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushString(L, player->getGuildNick());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetGuildNick(lua_State* L)
{
// player:setGuildNick(nick)
const std::string& nick = getString(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setGuildNick(nick);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetGroup(lua_State* L)
{
// player:getGroup()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushUserdata<Group>(L, player->getGroup());
setMetatable(L, -1, "Group");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetGroup(lua_State* L)
{
// player:setGroup(group)
Group* group = getUserdata<Group>(L, 2);
if (!group) {
pushBoolean(L, false);
return 1;
}
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setGroup(group);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetStamina(lua_State* L)
{
// player:getStamina()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getStaminaMinutes());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetStamina(lua_State* L)
{
// player:setStamina(stamina)
uint16_t stamina = getNumber<uint16_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->staminaMinutes = std::min<uint16_t>(2520, stamina);
player->sendStats();
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSoul(lua_State* L)
{
// player:getSoul()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getSoul());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddSoul(lua_State* L)
{
// player:addSoul(soulChange)
int32_t soulChange = getNumber<int32_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->changeSoul(soulChange);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetMaxSoul(lua_State* L)
{
// player:getMaxSoul()
Player* player = getUserdata<Player>(L, 1);
if (player && player->vocation) {
lua_pushnumber(L, player->vocation->getSoulMax());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetBankBalance(lua_State* L)
{
// player:getBankBalance()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getBankBalance());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetBankBalance(lua_State* L)
{
// player:setBankBalance(bankBalance)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setBankBalance(getNumber<uint64_t>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetStorageValue(lua_State* L)
{
// player:getStorageValue(key)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint32_t key = getNumber<uint32_t>(L, 2);
int32_t value;
if (player->getStorageValue(key, value)) {
lua_pushnumber(L, value);
} else {
lua_pushnumber(L, -1);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetStorageValue(lua_State* L)
{
// player:setStorageValue(key, value)
int32_t value = getNumber<int32_t>(L, 3);
uint32_t key = getNumber<uint32_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (IS_IN_KEYRANGE(key, RESERVED_RANGE)) {
std::ostringstream ss;
ss << "Accessing reserved range: " << key;
reportErrorFunc(ss.str());
pushBoolean(L, false);
return 1;
}
if (player) {
player->addStorageValue(key, value);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddItem(lua_State* L)
{
// player:addItem(itemId[, count = 1[, canDropOnMap = true[, subType = 1[, slot = CONST_SLOT_WHEREEVER]]]])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
pushBoolean(L, false);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t count = getNumber<int32_t>(L, 3, 1);
int32_t subType = getNumber<int32_t>(L, 5, 1);
const ItemType& it = Item::items[itemId];
int32_t itemCount = 1;
int parameters = lua_gettop(L);
if (parameters >= 4) {
itemCount = std::max<int32_t>(1, count);
} else if (it.hasSubType()) {
if (it.stackable) {
itemCount = std::ceil(count / 100.f);
}
subType = count;
} else {
itemCount = std::max<int32_t>(1, count);
}
bool hasTable = itemCount > 1;
if (hasTable) {
lua_newtable(L);
} else if (itemCount == 0) {
lua_pushnil(L);
return 1;
}
bool canDropOnMap = getBoolean(L, 4, true);
slots_t slot = getNumber<slots_t>(L, 6, CONST_SLOT_WHEREEVER);
for (int32_t i = 1; i <= itemCount; ++i) {
int32_t stackCount = subType;
if (it.stackable) {
stackCount = std::min<int32_t>(stackCount, 100);
subType -= stackCount;
}
Item* item = Item::CreateItem(itemId, stackCount);
if (!item) {
if (!hasTable) {
lua_pushnil(L);
}
return 1;
}
ReturnValue ret = g_game.internalPlayerAddItem(player, item, canDropOnMap, slot);
if (ret != RETURNVALUE_NOERROR) {
delete item;
if (!hasTable) {
lua_pushnil(L);
}
return 1;
}
if (hasTable) {
lua_pushnumber(L, i);
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
lua_settable(L, -3);
} else {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
}
}
return 1;
}
int LuaScriptInterface::luaPlayerAddItemEx(lua_State* L)
{
// player:addItemEx(item[, canDropOnMap = false[, index = INDEX_WHEREEVER[, flags = 0]]])
// player:addItemEx(item[, canDropOnMap = true[, slot = CONST_SLOT_WHEREEVER]])
Item* item = getUserdata<Item>(L, 2);
if (!item) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
if (item->getParent() != VirtualCylinder::virtualCylinder) {
reportErrorFunc("Item already has a parent");
pushBoolean(L, false);
return 1;
}
bool canDropOnMap = getBoolean(L, 3, false);
ReturnValue returnValue;
if (canDropOnMap) {
slots_t slot = getNumber<slots_t>(L, 4, CONST_SLOT_WHEREEVER);
returnValue = g_game.internalPlayerAddItem(player, item, true, slot);
} else {
int32_t index = getNumber<int32_t>(L, 4, INDEX_WHEREEVER);
uint32_t flags = getNumber<uint32_t>(L, 5, 0);
returnValue = g_game.internalAddItem(player, item, index, flags);
}
if (returnValue == RETURNVALUE_NOERROR) {
ScriptEnvironment::removeTempItem(item);
}
lua_pushnumber(L, returnValue);
return 1;
}
int LuaScriptInterface::luaPlayerRemoveItem(lua_State* L)
{
// player:removeItem(itemId, count[, subType = -1[, ignoreEquipped = false]])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
uint32_t count = getNumber<uint32_t>(L, 3);
int32_t subType = getNumber<int32_t>(L, 4, -1);
bool ignoreEquipped = getBoolean(L, 5, false);
pushBoolean(L, player->removeItemOfType(itemId, count, subType, ignoreEquipped));
return 1;
}
int LuaScriptInterface::luaPlayerGetMoney(lua_State* L)
{
// player:getMoney()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getMoney());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddMoney(lua_State* L)
{
// player:addMoney(money)
uint64_t money = getNumber<uint64_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
g_game.addMoney(player, money);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveMoney(lua_State* L)
{
// player:removeMoney(money)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint64_t money = getNumber<uint64_t>(L, 2);
pushBoolean(L, g_game.removeMoney(player, money));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerShowTextDialog(lua_State* L)
{
// player:showTextDialog(itemId[, text[, canWrite[, length]]])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
int32_t length = getNumber<int32_t>(L, 5, -1);
bool canWrite = getBoolean(L, 4, false);
std::string text;
int parameters = lua_gettop(L);
if (parameters >= 3) {
text = getString(L, 3);
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
Item* item = Item::CreateItem(itemId);
if (!item) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (length < 0) {
length = Item::items[item->getID()].maxTextLen;
}
if (!text.empty()) {
item->setText(text);
length = std::max<int32_t>(text.size(), length);
}
item->setParent(player);
player->setWriteItem(item, length);
player->sendTextWindow(item, length, canWrite);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerSendTextMessage(lua_State* L)
{
// player:sendTextMessage(type, text[, position, primaryValue = 0, primaryColor = TEXTCOLOR_NONE[, secondaryValue = 0, secondaryColor = TEXTCOLOR_NONE]])
int parameters = lua_gettop(L);
TextMessage message(getNumber<MessageClasses>(L, 2), getString(L, 3));
if (parameters >= 6) {
message.position = getPosition(L, 4);
message.primary.value = getNumber<int32_t>(L, 5);
message.primary.color = getNumber<TextColor_t>(L, 6);
}
if (parameters >= 8) {
message.secondary.value = getNumber<int32_t>(L, 7);
message.secondary.color = getNumber<TextColor_t>(L, 8);
}
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->sendTextMessage(message);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSendChannelMessage(lua_State* L)
{
// player:sendChannelMessage(author, text, type, channelId)
uint16_t channelId = getNumber<uint16_t>(L, 5);
SpeakClasses type = getNumber<SpeakClasses>(L, 4);
const std::string& text = getString(L, 3);
const std::string& author = getString(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->sendChannelMessage(author, text, type, channelId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSendPrivateMessage(lua_State* L)
{
// player:sendPrivateMessage(speaker, text[, type])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
const Player* speaker = getUserdata<const Player>(L, 2);
const std::string& text = getString(L, 3);
SpeakClasses type = getNumber<SpeakClasses>(L, 4, TALKTYPE_PRIVATE_FROM);
player->sendPrivateMessage(speaker, type, text);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerChannelSay(lua_State* L)
{
// player:channelSay(speaker, type, text, channelId)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Creature* speaker = getCreature(L, 2);
SpeakClasses type = getNumber<SpeakClasses>(L, 3);
const std::string& text = getString(L, 4);
uint16_t channelId = getNumber<uint16_t>(L, 5);
player->sendToChannel(speaker, type, text, channelId);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerOpenChannel(lua_State* L)
{
// player:openChannel(channelId)
uint16_t channelId = getNumber<uint16_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
g_game.playerOpenChannel(player->getID(), channelId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSlotItem(lua_State* L)
{
// player:getSlotItem(slot)
const Player* player = getUserdata<const Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint32_t slot = getNumber<uint32_t>(L, 2);
Thing* thing = player->getThing(slot);
if (!thing) {
lua_pushnil(L);
return 1;
}
Item* item = thing->getItem();
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetParty(lua_State* L)
{
// player:getParty()
const Player* player = getUserdata<const Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Party* party = player->getParty();
if (party) {
pushUserdata<Party>(L, party);
setMetatable(L, -1, "Party");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddOutfit(lua_State* L)
{
// player:addOutfit(lookType)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->addOutfit(getNumber<uint16_t>(L, 2), 0);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddOutfitAddon(lua_State* L)
{
// player:addOutfitAddon(lookType, addon)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint16_t lookType = getNumber<uint16_t>(L, 2);
uint8_t addon = getNumber<uint8_t>(L, 3);
player->addOutfit(lookType, addon);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveOutfit(lua_State* L)
{
// player:removeOutfit(lookType)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint16_t lookType = getNumber<uint16_t>(L, 2);
pushBoolean(L, player->removeOutfit(lookType));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveOutfitAddon(lua_State* L)
{
// player:removeOutfitAddon(lookType, addon)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint16_t lookType = getNumber<uint16_t>(L, 2);
uint8_t addon = getNumber<uint8_t>(L, 3);
pushBoolean(L, player->removeOutfitAddon(lookType, addon));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerHasOutfit(lua_State* L)
{
// player:hasOutfit(lookType[, addon = 0])
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint16_t lookType = getNumber<uint16_t>(L, 2);
uint8_t addon = getNumber<uint8_t>(L, 3, 0);
pushBoolean(L, player->canWear(lookType, addon));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSendOutfitWindow(lua_State* L)
{
// player:sendOutfitWindow()
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->sendOutfitWindow();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddMount(lua_State* L)
{
// player:addMount(mountId)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint8_t mountId = getNumber<uint8_t>(L, 2);
pushBoolean(L, player->tameMount(mountId));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveMount(lua_State* L)
{
// player:removeMount(mountId)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint8_t mountId = getNumber<uint8_t>(L, 2);
pushBoolean(L, player->untameMount(mountId));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerHasMount(lua_State* L)
{
// player:hasMount(mountId)
const Player* player = getUserdata<const Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint8_t mountId = getNumber<uint8_t>(L, 2);
Mount* mount = g_game.mounts.getMountByID(mountId);
if (mount) {
pushBoolean(L, player->hasMount(mount));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetPremiumDays(lua_State* L)
{
// player:getPremiumDays()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->premiumDays);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddPremiumDays(lua_State* L)
{
// player:addPremiumDays(days)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
if (player->premiumDays != std::numeric_limits<uint16_t>::max()) {
uint16_t days = getNumber<uint16_t>(L, 2);
int32_t addDays = std::min<int32_t>(0xFFFE - player->premiumDays, days);
if (addDays > 0) {
player->setPremiumDays(player->premiumDays + addDays);
IOLoginData::addPremiumDays(player->getAccount(), addDays);
}
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerRemovePremiumDays(lua_State* L)
{
// player:removePremiumDays(days)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
if (player->premiumDays != std::numeric_limits<uint16_t>::max()) {
uint16_t days = getNumber<uint16_t>(L, 2);
int32_t removeDays = std::min<int32_t>(player->premiumDays, days);
if (removeDays > 0) {
player->setPremiumDays(player->premiumDays - removeDays);
IOLoginData::removePremiumDays(player->getAccount(), removeDays);
}
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerHasBlessing(lua_State* L)
{
// player:hasBlessing(blessing)
uint8_t blessing = getNumber<uint8_t>(L, 2) - 1;
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushBoolean(L, player->hasBlessing(blessing));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddBlessing(lua_State* L)
{
// player:addBlessing(blessing)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint8_t blessing = getNumber<uint8_t>(L, 2) - 1;
if (player->hasBlessing(blessing)) {
pushBoolean(L, false);
return 1;
}
player->addBlessing(1 << blessing);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerRemoveBlessing(lua_State* L)
{
// player:removeBlessing(blessing)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint8_t blessing = getNumber<uint8_t>(L, 2) - 1;
if (!player->hasBlessing(blessing)) {
pushBoolean(L, false);
return 1;
}
player->removeBlessing(1 << blessing);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerCanLearnSpell(lua_State* L)
{
// player:canLearnSpell(spellName)
const Player* player = getUserdata<const Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
const std::string& spellName = getString(L, 2);
InstantSpell* spell = g_spells->getInstantSpellByName(spellName);
if (!spell) {
reportErrorFunc("Spell \"" + spellName + "\" not found");
pushBoolean(L, false);
return 1;
}
if (player->hasFlag(PlayerFlag_IgnoreSpellCheck)) {
pushBoolean(L, true);
return 1;
}
const auto& vocMap = spell->getVocMap();
if (vocMap.count(player->getVocationId()) == 0) {
pushBoolean(L, false);
} else if (player->getLevel() < spell->getLevel()) {
pushBoolean(L, false);
} else if (player->getMagicLevel() < spell->getMagicLevel()) {
pushBoolean(L, false);
} else {
pushBoolean(L, true);
}
return 1;
}
int LuaScriptInterface::luaPlayerLearnSpell(lua_State* L)
{
// player:learnSpell(spellName)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const std::string& spellName = getString(L, 2);
player->learnInstantSpell(spellName);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerForgetSpell(lua_State* L)
{
// player:forgetSpell(spellName)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const std::string& spellName = getString(L, 2);
player->forgetInstantSpell(spellName);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerHasLearnedSpell(lua_State* L)
{
// player:hasLearnedSpell(spellName)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const std::string& spellName = getString(L, 2);
pushBoolean(L, player->hasLearnedInstantSpell(spellName));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSendTutorial(lua_State* L)
{
// player:sendTutorial(tutorialId)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint8_t tutorialId = getNumber<uint8_t>(L, 2);
player->sendTutorial(tutorialId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddMapMark(lua_State* L)
{
// player:addMapMark(position, type, description)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const Position& position = getPosition(L, 2);
uint8_t type = getNumber<uint8_t>(L, 3);
const std::string& description = getString(L, 4);
player->sendAddMarker(position, type, description);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSave(lua_State* L)
{
// player:save()
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->loginPosition = player->getPosition();
pushBoolean(L, IOLoginData::savePlayer(player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerPopupFYI(lua_State* L)
{
// player:popupFYI(message)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const std::string& message = getString(L, 2);
player->sendFYIBox(message);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerIsPzLocked(lua_State* L)
{
// player:isPzLocked()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushBoolean(L, player->isPzLocked());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetClient(lua_State* L)
{
// player:getClient()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_createtable(L, 0, 2);
setField(L, "version", player->getProtocolVersion());
setField(L, "os", player->getOperatingSystem());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetHouse(lua_State* L)
{
// player:getHouse()
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
House* house = g_game.map.houses.getHouseByPlayerId(player->getGUID());
if (house) {
pushUserdata<House>(L, house);
setMetatable(L, -1, "House");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetGhostMode(lua_State* L)
{
// player:setGhostMode(enabled)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
bool enabled = getBoolean(L, 2);
if (player->isInGhostMode() == enabled) {
pushBoolean(L, true);
return 1;
}
player->switchGhostMode();
Tile* tile = player->getTile();
const Position& position = player->getPosition();
SpectatorVec list;
g_game.map.getSpectators(list, position, true, true);
for (Creature* spectator : list) {
Player* tmpPlayer = spectator->getPlayer();
if (tmpPlayer != player && !tmpPlayer->isAccessPlayer()) {
if (enabled) {
tmpPlayer->sendRemoveTileThing(position, tile->getStackposOfCreature(tmpPlayer, player));
} else {
tmpPlayer->sendCreatureAppear(player, position, true);
}
} else {
tmpPlayer->sendCreatureChangeVisible(player, !enabled);
}
}
if (player->isInGhostMode()) {
for (const auto& it : g_game.getPlayers()) {
if (!it.second->isAccessPlayer()) {
it.second->notifyStatusChange(player, VIPSTATUS_OFFLINE);
}
}
IOLoginData::updateOnlineStatus(player->getGUID(), false);
} else {
for (const auto& it : g_game.getPlayers()) {
if (!it.second->isAccessPlayer()) {
it.second->notifyStatusChange(player, VIPSTATUS_ONLINE);
}
}
IOLoginData::updateOnlineStatus(player->getGUID(), true);
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerGetContainerId(lua_State* L)
{
// player:getContainerId(container)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Container* container = getUserdata<Container>(L, 2);
if (container) {
lua_pushnumber(L, player->getContainerID(container));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetContainerById(lua_State* L)
{
// player:getContainerById(id)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Container* container = player->getContainerByID(getNumber<uint8_t>(L, 2));
if (container) {
pushUserdata<Container>(L, container);
setMetatable(L, -1, "Container");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetContainerIndex(lua_State* L)
{
// player:getContainerIndex(id)
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getContainerIndex(getNumber<uint8_t>(L, 2)));
} else {
lua_pushnil(L);
}
return 1;
}
// Monster
int LuaScriptInterface::luaMonsterCreate(lua_State* L)
{
// Monster(id or userdata)
Monster* monster;
if (isNumber(L, 2)) {
monster = g_game.getMonsterByID(getNumber<uint32_t>(L, 2));
} else if (isUserdata(L, 2)) {
if (getUserdataType(L, 2) != LuaData_Monster) {
lua_pushnil(L);
return 1;
}
monster = getUserdata<Monster>(L, 2);
} else {
monster = nullptr;
}
if (monster) {
pushUserdata<Monster>(L, monster);
setMetatable(L, -1, "Monster");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsMonster(lua_State* L)
{
// monster:isMonster()
pushBoolean(L, getUserdata<const Monster>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaMonsterGetType(lua_State* L)
{
// monster:getType()
const Monster* monster = getUserdata<const Monster>(L, 1);
if (monster) {
pushUserdata<MonsterType>(L, monster->mType);
setMetatable(L, -1, "MonsterType");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterGetSpawnPosition(lua_State* L)
{
// monster:getSpawnPosition()
const Monster* monster = getUserdata<const Monster>(L, 1);
if (monster) {
pushPosition(L, monster->getMasterPos());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsInSpawnRange(lua_State* L)
{
// monster:isInSpawnRange([position])
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
pushBoolean(L, monster->isInSpawnRange(lua_gettop(L) >= 2 ? getPosition(L, 2) : monster->getPosition()));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsIdle(lua_State* L)
{
// monster:isIdle()
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
pushBoolean(L, monster->getIdleStatus());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterSetIdle(lua_State* L)
{
// monster:setIdle(idle)
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
monster->setIdle(getBoolean(L, 2));
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaMonsterIsTarget(lua_State* L)
{
// monster:isTarget(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
const Creature* creature = getCreature(L, 2);
pushBoolean(L, monster->isTarget(creature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsOpponent(lua_State* L)
{
// monster:isOpponent(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
const Creature* creature = getCreature(L, 2);
pushBoolean(L, monster->isOpponent(creature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsFriend(lua_State* L)
{
// monster:isFriend(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
const Creature* creature = getCreature(L, 2);
pushBoolean(L, monster->isFriend(creature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterAddFriend(lua_State* L)
{
// monster:addFriend(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
Creature* creature = getCreature(L, 2);
monster->addFriend(creature);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterRemoveFriend(lua_State* L)
{
// monster:removeFriend(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
Creature* creature = getCreature(L, 2);
monster->removeFriend(creature);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterGetFriendList(lua_State* L)
{
// monster:getFriendList()
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
const auto& friendList = monster->getFriendList();
lua_createtable(L, friendList.size(), 0);
int index = 0;
for (Creature* creature : friendList) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterGetFriendCount(lua_State* L)
{
// monster:getFriendCount()
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
lua_pushnumber(L, monster->getFriendList().size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterAddTarget(lua_State* L)
{
// monster:addTarget(creature[, pushFront = false])
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
Creature* creature = getCreature(L, 2);
bool pushFront = getBoolean(L, 3, false);
monster->addTarget(creature, pushFront);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaMonsterRemoveTarget(lua_State* L)
{
// monster:removeTarget(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
monster->removeTarget(getCreature(L, 2));
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaMonsterGetTargetList(lua_State* L)
{
// monster:getTargetList()
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
const auto& targetList = monster->getTargetList();
lua_createtable(L, targetList.size(), 0);
int index = 0;
for (Creature* creature : targetList) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterGetTargetCount(lua_State* L)
{
// monster:getTargetCount()
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
lua_pushnumber(L, monster->getTargetList().size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterSelectTarget(lua_State* L)
{
// monster:selectTarget(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
Creature* creature = getCreature(L, 2);
pushBoolean(L, monster->selectTarget(creature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterSearchTarget(lua_State* L)
{
// monster:searchTarget([searchType = TARGETSEARCH_DEFAULT])
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
TargetSearchType_t searchType = getNumber<TargetSearchType_t>(L, 2, TARGETSEARCH_DEFAULT);
pushBoolean(L, monster->searchTarget(searchType));
} else {
lua_pushnil(L);
}
return 1;
}
// Npc
int LuaScriptInterface::luaNpcCreate(lua_State* L)
{
// Npc([id or name or userdata])
Npc* npc;
if (lua_gettop(L) >= 2) {
if (isNumber(L, 2)) {
npc = g_game.getNpcByID(getNumber<uint32_t>(L, 2));
} else if (isString(L, 2)) {
npc = g_game.getNpcByName(getString(L, 2));
} else if (isUserdata(L, 2)) {
if (getUserdataType(L, 2) != LuaData_Npc) {
lua_pushnil(L);
return 1;
}
npc = getUserdata<Npc>(L, 2);
} else {
npc = nullptr;
}
} else {
npc = getScriptEnv()->getNpc();
}
if (npc) {
pushUserdata<Npc>(L, npc);
setMetatable(L, -1, "Npc");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNpcIsNpc(lua_State* L)
{
// npc:isNpc()
pushBoolean(L, getUserdata<const Npc>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaNpcSetMasterPos(lua_State* L)
{
// npc:setMasterPos(pos[, radius])
Npc* npc = getUserdata<Npc>(L, 1);
if (!npc) {
lua_pushnil(L);
return 1;
}
const Position& pos = getPosition(L, 2);
int32_t radius = getNumber<int32_t>(L, 3, 1);
npc->setMasterPos(pos, radius);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaNpcGetSpeechBubble(lua_State* L)
{
// npc:getSpeechBubble()
Npc* npc = getUserdata<Npc>(L, 1);
if (npc) {
lua_pushnumber(L, npc->getSpeechBubble());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNpcSetSpeechBubble(lua_State* L)
{
// npc:setSpeechBubble(speechBubble)
Npc* npc = getUserdata<Npc>(L, 1);
if (npc) {
npc->setSpeechBubble(getNumber<uint8_t>(L, 2));
}
return 0;
}
// Guild
int LuaScriptInterface::luaGuildCreate(lua_State* L)
{
// Guild(id)
uint32_t id = getNumber<uint32_t>(L, 2);
Guild* guild = g_game.getGuild(id);
if (guild) {
pushUserdata<Guild>(L, guild);
setMetatable(L, -1, "Guild");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetId(lua_State* L)
{
// guild:getId()
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
lua_pushnumber(L, guild->getId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetName(lua_State* L)
{
// guild:getName()
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
pushString(L, guild->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetMembersOnline(lua_State* L)
{
// guild:getMembersOnline()
const Guild* guild = getUserdata<const Guild>(L, 1);
if (!guild) {
lua_pushnil(L);
return 1;
}
const auto& members = guild->getMembersOnline();
lua_createtable(L, members.size(), 0);
int index = 0;
for (Player* player : members) {
pushUserdata<Player>(L, player);
setMetatable(L, -1, "Player");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGuildAddMember(lua_State* L)
{
// guild:addMember(player)
Guild* guild = getUserdata<Guild>(L, 1);
if (!guild) {
lua_pushnil(L);
return 1;
}
Player* player = getPlayer(L, 2);
if (player) {
guild->addMember(player);
pushBoolean(L, true);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaGuildRemoveMember(lua_State* L)
{
// guild:removeMember(player)
Guild* guild = getUserdata<Guild>(L, 1);
if (!guild) {
lua_pushnil(L);
return 1;
}
Player* player = getPlayer(L, 2);
if (player) {
guild->removeMember(player);
pushBoolean(L, true);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaGuildAddRank(lua_State* L)
{
// guild:addRank(id, name, level)
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
uint32_t id = getNumber<uint32_t>(L, 2);
const std::string& name = getString(L, 3);
uint8_t level = getNumber<uint8_t>(L, 4);
guild->addRank(id, name, level);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetRankById(lua_State* L)
{
// guild:getRankById(id)
Guild* guild = getUserdata<Guild>(L, 1);
if (!guild) {
lua_pushnil(L);
return 1;
}
uint32_t id = getNumber<uint32_t>(L, 2);
GuildRank* rank = guild->getRankById(id);
if (rank) {
lua_createtable(L, 0, 3);
setField(L, "id", rank->id);
setField(L, "name", rank->name);
setField(L, "level", rank->level);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetRankByLevel(lua_State* L)
{
// guild:getRankByLevel(level)
const Guild* guild = getUserdata<const Guild>(L, 1);
if (!guild) {
lua_pushnil(L);
return 1;
}
uint8_t level = getNumber<uint8_t>(L, 2);
const GuildRank* rank = guild->getRankByLevel(level);
if (rank) {
lua_createtable(L, 0, 3);
setField(L, "id", rank->id);
setField(L, "name", rank->name);
setField(L, "level", rank->level);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetMotd(lua_State* L)
{
// guild:getMotd()
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
pushString(L, guild->getMotd());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildSetMotd(lua_State* L)
{
// guild:setMotd(motd)
const std::string& motd = getString(L, 2);
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
guild->setMotd(motd);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
// Group
int LuaScriptInterface::luaGroupCreate(lua_State* L)
{
// Group(id)
uint32_t id = getNumber<uint32_t>(L, 2);
Group* group = g_game.groups.getGroup(id);
if (group) {
pushUserdata<Group>(L, group);
setMetatable(L, -1, "Group");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetId(lua_State* L)
{
// group:getId()
Group* group = getUserdata<Group>(L, 1);
if (group) {
lua_pushnumber(L, group->id);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetName(lua_State* L)
{
// group:getName()
Group* group = getUserdata<Group>(L, 1);
if (group) {
pushString(L, group->name);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetFlags(lua_State* L)
{
// group:getFlags()
Group* group = getUserdata<Group>(L, 1);
if (group) {
lua_pushnumber(L, group->flags);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetAccess(lua_State* L)
{
// group:getAccess()
Group* group = getUserdata<Group>(L, 1);
if (group) {
pushBoolean(L, group->access);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetMaxDepotItems(lua_State* L)
{
// group:getMaxDepotItems()
Group* group = getUserdata<Group>(L, 1);
if (group) {
lua_pushnumber(L, group->maxDepotItems);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetMaxVipEntries(lua_State* L)
{
// group:getMaxVipEntries()
Group* group = getUserdata<Group>(L, 1);
if (group) {
lua_pushnumber(L, group->maxVipEntries);
} else {
lua_pushnil(L);
}
return 1;
}
// Vocation
int LuaScriptInterface::luaVocationCreate(lua_State* L)
{
// Vocation(id or name)
uint32_t id;
if (isNumber(L, 2)) {
id = getNumber<uint32_t>(L, 2);
} else {
id = g_vocations.getVocationId(getString(L, 2));
}
Vocation* vocation = g_vocations.getVocation(id);
if (vocation) {
pushUserdata<Vocation>(L, vocation);
setMetatable(L, -1, "Vocation");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetId(lua_State* L)
{
// vocation:getId()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetClientId(lua_State* L)
{
// vocation:getClientId()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getClientId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetName(lua_State* L)
{
// vocation:getName()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
pushString(L, vocation->getVocName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetDescription(lua_State* L)
{
// vocation:getDescription()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
pushString(L, vocation->getVocDescription());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetRequiredSkillTries(lua_State* L)
{
// vocation:getRequiredSkillTries(skillType, skillLevel)
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
skills_t skillType = getNumber<skills_t>(L, 2);
uint16_t skillLevel = getNumber<uint16_t>(L, 3);
lua_pushnumber(L, vocation->getReqSkillTries(skillType, skillLevel));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetRequiredManaSpent(lua_State* L)
{
// vocation:getRequiredManaSpent(magicLevel)
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
uint32_t magicLevel = getNumber<uint32_t>(L, 2);
lua_pushnumber(L, vocation->getReqMana(magicLevel));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetCapacityGain(lua_State* L)
{
// vocation:getCapacityGain()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getCapGain());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetHealthGain(lua_State* L)
{
// vocation:getHealthGain()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getHPGain());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetHealthGainTicks(lua_State* L)
{
// vocation:getHealthGainTicks()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getHealthGainTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetHealthGainAmount(lua_State* L)
{
// vocation:getHealthGainAmount()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getHealthGainAmount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetManaGain(lua_State* L)
{
// vocation:getManaGain()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getManaGain());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetManaGainTicks(lua_State* L)
{
// vocation:getManaGainTicks()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getManaGainTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetManaGainAmount(lua_State* L)
{
// vocation:getManaGainAmount()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getManaGainAmount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetMaxSoul(lua_State* L)
{
// vocation:getMaxSoul()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getSoulMax());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetSoulGainTicks(lua_State* L)
{
// vocation:getSoulGainTicks()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getSoulGainTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetAttackSpeed(lua_State* L)
{
// vocation:getAttackSpeed()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getAttackSpeed());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetBaseSpeed(lua_State* L)
{
// vocation:getBaseSpeed()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getBaseSpeed());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetDemotion(lua_State* L)
{
// vocation:getDemotion()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (!vocation) {
lua_pushnil(L);
return 1;
}
uint16_t fromId = vocation->getFromVocation();
if (fromId == VOCATION_NONE) {
lua_pushnil(L);
return 1;
}
Vocation* demotedVocation = g_vocations.getVocation(fromId);
if (demotedVocation && demotedVocation != vocation) {
pushUserdata<Vocation>(L, demotedVocation);
setMetatable(L, -1, "Vocation");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetPromotion(lua_State* L)
{
// vocation:getPromotion()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (!vocation) {
lua_pushnil(L);
return 1;
}
uint16_t promotedId = g_vocations.getPromotedVocation(vocation->getId());
if (promotedId == VOCATION_NONE) {
lua_pushnil(L);
return 1;
}
Vocation* promotedVocation = g_vocations.getVocation(promotedId);
if (promotedVocation && promotedVocation != vocation) {
pushUserdata<Vocation>(L, promotedVocation);
setMetatable(L, -1, "Vocation");
} else {
lua_pushnil(L);
}
return 1;
}
// Town
int LuaScriptInterface::luaTownCreate(lua_State* L)
{
// Town(id or name)
Town* town;
if (isNumber(L, 2)) {
town = g_game.map.towns.getTown(getNumber<uint32_t>(L, 2));
} else if (isString(L, 2)) {
town = g_game.map.towns.getTown(getString(L, 2));
} else {
town = nullptr;
}
if (town) {
pushUserdata<Town>(L, town);
setMetatable(L, -1, "Town");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTownGetId(lua_State* L)
{
// town:getId()
Town* town = getUserdata<Town>(L, 1);
if (town) {
lua_pushnumber(L, town->getID());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTownGetName(lua_State* L)
{
// town:getName()
Town* town = getUserdata<Town>(L, 1);
if (town) {
pushString(L, town->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTownGetTemplePosition(lua_State* L)
{
// town:getTemplePosition()
Town* town = getUserdata<Town>(L, 1);
if (town) {
pushPosition(L, town->getTemplePosition());
} else {
lua_pushnil(L);
}
return 1;
}
// House
int LuaScriptInterface::luaHouseCreate(lua_State* L)
{
// House(id)
House* house = g_game.map.houses.getHouse(getNumber<uint32_t>(L, 2));
if (house) {
pushUserdata<House>(L, house);
setMetatable(L, -1, "House");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetId(lua_State* L)
{
// house:getId()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetName(lua_State* L)
{
// house:getName()
House* house = getUserdata<House>(L, 1);
if (house) {
pushString(L, house->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetTown(lua_State* L)
{
// house:getTown()
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
Town* town = g_game.map.towns.getTown(house->getTownId());
if (town) {
pushUserdata<Town>(L, town);
setMetatable(L, -1, "Town");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetExitPosition(lua_State* L)
{
// house:getExitPosition()
House* house = getUserdata<House>(L, 1);
if (house) {
pushPosition(L, house->getEntryPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetRent(lua_State* L)
{
// house:getRent()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getRent());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetOwnerGuid(lua_State* L)
{
// house:getOwnerGuid()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getOwner());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseSetOwnerGuid(lua_State* L)
{
// house:setOwnerGuid(guid[, updateDatabase = true])
House* house = getUserdata<House>(L, 1);
if (house) {
uint32_t guid = getNumber<uint32_t>(L, 2);
bool updateDatabase = getBoolean(L, 3, true);
house->setOwner(guid, updateDatabase);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetBeds(lua_State* L)
{
// house:getBeds()
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
const auto& beds = house->getBeds();
lua_createtable(L, beds.size(), 0);
int index = 0;
for (BedItem* bedItem : beds) {
pushUserdata<Item>(L, bedItem);
setItemMetatable(L, -1, bedItem);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaHouseGetBedCount(lua_State* L)
{
// house:getBedCount()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getBedCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetDoors(lua_State* L)
{
// house:getDoors()
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
const auto& doors = house->getDoors();
lua_createtable(L, doors.size(), 0);
int index = 0;
for (Door* door : doors) {
pushUserdata<Item>(L, door);
setItemMetatable(L, -1, door);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaHouseGetDoorCount(lua_State* L)
{
// house:getDoorCount()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getDoors().size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetTiles(lua_State* L)
{
// house:getTiles()
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
const auto& tiles = house->getTiles();
lua_createtable(L, tiles.size(), 0);
int index = 0;
for (Tile* tile : tiles) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaHouseGetTileCount(lua_State* L)
{
// house:getTileCount()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getTiles().size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetAccessList(lua_State* L)
{
// house:getAccessList(listId)
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
std::string list;
uint32_t listId = getNumber<uint32_t>(L, 2);
if (house->getAccessList(listId, list)) {
pushString(L, list);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaHouseSetAccessList(lua_State* L)
{
// house:setAccessList(listId, list)
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
uint32_t listId = getNumber<uint32_t>(L, 2);
const std::string& list = getString(L, 3);
house->setAccessList(listId, list);
pushBoolean(L, true);
return 1;
}
// ItemType
int LuaScriptInterface::luaItemTypeCreate(lua_State* L)
{
// ItemType(id or name)
uint32_t id;
if (isNumber(L, 2)) {
id = getNumber<uint32_t>(L, 2);
} else {
id = Item::items.getItemIdByName(getString(L, 2));
}
const ItemType& itemType = Item::items[id];
pushUserdata<const ItemType>(L, &itemType);
setMetatable(L, -1, "ItemType");
return 1;
}
int LuaScriptInterface::luaItemTypeIsCorpse(lua_State* L)
{
// itemType:isCorpse()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->corpseType != RACE_NONE);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsDoor(lua_State* L)
{
// itemType:isDoor()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isDoor());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsContainer(lua_State* L)
{
// itemType:isContainer()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isContainer());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsFluidContainer(lua_State* L)
{
// itemType:isFluidContainer()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isFluidContainer());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsMovable(lua_State* L)
{
// itemType:isMovable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->moveable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsRune(lua_State* L)
{
// itemType:isRune()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isRune());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsStackable(lua_State* L)
{
// itemType:isStackable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->stackable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsReadable(lua_State* L)
{
// itemType:isReadable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->canReadText);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsWritable(lua_State* L)
{
// itemType:isWritable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->canWriteText);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetType(lua_State* L)
{
// itemType:getType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->type);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetId(lua_State* L)
{
// itemType:getId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->id);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetClientId(lua_State* L)
{
// itemType:getClientId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->clientId);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetName(lua_State* L)
{
// itemType:getName()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushString(L, itemType->name);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetPluralName(lua_State* L)
{
// itemType:getPluralName()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushString(L, itemType->getPluralName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetArticle(lua_State* L)
{
// itemType:getArticle()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushString(L, itemType->article);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetDescription(lua_State* L)
{
// itemType:getDescription()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushString(L, itemType->description);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetSlotPosition(lua_State *L)
{
// itemType:getSlotPosition()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->slotPosition);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetCharges(lua_State* L)
{
// itemType:getCharges()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->charges);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetFluidSource(lua_State* L)
{
// itemType:getFluidSource()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->fluidSource);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetCapacity(lua_State* L)
{
// itemType:getCapacity()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->maxItems);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetWeight(lua_State* L)
{
// itemType:getWeight([count = 1])
uint16_t count = getNumber<uint16_t>(L, 2, 1);
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (!itemType) {
lua_pushnil(L);
return 1;
}
uint64_t weight = static_cast<uint64_t>(itemType->weight) * std::max<int32_t>(1, count);
lua_pushnumber(L, weight);
return 1;
}
int LuaScriptInterface::luaItemTypeGetHitChance(lua_State* L)
{
// itemType:getHitChance()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->hitChance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetShootRange(lua_State* L)
{
// itemType:getShootRange()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->shootRange);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetAttack(lua_State* L)
{
// itemType:getAttack()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->attack);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetDefense(lua_State* L)
{
// itemType:getDefense()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->defense);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetExtraDefense(lua_State* L)
{
// itemType:getExtraDefense()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->extraDefense);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetArmor(lua_State* L)
{
// itemType:getArmor()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->armor);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetWeaponType(lua_State* L)
{
// itemType:getWeaponType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->weaponType);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetElementType(lua_State* L)
{
// itemType:getElementType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (!itemType) {
lua_pushnil(L);
return 1;
}
auto& abilities = itemType->abilities;
if (abilities) {
lua_pushnumber(L, abilities->elementType);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetElementDamage(lua_State* L)
{
// itemType:getElementDamage()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (!itemType) {
lua_pushnil(L);
return 1;
}
auto& abilities = itemType->abilities;
if (abilities) {
lua_pushnumber(L, abilities->elementDamage);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetTransformEquipId(lua_State* L)
{
// itemType:getTransformEquipId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->transformEquipTo);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetTransformDeEquipId(lua_State* L)
{
// itemType:getTransformDeEquipId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->transformDeEquipTo);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetDestroyId(lua_State* L)
{
// itemType:getDestroyId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->destroyTo);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetDecayId(lua_State* L)
{
// itemType:getDecayId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->decayTo);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetRequiredLevel(lua_State* L)
{
// itemType:getRequiredLevel()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->minReqLevel);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeHasSubType(lua_State* L)
{
// itemType:hasSubType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->hasSubType());
} else {
lua_pushnil(L);
}
return 1;
}
// Combat
int LuaScriptInterface::luaCombatCreate(lua_State* L)
{
// Combat()
uint32_t id = g_luaEnvironment.createCombatObject(getScriptEnv()->getScriptInterface());
pushUserdata<Combat>(L, g_luaEnvironment.getCombatObject(id));
setMetatable(L, -1, "Combat");
return 1;
}
int LuaScriptInterface::luaCombatSetParameter(lua_State* L)
{
// combat:setParameter(key, value)
uint32_t value = getNumber<uint32_t>(L, 3);
CombatParam_t key = getNumber<CombatParam_t>(L, 2);
Combat* combat = getUserdata<Combat>(L, 1);
if (combat) {
pushBoolean(L, combat->setParam(key, value));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCombatSetFormula(lua_State* L)
{
// combat:setFormula(type, mina, minb, maxa, maxb)
Combat* combat = getUserdata<Combat>(L, 1);
if (!combat) {
lua_pushnil(L);
return 1;
}
formulaType_t type = getNumber<formulaType_t>(L, 2);
double mina = getNumber<double>(L, 3);
double minb = getNumber<double>(L, 4);
double maxa = getNumber<double>(L, 5);
double maxb = getNumber<double>(L, 6);
combat->setPlayerCombatValues(type, mina, minb, maxa, maxb);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCombatSetArea(lua_State* L)
{
// combat:setArea(area)
if (getScriptEnv()->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
lua_pushnil(L);
return 1;
}
const AreaCombat* area = g_luaEnvironment.getAreaObject(getNumber<uint32_t>(L, 2));
if (!area) {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
lua_pushnil(L);
return 1;
}
Combat* combat = getUserdata<Combat>(L, 1);
if (combat) {
combat->setArea(new AreaCombat(*area));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCombatSetCondition(lua_State* L)
{
// combat:setCondition(condition)
Condition* condition = getUserdata<Condition>(L, 2);
Combat* combat = getUserdata<Combat>(L, 1);
if (combat && condition) {
combat->setCondition(condition->clone());
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCombatSetCallback(lua_State* L)
{
// combat:setCallback(key, function)
Combat* combat = getUserdata<Combat>(L, 1);
if (!combat) {
lua_pushnil(L);
return 1;
}
CallBackParam_t key = getNumber<CallBackParam_t>(L, 2);
if (!combat->setCallback(key)) {
lua_pushnil(L);
return 1;
}
CallBack* callback = combat->getCallback(key);
if (!callback) {
lua_pushnil(L);
return 1;
}
const std::string& function = getString(L, 3);
pushBoolean(L, callback->loadCallBack(getScriptEnv()->getScriptInterface(), function));
return 1;
}
int LuaScriptInterface::luaCombatSetOrigin(lua_State* L)
{
// combat:setOrigin(origin)
Combat* combat = getUserdata<Combat>(L, 1);
if (combat) {
combat->setOrigin(getNumber<CombatOrigin>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCombatExecute(lua_State* L)
{
// combat:execute(creature, variant)
Combat* combat = getUserdata<Combat>(L, 1);
if (!combat) {
pushBoolean(L, false);
return 1;
}
Creature* creature = getCreature(L, 2);
const LuaVariant& variant = getVariant(L, 3);
switch (variant.type) {
case VARIANT_NUMBER: {
Creature* target = g_game.getCreatureByID(variant.number);
if (!target) {
pushBoolean(L, false);
return 1;
}
if (combat->hasArea()) {
combat->doCombat(creature, target->getPosition());
} else {
combat->doCombat(creature, target);
}
break;
}
case VARIANT_POSITION: {
combat->doCombat(creature, variant.pos);
break;
}
case VARIANT_TARGETPOSITION: {
if (combat->hasArea()) {
combat->doCombat(creature, variant.pos);
} else {
combat->postCombatEffects(creature, variant.pos);
g_game.addMagicEffect(variant.pos, CONST_ME_POFF);
}
break;
}
case VARIANT_STRING: {
Player* target = g_game.getPlayerByName(variant.text);
if (!target) {
pushBoolean(L, false);
return 1;
}
combat->doCombat(creature, target);
break;
}
case VARIANT_NONE: {
reportErrorFunc(getErrorDesc(LUA_ERROR_VARIANT_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
default: {
break;
}
}
pushBoolean(L, true);
return 1;
}
// Condition
int LuaScriptInterface::luaConditionCreate(lua_State* L)
{
// Condition(conditionType[, conditionId = CONDITIONID_COMBAT])
ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2);
ConditionId_t conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT);
uint32_t id;
if (g_luaEnvironment.createConditionObject(conditionType, conditionId, id)) {
pushUserdata<Condition>(L, g_luaEnvironment.getConditionObject(id));
setMetatable(L, -1, "Condition");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionDelete(lua_State* L)
{
// condition:delete()
Condition** conditionPtr = getRawUserdata<Condition>(L, 1);
if (conditionPtr && *conditionPtr) {
delete *conditionPtr;
*conditionPtr = nullptr;
}
return 0;
}
int LuaScriptInterface::luaConditionGetId(lua_State* L)
{
// condition:getId()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetSubId(lua_State* L)
{
// condition:getSubId()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getSubId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetType(lua_State* L)
{
// condition:getType()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getType());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetIcons(lua_State* L)
{
// condition:getIcons()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getIcons());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetEndTime(lua_State* L)
{
// condition:getEndTime()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getEndTime());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionClone(lua_State* L)
{
// condition:clone()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
pushUserdata<Condition>(L, condition->clone());
setMetatable(L, -1, "Condition");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetTicks(lua_State* L)
{
// condition:getTicks()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionSetTicks(lua_State* L)
{
// condition:setTicks(ticks)
int32_t ticks = getNumber<int32_t>(L, 2);
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
condition->setTicks(ticks);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionSetParameter(lua_State* L)
{
// condition:setParameter(key, value)
Condition* condition = getUserdata<Condition>(L, 1);
if (!condition) {
lua_pushnil(L);
return 1;
}
ConditionParam_t key = getNumber<ConditionParam_t>(L, 2);
int32_t value;
if (isBoolean(L, 3)) {
value = getBoolean(L, 3) ? 1 : 0;
} else {
value = getNumber<int32_t>(L, 3);
}
condition->setParam(key, value);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaConditionSetFormula(lua_State* L)
{
// condition:setFormula(mina, minb, maxa, maxb)
double maxb = getNumber<double>(L, 5);
double maxa = getNumber<double>(L, 4);
double minb = getNumber<double>(L, 3);
double mina = getNumber<double>(L, 2);
ConditionSpeed* condition = dynamic_cast<ConditionSpeed*>(getUserdata<Condition>(L, 1));
if (condition) {
condition->setFormulaVars(mina, minb, maxa, maxb);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionSetOutfit(lua_State* L)
{
// condition:setOutfit(outfit)
// condition:setOutfit(lookTypeEx, lookType, lookHead, lookBody, lookLegs, lookFeet[, lookAddons[, lookMount]])
Outfit_t outfit;
if (isTable(L, 2)) {
outfit = getOutfit(L, 2);
} else {
outfit.lookMount = getNumber<uint16_t>(L, 9, outfit.lookMount);
outfit.lookAddons = getNumber<uint8_t>(L, 8, outfit.lookAddons);
outfit.lookFeet = getNumber<uint8_t>(L, 7);
outfit.lookLegs = getNumber<uint8_t>(L, 6);
outfit.lookBody = getNumber<uint8_t>(L, 5);
outfit.lookHead = getNumber<uint8_t>(L, 4);
outfit.lookType = getNumber<uint16_t>(L, 3);
outfit.lookTypeEx = getNumber<uint16_t>(L, 2);
}
ConditionOutfit* condition = dynamic_cast<ConditionOutfit*>(getUserdata<Condition>(L, 1));
if (condition) {
condition->setOutfit(outfit);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionAddDamage(lua_State* L)
{
// condition:addDamage(rounds, time, value)
int32_t value = getNumber<int32_t>(L, 4);
int32_t time = getNumber<int32_t>(L, 3);
int32_t rounds = getNumber<int32_t>(L, 2);
ConditionDamage* condition = dynamic_cast<ConditionDamage*>(getUserdata<Condition>(L, 1));
if (condition) {
pushBoolean(L, condition->addDamage(rounds, time, value));
} else {
lua_pushnil(L);
}
return 1;
}
// MonsterType
int LuaScriptInterface::luaMonsterTypeCreate(lua_State* L)
{
// MonsterType(name)
MonsterType* monsterType = g_monsters.getMonsterType(getString(L, 2));
if (monsterType) {
pushUserdata<MonsterType>(L, monsterType);
setMetatable(L, -1, "MonsterType");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsAttackable(lua_State* L)
{
// monsterType:isAttackable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->isAttackable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsConvinceable(lua_State* L)
{
// monsterType:isConvinceable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->isConvinceable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsSummonable(lua_State* L)
{
// monsterType:isSummonable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->isSummonable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsIllusionable(lua_State* L)
{
// monsterType:isIllusionable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->isIllusionable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsHostile(lua_State* L)
{
// monsterType:isHostile()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->isHostile);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsPushable(lua_State* L)
{
// monsterType:isPushable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->pushable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsHealthShown(lua_State* L)
{
// monsterType:isHealthShown()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, !monsterType->hiddenHealth);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeCanPushItems(lua_State* L)
{
// monsterType:canPushItems()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->canPushItems);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeCanPushCreatures(lua_State* L)
{
// monsterType:canPushCreatures()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->canPushCreatures);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetName(lua_State* L)
{
// monsterType:getName()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushString(L, monsterType->name);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetNameDescription(lua_State* L)
{
// monsterType:getNameDescription()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushString(L, monsterType->nameDescription);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetHealth(lua_State* L)
{
// monsterType:getHealth()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->health);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetMaxHealth(lua_State* L)
{
// monsterType:getMaxHealth()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->healthMax);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetRunHealth(lua_State* L)
{
// monsterType:getRunHealth()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->runAwayHealth);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetExperience(lua_State* L)
{
// monsterType:getExperience()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->experience);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetCombatImmunities(lua_State* L)
{
// monsterType:getCombatImmunities()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->damageImmunities);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetConditionImmunities(lua_State* L)
{
// monsterType:getConditionImmunities()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->conditionImmunities);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetAttackList(lua_State* L)
{
// monsterType:getAttackList()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, monsterType->attackSpells.size(), 0);
int index = 0;
for (const auto& spellBlock : monsterType->attackSpells) {
lua_createtable(L, 0, 8);
setField(L, "chance", spellBlock.chance);
setField(L, "isCombatSpell", spellBlock.combatSpell ? 1 : 0);
setField(L, "isMelee", spellBlock.isMelee ? 1 : 0);
setField(L, "minCombatValue", spellBlock.minCombatValue);
setField(L, "maxCombatValue", spellBlock.maxCombatValue);
setField(L, "range", spellBlock.range);
setField(L, "speed", spellBlock.speed);
pushUserdata<CombatSpell>(L, static_cast<CombatSpell*>(spellBlock.spell));
lua_setfield(L, -2, "spell");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetDefenseList(lua_State* L)
{
// monsterType:getDefenseList()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, monsterType->defenseSpells.size(), 0);
int index = 0;
for (const auto& spellBlock : monsterType->defenseSpells) {
lua_createtable(L, 0, 8);
setField(L, "chance", spellBlock.chance);
setField(L, "isCombatSpell", spellBlock.combatSpell ? 1 : 0);
setField(L, "isMelee", spellBlock.isMelee ? 1 : 0);
setField(L, "minCombatValue", spellBlock.minCombatValue);
setField(L, "maxCombatValue", spellBlock.maxCombatValue);
setField(L, "range", spellBlock.range);
setField(L, "speed", spellBlock.speed);
pushUserdata<CombatSpell>(L, static_cast<CombatSpell*>(spellBlock.spell));
lua_setfield(L, -2, "spell");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetElementList(lua_State* L)
{
// monsterType:getElementList()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, monsterType->elementMap.size(), 0);
for (const auto& elementEntry : monsterType->elementMap) {
lua_pushnumber(L, elementEntry.second);
lua_rawseti(L, -2, elementEntry.first);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetVoices(lua_State* L)
{
// monsterType:getVoices()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
int index = 0;
lua_createtable(L, monsterType->voiceVector.size(), 0);
for (const auto& voiceBlock : monsterType->voiceVector) {
lua_createtable(L, 0, 2);
setField(L, "text", voiceBlock.text);
setField(L, "yellText", voiceBlock.yellText);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetLoot(lua_State* L)
{
// monsterType:getLoot()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
static const std::function<void(const std::vector<LootBlock>&)> parseLoot = [&](const std::vector<LootBlock>& lootList) {
lua_createtable(L, lootList.size(), 0);
int index = 0;
for (const auto& lootBlock : lootList) {
lua_createtable(L, 0, 7);
setField(L, "itemId", lootBlock.id);
setField(L, "chance", lootBlock.chance);
setField(L, "subType", lootBlock.subType);
setField(L, "maxCount", lootBlock.countmax);
setField(L, "actionId", lootBlock.actionId);
setField(L, "text", lootBlock.text);
parseLoot(lootBlock.childLoot);
lua_setfield(L, -2, "childLoot");
lua_rawseti(L, -2, ++index);
}
};
parseLoot(monsterType->lootItems);
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetCreatureEvents(lua_State* L)
{
// monsterType:getCreatureEvents()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
int index = 0;
lua_createtable(L, monsterType->scripts.size(), 0);
for (const std::string& creatureEvent : monsterType->scripts) {
pushString(L, creatureEvent);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetSummonList(lua_State* L)
{
// monsterType:getSummonList()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
int index = 0;
lua_createtable(L, monsterType->summons.size(), 0);
for (const auto& summonBlock : monsterType->summons) {
lua_createtable(L, 0, 3);
setField(L, "name", summonBlock.name);
setField(L, "speed", summonBlock.speed);
setField(L, "chance", summonBlock.chance);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetMaxSummons(lua_State* L)
{
// monsterType:getMaxSummons()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->maxSummons);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetArmor(lua_State* L)
{
// monsterType:getArmor()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->armor);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetDefense(lua_State* L)
{
// monsterType:getDefense()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->defense);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetOutfit(lua_State* L)
{
// monsterType:getOutfit()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushOutfit(L, monsterType->outfit);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetRace(lua_State* L)
{
// monsterType:getRace()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->race);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetCorpseId(lua_State* L)
{
// monsterType:getCorpseId()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->lookcorpse);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetManaCost(lua_State* L)
{
// monsterType:getManaCost()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->manaCost);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetBaseSpeed(lua_State* L)
{
// monsterType:getBaseSpeed()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->baseSpeed);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetLight(lua_State* L)
{
// monsterType:getLight()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, monsterType->lightLevel);
lua_pushnumber(L, monsterType->lightColor);
return 2;
}
int LuaScriptInterface::luaMonsterTypeGetStaticAttackChance(lua_State* L)
{
// monsterType:getStaticAttackChance()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->staticAttackChance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetTargetDistance(lua_State* L)
{
// monsterType:getTargetDistance()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->targetDistance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetYellChance(lua_State* L)
{
// monsterType:getYellChance()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->yellChance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetYellSpeedTicks(lua_State* L)
{
// monsterType:getYellSpeedTicks()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->yellSpeedTicks);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetChangeTargetChance(lua_State* L)
{
// monsterType:getChangeTargetChance()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->changeTargetChance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetChangeTargetSpeed(lua_State* L)
{
// monsterType:getChangeTargetSpeed()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->changeTargetSpeed);
} else {
lua_pushnil(L);
}
return 1;
}
// Party
int LuaScriptInterface::luaPartyDisband(lua_State* L)
{
// party:disband()
Party** partyPtr = getRawUserdata<Party>(L, 1);
if (partyPtr && *partyPtr) {
Party*& party = *partyPtr;
party->disband();
party = nullptr;
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyGetLeader(lua_State* L)
{
// party:getLeader()
Party* party = getUserdata<Party>(L, 1);
if (!party) {
lua_pushnil(L);
return 1;
}
Player* leader = party->getLeader();
if (leader) {
pushUserdata<Player>(L, leader);
setMetatable(L, -1, "Player");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartySetLeader(lua_State* L)
{
// party:setLeader(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->passPartyLeadership(player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyGetMembers(lua_State* L)
{
// party:getMembers()
Party* party = getUserdata<Party>(L, 1);
if (!party) {
lua_pushnil(L);
return 1;
}
int index = 0;
lua_createtable(L, party->getMemberCount(), 0);
for (Player* player : party->getMembers()) {
pushUserdata<Player>(L, player);
setMetatable(L, -1, "Player");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaPartyGetMemberCount(lua_State* L)
{
// party:getMemberCount()
Party* party = getUserdata<Party>(L, 1);
if (party) {
lua_pushnumber(L, party->getMemberCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyGetInvitees(lua_State* L)
{
// party:getInvitees()
Party* party = getUserdata<Party>(L, 1);
if (party) {
lua_createtable(L, party->getInvitationCount(), 0);
int index = 0;
for (Player* player : party->getInvitees()) {
pushUserdata<Player>(L, player);
setMetatable(L, -1, "Player");
lua_rawseti(L, -2, ++index);
}
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyGetInviteeCount(lua_State* L)
{
// party:getInviteeCount()
Party* party = getUserdata<Party>(L, 1);
if (party) {
lua_pushnumber(L, party->getInvitationCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyAddInvite(lua_State* L)
{
// party:addInvite(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->invitePlayer(*player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyRemoveInvite(lua_State* L)
{
// party:removeInvite(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->removeInvite(*player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyAddMember(lua_State* L)
{
// party:addMember(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->joinParty(*player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyRemoveMember(lua_State* L)
{
// party:removeMember(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->leaveParty(player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyIsSharedExperienceActive(lua_State* L)
{
// party:isSharedExperienceActive()
Party* party = getUserdata<Party>(L, 1);
if (party) {
pushBoolean(L, party->isSharedExperienceActive());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyIsSharedExperienceEnabled(lua_State* L)
{
// party:isSharedExperienceEnabled()
Party* party = getUserdata<Party>(L, 1);
if (party) {
pushBoolean(L, party->isSharedExperienceEnabled());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyShareExperience(lua_State* L)
{
// party:shareExperience(experience)
uint64_t experience = getNumber<uint64_t>(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party) {
party->shareExperience(experience);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartySetSharedExperience(lua_State* L)
{
// party:setSharedExperience(active)
bool active = getBoolean(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party) {
pushBoolean(L, party->setSharedExperience(party->getLeader(), active));
} else {
lua_pushnil(L);
}
return 1;
}
//
LuaEnvironment::LuaEnvironment() :
LuaScriptInterface("Main Interface"), m_testInterface(nullptr),
m_lastEventTimerId(1), m_lastCombatId(0), m_lastConditionId(0), m_lastAreaId(0)
{
//
}
LuaEnvironment::~LuaEnvironment()
{
delete m_testInterface;
closeState();
}
bool LuaEnvironment::initState()
{
m_luaState = luaL_newstate();
if (!m_luaState) {
return false;
}
luaL_openlibs(m_luaState);
registerFunctions();
m_runningEventId = EVENT_ID_USER;
return true;
}
bool LuaEnvironment::reInitState()
{
// TODO: get children, reload children
closeState();
return initState();
}
bool LuaEnvironment::closeState()
{
if (!m_luaState) {
return false;
}
for (const auto& combatEntry : m_combatIdMap) {
clearCombatObjects(combatEntry.first);
}
for (const auto& areaEntry : m_areaIdMap) {
clearAreaObjects(areaEntry.first);
}
for (auto& timerEntry : m_timerEvents) {
LuaTimerEventDesc timerEventDesc = std::move(timerEntry.second);
for (int32_t parameter : timerEventDesc.parameters) {
luaL_unref(m_luaState, LUA_REGISTRYINDEX, parameter);
}
luaL_unref(m_luaState, LUA_REGISTRYINDEX, timerEventDesc.function);
}
m_combatIdMap.clear();
m_areaIdMap.clear();
m_timerEvents.clear();
m_cacheFiles.clear();
lua_close(m_luaState);
m_luaState = nullptr;
return true;
}
LuaScriptInterface* LuaEnvironment::getTestInterface()
{
if (!m_testInterface) {
m_testInterface = new LuaScriptInterface("Test Interface");
m_testInterface->initState();
}
return m_testInterface;
}
Combat* LuaEnvironment::getCombatObject(uint32_t id) const
{
auto it = m_combatMap.find(id);
if (it == m_combatMap.end()) {
return nullptr;
}
return it->second;
}
uint32_t LuaEnvironment::createCombatObject(LuaScriptInterface* interface)
{
m_combatMap[++m_lastCombatId] = new Combat;
m_combatIdMap[interface].push_back(m_lastCombatId);
return m_lastCombatId;
}
void LuaEnvironment::clearCombatObjects(LuaScriptInterface* interface)
{
auto it = m_combatIdMap.find(interface);
if (it == m_combatIdMap.end()) {
return;
}
for (uint32_t id : it->second) {
auto itt = m_combatMap.find(id);
if (itt != m_combatMap.end()) {
delete itt->second;
m_combatMap.erase(itt);
}
}
it->second.clear();
}
Condition* LuaEnvironment::getConditionObject(uint32_t id) const
{
auto it = m_conditionMap.find(id);
if (it == m_conditionMap.end()) {
return nullptr;
}
return it->second;
}
bool LuaEnvironment::createConditionObject(ConditionType_t conditionType, ConditionId_t conditionId, uint32_t& id)
{
Condition* condition = Condition::createCondition(conditionId, conditionType, 0, 0);
if (!condition) {
return false;
}
id = ++m_lastConditionId;
m_conditionMap[m_lastConditionId] = condition;
return true;
}
AreaCombat* LuaEnvironment::getAreaObject(uint32_t id) const
{
auto it = m_areaMap.find(id);
if (it == m_areaMap.end()) {
return nullptr;
}
return it->second;
}
uint32_t LuaEnvironment::createAreaObject(LuaScriptInterface* interface)
{
m_areaMap[++m_lastAreaId] = new AreaCombat;
m_areaIdMap[interface].push_back(m_lastAreaId);
return m_lastAreaId;
}
void LuaEnvironment::clearAreaObjects(LuaScriptInterface* interface)
{
auto it = m_areaIdMap.find(interface);
if (it == m_areaIdMap.end()) {
return;
}
for (uint32_t id : it->second) {
auto itt = m_areaMap.find(id);
if (itt != m_areaMap.end()) {
delete itt->second;
m_areaMap.erase(itt);
}
}
it->second.clear();
}
void LuaEnvironment::executeTimerEvent(uint32_t eventIndex)
{
auto it = m_timerEvents.find(eventIndex);
if (it == m_timerEvents.end()) {
return;
}
LuaTimerEventDesc timerEventDesc = std::move(it->second);
m_timerEvents.erase(it);
//push function
lua_rawgeti(m_luaState, LUA_REGISTRYINDEX, timerEventDesc.function);
//push parameters
for (auto parameter : boost::adaptors::reverse(timerEventDesc.parameters)) {
lua_rawgeti(m_luaState, LUA_REGISTRYINDEX, parameter);
}
//call the function
if (reserveScriptEnv()) {
ScriptEnvironment* env = getScriptEnv();
env->setTimerEvent();
env->setScriptId(timerEventDesc.scriptId, this);
callFunction(timerEventDesc.parameters.size());
} else {
std::cout << "[Error - LuaScriptInterface::executeTimerEvent] Call stack overflow" << std::endl;
}
//free resources
luaL_unref(m_luaState, LUA_REGISTRYINDEX, timerEventDesc.function);
for (auto parameter : timerEventDesc.parameters) {
luaL_unref(m_luaState, LUA_REGISTRYINDEX, parameter);
}
}
| 1 | 11,577 | Should be named getDescription, since the other description functions are named that. | otland-forgottenserver | cpp |
@@ -62,7 +62,9 @@ public class PlatformActivity extends VRActivity implements RenderInterface, CVC
if (ControllerClient.isControllerServiceExisted(this)) {
mControllerManager = new CVControllerManager(this);
mControllerManager.setListener(this);
- mType = 1;
+ mType = 1; // Neo2
+ // Enable high res
+ PicovrSDK.SetEyeBufferSize(1920, 1920);
} else {
mHbManager = new HbManager(this);
mHbManager.InitServices(); | 1 | /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.vrbrowser;
import android.Manifest;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import com.picovr.client.HbListener;
import com.picovr.cvclient.ButtonNum;
import com.picovr.client.HbController;
import com.picovr.client.HbManager;
import com.picovr.client.HbTool;
import com.picovr.client.Orientation;
import com.picovr.cvclient.CVController;
import com.picovr.cvclient.CVControllerListener;
import com.picovr.cvclient.CVControllerManager;
import com.picovr.picovrlib.cvcontrollerclient.ControllerClient;
import com.picovr.vractivity.Eye;
import com.picovr.vractivity.HmdState;
import com.picovr.vractivity.RenderInterface;
import com.picovr.vractivity.VRActivity;
import com.psmart.vrlib.VrActivity;
import com.psmart.vrlib.PicovrSDK;
import org.mozilla.vrbrowser.utils.SystemUtils;
public class PlatformActivity extends VRActivity implements RenderInterface, CVControllerListener {
static String LOGTAG = SystemUtils.createLogtag(PlatformActivity.class);
public static boolean filterPermission(final String aPermission) {
if (aPermission.equals(Manifest.permission.CAMERA)) {
return true;
}
return false;
}
CVControllerManager mControllerManager;
HbManager mHbManager;
private boolean mControllersReady;
private int mType = 0;
private int mHand = 0;
// These need to match DeviceDelegatePicoVR.cpp
private final int BUTTON_APP = 1;
private final int BUTTON_TRIGGER = 1 << 1;
private final int BUTTON_TOUCHPAD = 1 << 2;
private final int BUTTON_AX = 1 << 3;
private final int BUTTON_BY = 1 << 4;
private final int BUTTON_GRIP = 1 << 5;
@Override
protected void onCreate(Bundle bundle) {
nativeOnCreate();
super.onCreate(bundle);
if (ControllerClient.isControllerServiceExisted(this)) {
mControllerManager = new CVControllerManager(this);
mControllerManager.setListener(this);
mType = 1;
} else {
mHbManager = new HbManager(this);
mHbManager.InitServices();
mHbManager.setHbListener(new HbListener() {
// Does not seem to get called.
@Override
public void onConnect() {}
// Does not seem to get called.
@Override
public void onDisconnect() {}
@Override
public void onDataUpdate() {
}
// Does not seem to get called.
@Override
public void onReCenter() {}
@Override
public void onBindService() {
mControllersReady = true;
}
});
}
}
@Override
protected void onPause() {
if (mControllerManager != null) {
mControllerManager.unbindService();
} else if (mHbManager != null) {
mHbManager.Pause();
}
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
if (mControllerManager != null) {
mControllerManager.bindService();
} else if (mHbManager != null) {
mHbManager.Resume();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mControllerManager != null) {
mControllerManager.setListener(null);
}
}
@Override
public void onBackPressed() {
// Eat the back button.
}
@Override
public void onFrameBegin(HmdState hmdState) {
updateControllers();
float[] q = hmdState.getOrientation();
float[] p = hmdState.getPos();
float ipd = hmdState.getIpd();
float fov = hmdState.getFov();
nativeStartFrame(ipd, fov, p[0], p[1], p[2], q[0], q[1], q[2], q[3]);
}
private void updateControllers() {
if (!mControllersReady) {
return;
}
if (mControllerManager != null) {
int hand = VrActivity.getPvrHandness(this);
if (hand != mHand) {
nativeSetFocusedController(hand);
mHand = hand;
}
CVController main = mControllerManager.getMainController();
if (main != null) {
updateController(hand, main);
}
CVController sub = mControllerManager.getSubController();
if (sub != null) {
updateController(1 - hand, sub);
}
} else if (mHbManager != null) {
update3DofController();
}
}
private void update3DofController() {
if (mHbManager == null) {
return;
}
HbController controller = mHbManager.getHbController();
if (controller == null) {
Log.e(LOGTAG, "CONTROLLER NULL");
return;
}
if (controller.getConnectState() < 2) {
nativeUpdateControllerState(0, false, 0, 0, 0, 0, false);
return;
}
int hand = VrActivity.getPvrHandness(this);
if (mHand != hand) {
nativeUpdateControllerState(mHand, false, 0, 0, 0, 0, false);
mHand = hand;
}
controller.update();
float axisX = 0;
float axisY = 0;
int[] stick = controller.getTouchPosition();
if (stick.length >= 2) {
axisY = 1.0f -((float)stick[0] / 255.0f);
axisX = (float)stick[1] / 255.0f;
}
int buttons = 0;
int trigger = controller.getTrigerKeyEvent();
boolean touched = controller.isTouching();
buttons |= controller.getButtonState(HbTool.ButtonNum.app) ? BUTTON_APP : 0;
buttons |= controller.getButtonState(HbTool.ButtonNum.click) ? BUTTON_TOUCHPAD : 0;
buttons |= trigger > 0 ? BUTTON_TRIGGER : 0;
nativeUpdateControllerState(mHand, true, buttons, (float)trigger, axisX, axisY, touched);
Orientation q = controller.getOrientation();
nativeUpdateControllerPose(mHand, false, 0.0f, 0.0f, 0.0f, q.x, q.y, q.z, q.w);
}
private void updateController(int aIndex, @NonNull CVController aController) {
final float kMax = 25500.0f;
final float kHalfMax = kMax / 2.0f;
boolean connected = aController.getConnectState() > 0;
if (!connected) {
nativeUpdateControllerState(aIndex, false, 0, 0, 0, 0, false);
return;
}
float axisX = 0.0f;
float axisY = 0.0f;
int[] stick = aController.getTouchPad();
if (stick.length >= 2) {
//Log.e(LOGTAG, "stick[" + aIndex + "] " + stick[0] + " " + stick[1]);
/*
axisY = ((float)stick[0] - kHalfMax) / kHalfMax;
axisX = ((float)stick[1] - kHalfMax) / kHalfMax;
if (axisX < 0.1f && axisX > -0.1f) { axisX = 0.0f; }
if (axisY < 0.1f && axisY > -0.1f) { axisY = 0.0f; }
*/
axisY = (float)stick[0] / kMax;
axisX = (float)stick[1] / kMax;
} else {
stick = new int[2];
}
int buttons = 0;
float trigger = (float)aController.getTriggerNum() / 255.0f;
buttons |= aController.getButtonState(ButtonNum.app) ? BUTTON_APP : 0;
buttons |= aController.getButtonState(ButtonNum.buttonAX) ? BUTTON_AX : 0;
buttons |= aController.getButtonState(ButtonNum.buttonBY) ? BUTTON_BY : 0;
buttons |= trigger >= 0.9f ? BUTTON_TRIGGER : 0;
buttons |= aController.getButtonState(ButtonNum.buttonRG) ? BUTTON_GRIP : 0;
buttons |= aController.getButtonState(ButtonNum.buttonLG) ? BUTTON_GRIP : 0;
buttons |= aController.getButtonState(ButtonNum.click) ? BUTTON_TOUCHPAD : 0;
nativeUpdateControllerState(aIndex, true, buttons, trigger, axisX, axisY, (stick[0] != 0 ) || (stick[1] != 0));
boolean supports6Dof = aController.get6DofAbility() > 0;
float[] q = aController.getOrientation();
float[] p = aController.getPosition();
nativeUpdateControllerPose(aIndex, supports6Dof, p[0], p[1], p[2], q[0], q[1], q[2], q[3]);
}
@Override
public void onDrawEye(Eye eye) {
nativeDrawEye(eye.getType());
}
@Override
public void onFrameEnd() {
nativeEndFrame();
}
@Override
public void onTouchEvent() {
}
@Override
public void onRenderPause() {
nativePause();
}
@Override
public void onRenderResume() {
nativeResume();
}
@Override
public void onRendererShutdown() {
nativeShutdown();
nativeDestroy();
}
@Override
public void initGL(int width, int height) {
mHand = VrActivity.getPvrHandness(this);
nativeInitialize(width, height, getAssets(), mType, mHand);
}
@Override
public void renderEventCallBack(int i) {
}
@Override
public void surfaceChangedCallBack(int width, int height) {
}
// CVControllerListener
/*
@Override
public void onBindSuccess() {
}
*/
@Override
public void onBindFail() {
mControllersReady = false;
}
@Override
public void onThreadStart() {
mControllersReady = true;
}
@Override
public void onConnectStateChanged(int serialNum, int state) {
}
@Override
public void onMainControllerChanged(int serialNum) {
}
/*
@Override
public void onChannelChanged(int var1, int var2) {
}
*/
protected native void nativeOnCreate();
protected native void nativeInitialize(int width, int height, Object aAssetManager, int type, int focusIndex);
protected native void nativeShutdown();
protected native void nativeDestroy();
protected native void nativeStartFrame(float ipd, float fov, float px, float py, float pz, float qx, float qy, float qz, float qw);
protected native void nativeDrawEye(int eye);
protected native void nativeEndFrame();
protected native void nativePause();
protected native void nativeResume();
protected native void nativeSetFocusedController(int index);
protected native void nativeUpdateControllerState(int index, boolean connected, int buttons, float grip, float axisX, float axisY, boolean touched);
protected native void nativeUpdateControllerPose(int index, boolean dof6, float px, float py, float pz, float qx, float qy, float qz, float qw);
protected native void queueRunnable(Runnable aRunnable);
}
| 1 | 9,035 | Don't we want to do this for g2 4k also? | MozillaReality-FirefoxReality | java |
@@ -4,6 +4,8 @@ const time = require('./time').default;
const Logger = require('./Logger').default;
const { _ } = require('./locale');
const urlUtils = require('./urlUtils.js');
+const str2ab = require('string-to-arraybuffer');
+const Buffer = require('buffer').Buffer;
class OneDriveApi {
// `isPublic` is to tell OneDrive whether the application is a "public" one (Mobile and desktop | 1 | const shim = require('./shim').default;
const { stringify } = require('query-string');
const time = require('./time').default;
const Logger = require('./Logger').default;
const { _ } = require('./locale');
const urlUtils = require('./urlUtils.js');
class OneDriveApi {
// `isPublic` is to tell OneDrive whether the application is a "public" one (Mobile and desktop
// apps are considered "public"), in which case the secret should not be sent to the API.
// In practice the React Native app is public, and the Node one is not because we
// use a local server for the OAuth dance.
constructor(clientId, clientSecret, isPublic) {
this.clientId_ = clientId;
this.clientSecret_ = clientSecret;
this.auth_ = null;
this.accountProperties_ = null;
this.isPublic_ = isPublic;
this.listeners_ = {
authRefreshed: [],
};
this.logger_ = new Logger();
}
setLogger(l) {
this.logger_ = l;
}
logger() {
return this.logger_;
}
isPublic() {
return this.isPublic_;
}
dispatch(eventName, param) {
const ls = this.listeners_[eventName];
for (let i = 0; i < ls.length; i++) {
ls[i](param);
}
}
on(eventName, callback) {
this.listeners_[eventName].push(callback);
}
tokenBaseUrl() {
return 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
}
nativeClientRedirectUrl() {
return 'https://login.microsoftonline.com/common/oauth2/nativeclient';
}
auth() {
return this.auth_;
}
setAuth(auth) {
this.auth_ = auth;
this.dispatch('authRefreshed', this.auth());
}
token() {
return this.auth_ ? this.auth_.access_token : null;
}
clientId() {
return this.clientId_;
}
clientSecret() {
return this.clientSecret_;
}
async appDirectory() {
const driveId = this.accountProperties_.driveId;
const r = await this.execJson('GET', `/me/drives/${driveId}/special/approot`);
return `${r.parentReference.path}/${r.name}`;
}
authCodeUrl(redirectUri) {
const query = {
client_id: this.clientId_,
scope: 'files.readwrite offline_access sites.readwrite.all',
response_type: 'code',
redirect_uri: redirectUri,
};
return `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?${stringify(query)}`;
}
async execTokenRequest(code, redirectUri) {
const body = {};
body['client_id'] = this.clientId();
if (!this.isPublic()) body['client_secret'] = this.clientSecret();
body['code'] = code;
body['redirect_uri'] = redirectUri;
body['grant_type'] = 'authorization_code';
const r = await shim.fetch(this.tokenBaseUrl(), {
method: 'POST',
body: urlUtils.objectToQueryString(body),
headers: {
['Content-Type']: 'application/x-www-form-urlencoded',
},
});
if (!r.ok) {
const text = await r.text();
throw new Error(`Could not retrieve auth code: ${r.status}: ${r.statusText}: ${text}`);
}
try {
const json = await r.json();
this.setAuth(json);
} catch (error) {
this.setAuth(null);
const text = await r.text();
error.message += `: ${text}`;
throw error;
}
}
oneDriveErrorResponseToError(errorResponse) {
if (!errorResponse) return new Error('Undefined error');
if (errorResponse.error) {
const e = errorResponse.error;
const output = new Error(e.message);
if (e.code) output.code = e.code;
if (e.innerError) output.innerError = e.innerError;
return output;
} else {
return new Error(JSON.stringify(errorResponse));
}
}
async uploadChunk(url, handle, options) {
options = Object.assign({}, options);
if (!options.method) { options.method = 'POST'; }
if (!options.headers) { options.headers = {}; }
if (!options.contentLength) throw new Error(' uploadChunk: contentLength is missing');
const chunk = await shim.fsDriver().readFileChunk(handle, options.contentLength);
const Buffer = require('buffer').Buffer;
const buffer = Buffer.from(chunk, 'base64');
delete options.contentLength;
options.body = buffer;
const response = await shim.fetch(url, options);
return response;
}
async uploadBigFile(url, options) {
const response = await shim.fetch(url, {
method: 'POST',
headers: {
'Authorization': options.headers.Authorization,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
return response;
} else {
const uploadUrl = (await response.json()).uploadUrl;
// uploading file in 7.5 MiB-Fragments (except the last one) because this is the mean of 5 and 10 Mib which are the recommended lower and upper limits.
// https://docs.microsoft.com/de-de/onedrive/developer/rest-api/api/driveitem_createuploadsession?view=odsp-graph-online#best-practices
const chunkSize = 7.5 * 1024 * 1024;
const fileSize = (await shim.fsDriver().stat(options.path)).size;
const numberOfChunks = Math.ceil(fileSize / chunkSize);
const handle = await shim.fsDriver().open(options.path, 'r');
try {
for (let i = 0; i < numberOfChunks; i++) {
const startByte = i * chunkSize;
let endByte = null;
let contentLength = null;
if (i === numberOfChunks - 1) {
// Last fragment. It is not ensured that the last fragment is a multiple of 327,680 bytes as recommanded in the api doc. The reasons is that the docs are out of day for this purpose: https://github.com/OneDrive/onedrive-api-docs/issues/1200#issuecomment-597281253
endByte = fileSize - 1;
contentLength = fileSize - ((numberOfChunks - 1) * chunkSize);
} else {
endByte = (i + 1) * chunkSize - 1;
contentLength = chunkSize;
}
this.logger().debug(`${options.path}: Uploading File Fragment ${(startByte / 1048576).toFixed(2)} - ${(endByte / 1048576).toFixed(2)} from ${(fileSize / 1048576).toFixed(2)} Mbit ...`);
const headers = {
'Content-Length': contentLength,
'Content-Range': `bytes ${startByte}-${endByte}/${fileSize}`,
'Content-Type': 'application/octet-stream; charset=utf-8',
};
const response = await this.uploadChunk(uploadUrl, handle, { contentLength: contentLength, method: 'PUT', headers: headers });
if (!response.ok) {
return response;
}
}
return { ok: true };
} catch (error) {
this.logger().error('Got unhandled error:', error ? error.code : '', error ? error.message : '', error);
throw error;
} finally {
await shim.fsDriver().close(handle);
}
}
}
async exec(method, path, query = null, data = null, options = null) {
if (!path) throw new Error('Path is required');
method = method.toUpperCase();
if (!options) options = {};
if (!options.headers) options.headers = {};
if (!options.target) options.target = 'string';
if (method != 'GET') {
options.method = method;
}
if (method == 'PATCH' || method == 'POST') {
options.headers['Content-Type'] = 'application/json';
if (data) data = JSON.stringify(data);
}
let url = path;
// In general, `path` contains a path relative to the base URL, but in some
// cases the full URL is provided (for example, when it's a URL that was
// retrieved from the API).
if (url.indexOf('https://') !== 0) {
const slash = path.indexOf('/') === 0 ? '' : '/';
url = `https://graph.microsoft.com/v1.0${slash}${path}`;
}
if (query) {
url += url.indexOf('?') < 0 ? '?' : '&';
url += stringify(query);
}
if (data) options.body = data;
options.timeout = 1000 * 60 * 5; // in ms
for (let i = 0; i < 5; i++) {
options.headers['Authorization'] = `bearer ${this.token()}`;
let response = null;
try {
if (options.source == 'file' && (method == 'POST' || method == 'PUT')) {
response = path.includes('/createUploadSession') ? await this.uploadBigFile(url, options) : await shim.uploadBlob(url, options);
} else if (options.target == 'string') {
response = await shim.fetch(url, options);
} else {
// file
response = await shim.fetchBlob(url, options);
}
} catch (error) {
this.logger().error('Got unhandled error:', error ? error.code : '', error ? error.message : '', error);
throw error;
}
if (!response.ok) {
const errorResponseText = await response.text();
let errorResponse = null;
try {
errorResponse = JSON.parse(errorResponseText); // await response.json();
} catch (error) {
error.message = `OneDriveApi::exec: Cannot parse JSON error: ${errorResponseText} ${error.message}`;
throw error;
}
const error = this.oneDriveErrorResponseToError(errorResponse);
if (error.code == 'InvalidAuthenticationToken' || error.code == 'unauthenticated') {
this.logger().info('Token expired: refreshing...');
await this.refreshAccessToken();
continue;
} else if (error && ((error.error && error.error.code == 'generalException') || error.code == 'generalException' || error.code == 'EAGAIN')) {
// Rare error (one Google hit) - I guess the request can be repeated
// { error:
// { code: 'generalException',
// message: 'An error occurred in the data store.',
// innerError:
// { 'request-id': 'b4310552-c18a-45b1-bde1-68e2c2345eef',
// date: '2017-06-29T00:15:50' } } }
// { FetchError: request to https://graph.microsoft.com/v1.0/drive/root:/Apps/Joplin/.sync/7ee5dc04afcb414aa7c684bfc1edba8b.md_1499352102856 failed, reason: connect EAGAIN 65.52.64.250:443 - Local (0.0.0.0:54374)
// name: 'FetchError',
// message: 'request to https://graph.microsoft.com/v1.0/drive/root:/Apps/Joplin/.sync/7ee5dc04afcb414aa7c684bfc1edba8b.md_1499352102856 failed, reason: connect EAGAIN 65.52.64.250:443 - Local (0.0.0.0:54374)',
// type: 'system',
// errno: 'EAGAIN',
// code: 'EAGAIN' }
this.logger().info(`Got error below - retrying (${i})...`);
this.logger().info(error);
await time.sleep((i + 1) * 3);
continue;
} else if (error && (error.code === 'resourceModified' || (error.error && error.error.code === 'resourceModified'))) {
// NOTE: not tested, very hard to reproduce and non-informative error message, but can be repeated
// Error: ETag does not match current item's value
// Code: resourceModified
// Header: {"_headers":{"cache-control":["private"],"transfer-encoding":["chunked"],"content-type":["application/json"],"request-id":["d...ea47"],"client-request-id":["d99...ea47"],"x-ms-ags-diagnostic":["{\"ServerInfo\":{\"DataCenter\":\"North Europe\",\"Slice\":\"SliceA\",\"Ring\":\"2\",\"ScaleUnit\":\"000\",\"Host\":\"AGSFE_IN_13\",\"ADSiteName\":\"DUB\"}}"],"duration":["96.9464"],"date":[],"connection":["close"]}}
// Request: PATCH https://graph.microsoft.com/v1.0/drive/root:/Apps/JoplinDev/f56c5601fee94b8085524513bf3e352f.md null "{\"fileSystemInfo\":{\"lastModifiedDateTime\":\"....\"}}" {"headers":{"Content-Type":"application/json","Authorization":"bearer ...
this.logger().info(`Got error below - retrying (${i})...`);
this.logger().info(error);
await time.sleep((i + 1) * 3);
continue;
} else if (error.code == 'itemNotFound' && method == 'DELETE') {
// Deleting a non-existing item is ok - noop
return;
} else {
error.request = `${method} ${url} ${JSON.stringify(query)} ${JSON.stringify(data)} ${JSON.stringify(options)}`;
error.headers = await response.headers;
throw error;
}
}
return response;
}
throw new Error(`Could not execute request after multiple attempts: ${method} ${url}`);
}
setAccountProperties(accountProperties) {
this.accountProperties_ = accountProperties;
}
async execAccountPropertiesRequest() {
try {
const response = await this.exec('GET','https://graph.microsoft.com/v1.0/me/drive');
const data = await response.json();
const accountProperties = { accountType: data.driveType, driveId: data.id };
return accountProperties;
} catch (error) {
throw new Error(`Could not retrieve account details (drive ID, Account type. Error code: ${error.code}, Error message: ${error.message}`);
}
}
async execJson(method, path, query, data) {
const response = await this.exec(method, path, query, data);
const errorResponseText = await response.text();
try {
const output = JSON.parse(errorResponseText); // await response.json();
return output;
} catch (error) {
error.message = `OneDriveApi::execJson: Cannot parse JSON: ${errorResponseText} ${error.message}`;
throw error;
// throw new Error('Cannot parse JSON: ' + text);
}
}
async execText(method, path, query, data) {
const response = await this.exec(method, path, query, data);
const output = await response.text();
return output;
}
async refreshAccessToken() {
if (!this.auth_ || !this.auth_.refresh_token) {
this.setAuth(null);
throw new Error(_('Cannot refresh token: authentication data is missing. Starting the synchronisation again may fix the problem.'));
}
const body = {};
body['client_id'] = this.clientId();
if (!this.isPublic()) body['client_secret'] = this.clientSecret();
body['refresh_token'] = this.auth_.refresh_token;
body['redirect_uri'] = 'http://localhost:1917';
body['grant_type'] = 'refresh_token';
const response = await shim.fetch(this.tokenBaseUrl(), {
method: 'POST',
body: urlUtils.objectToQueryString(body),
headers: {
['Content-Type']: 'application/x-www-form-urlencoded',
},
});
if (!response.ok) {
this.setAuth(null);
const msg = await response.text();
throw new Error(`${msg}: TOKEN: ${this.auth_}`);
}
const auth = await response.json();
this.setAuth(auth);
}
}
module.exports = { OneDriveApi };
| 1 | 15,615 | I would prefer if we don't add this package as it's unsupported, and I expect not necessary. Node buffer supports many formats - is it not possible to use one of its helper functions to load the content? | laurent22-joplin | js |
@@ -205,6 +205,12 @@ type Table struct {
// to what we calculate from chainToContents.
chainToDataplaneHashes map[string][]string
+ // chainsToFullRules contains the full rules, mapped from chain name to slices of rules in that chain.
+ chainsToFullRules map[string][]string
+
+ // hashToFullRules contains a mapping of rule hashes to the full rules.
+ hashToFullRules map[string]string
+
// hashCommentPrefix holds the prefix that we prepend to our rule-tracking hashes.
hashCommentPrefix string
// hashCommentRegexp matches the rule-tracking comment, capturing the rule hash. | 1 | // Copyright (c) 2016-2019 Tigera, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package iptables
import (
"bufio"
"bytes"
"fmt"
"io"
"os/exec"
"reflect"
"regexp"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"github.com/projectcalico/libcalico-go/lib/set"
)
const (
MaxChainNameLength = 28
minPostWriteInterval = 50 * time.Millisecond
)
var (
// List of all the top-level kernel-created chains by iptables table.
tableToKernelChains = map[string][]string{
"filter": []string{"INPUT", "FORWARD", "OUTPUT"},
"nat": []string{"PREROUTING", "INPUT", "OUTPUT", "POSTROUTING"},
"mangle": []string{"PREROUTING", "INPUT", "FORWARD", "OUTPUT", "POSTROUTING"},
"raw": []string{"PREROUTING", "OUTPUT"},
}
// chainCreateRegexp matches iptables-save output lines for chain forward reference lines.
// It captures the name of the chain.
chainCreateRegexp = regexp.MustCompile(`^:(\S+)`)
// appendRegexp matches an iptables-save output line for an append operation.
appendRegexp = regexp.MustCompile(`^-A (\S+)`)
// Prometheus metrics.
countNumRestoreCalls = prometheus.NewCounter(prometheus.CounterOpts{
Name: "felix_iptables_restore_calls",
Help: "Number of iptables-restore calls.",
})
countNumRestoreErrors = prometheus.NewCounter(prometheus.CounterOpts{
Name: "felix_iptables_restore_errors",
Help: "Number of iptables-restore errors.",
})
countNumSaveCalls = prometheus.NewCounter(prometheus.CounterOpts{
Name: "felix_iptables_save_calls",
Help: "Number of iptables-save calls.",
})
countNumSaveErrors = prometheus.NewCounter(prometheus.CounterOpts{
Name: "felix_iptables_save_errors",
Help: "Number of iptables-save errors.",
})
gaugeNumChains = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "felix_iptables_chains",
Help: "Number of active iptables chains.",
}, []string{"ip_version", "table"})
gaugeNumRules = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "felix_iptables_rules",
Help: "Number of active iptables rules.",
}, []string{"ip_version", "table"})
countNumLinesExecuted = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "felix_iptables_lines_executed",
Help: "Number of iptables rule updates executed.",
}, []string{"ip_version", "table"})
)
func init() {
prometheus.MustRegister(countNumRestoreCalls)
prometheus.MustRegister(countNumRestoreErrors)
prometheus.MustRegister(countNumSaveCalls)
prometheus.MustRegister(countNumSaveErrors)
prometheus.MustRegister(gaugeNumChains)
prometheus.MustRegister(gaugeNumRules)
prometheus.MustRegister(countNumLinesExecuted)
}
// Table represents a single one of the iptables tables i.e. "raw", "nat", "filter", etc. It
// caches the desired state of that table, then attempts to bring it into sync when Apply() is
// called.
//
// API Model
//
// Table supports two classes of operation: "rule insertions" and "full chain updates".
//
// As the name suggests, rule insertions allow for inserting one or more rules into a pre-existing
// chain. Rule insertions are intended to be used to hook kernel chains (such as "FORWARD") in
// order to direct them to a Felix-owned chain. It is important to minimise the use of rule
// insertions because the top-level chains are shared resources, which can be modified by other
// applications. In addition, rule insertions are harder to clean up after an upgrade to a new
// version of Felix (because we need a way to recognise our rules in a crowded chain).
//
// Full chain updates replace the entire contents of a Felix-owned chain with a new set of rules.
// Limiting the operation to "replace whole chain" in this way significantly simplifies the API.
// Although the API operates on full chains, the dataplane write logic tries to avoid rewriting
// a whole chain if only part of it has changed (this was not the case in Felix 1.4). This
// prevents iptables counters from being reset unnecessarily.
//
// In either case, the actual dataplane updates are deferred until the next call to Apply() so
// chain updates and insertions may occur in any order as long as they are consistent (i.e. there
// are no references to non-existent chains) by the time Apply() is called.
//
// Design
//
// We had several goals in designing the iptables machinery in 2.0.0:
//
// (1) High performance. Felix needs to handle high churn of endpoints and rules.
//
// (2) Ability to restore rules, even if other applications accidentally break them: we found that
// other applications sometimes misuse iptables-save and iptables-restore to do a read, modify,
// write cycle. That behaviour is not safe under concurrent modification.
//
// (3) Avoid rewriting rules that haven't changed so that we don't reset iptables counters.
//
// (4) Avoid parsing iptables commands (for example, the output from iptables/iptables-save).
// This is very hard to do robustly because iptables rules do not necessarily round-trip through
// the kernel in the same form. In addition, the format could easily change due to changes or
// fixes in the iptables/iptables-save command.
//
// (5) Support for graceful restart. I.e. deferring potentially incorrect updates until we're
// in-sync with the datastore. For example, if we have 100 endpoints on a host, after a restart
// we don't want to write a "dispatch" chain when we learn about the first endpoint (possibly
// replacing an existing one that had all 100 endpoints in place and causing traffic to glitch);
// instead, we want to defer until we've seen all 100 and then do the write.
//
// (6) Improved handling of rule inserts vs Felix 1.4.x. Previous versions of Felix sometimes
// inserted special-case rules that were not marked as Calico rules in any sensible way making
// cleanup of those rules after an upgrade difficult.
//
// Implementation
//
// For high performance (goal 1), we use iptables-restore to do bulk updates to iptables. This is
// much faster than individual iptables calls.
//
// To allow us to restore rules after they are clobbered by another process (goal 2), we cache
// them at this layer. This means that we don't need a mechanism to ask the other layers of Felix
// to do a resync. Note: Table doesn't start a thread of its own so it relies on the main event
// loop to trigger any dataplane resync polls.
//
// There is tension between goals 3 and 4. In order to avoid full rewrites (goal 3), we need to
// know what rules are in place, but we also don't want to parse them to find out (goal 4)! As
// a compromise, we deterministically calculate an ID for each rule and store it in an iptables
// comment. Then, when we want to know what rules are in place, we _do_ parse the output from
// iptables-save, but only to read back the rule IDs. That limits the amount of parsing we need
// to do and keeps it manageable/robust.
//
// To support graceful restart (goal 5), we defer updates to the dataplane until Apply() is called,
// then we do an atomic update using iptables-restore. As long as the first Apply() call is
// after we're in sync, the dataplane won't be touched until the right time. Felix 1.4.x had a
// more complex mechanism to support partial updates during the graceful restart period but
// Felix 2.0.0 resyncs so quickly that the added complexity is not justified.
//
// To make it easier to manage rule insertions (goal 6), we add rule IDs to those too. With
// rule IDs in place, we can easily distinguish Calico rules from non-Calico rules without needing
// to know exactly which rules to expect. To deal with cleanup after upgrade from older versions
// that did not write rule IDs, we support special-case regexes to detect our old rules.
//
// Thread safety
//
// Table doesn't do any internal synchronization, its methods should only be called from one
// thread. To avoid conflicts in the dataplane itself, there should only be one instance of
// Table for each iptable table in an application.
type Table struct {
Name string
IPVersion uint8
// featureDetector detects the features of the dataplane.
featureDetector *FeatureDetector
// chainToInsertedRules maps from chain name to a list of rules to be inserted at the start
// of that chain. Rules are written with rule hash comments. The Table cleans up inserted
// rules with unknown hashes.
chainToInsertedRules map[string][]Rule
dirtyInserts set.Set
// chainToRuleFragments contains the desired state of our iptables chains, indexed by
// chain name. The values are slices of iptables fragments, such as
// "--match foo --jump DROP" (i.e. omitting the action and chain name, which are calculated
// as needed).
chainNameToChain map[string]*Chain
dirtyChains set.Set
inSyncWithDataPlane bool
// chainToDataplaneHashes contains the rule hashes that we think are in the dataplane.
// it is updated when we write to the dataplane but it can also be read back and compared
// to what we calculate from chainToContents.
chainToDataplaneHashes map[string][]string
// hashCommentPrefix holds the prefix that we prepend to our rule-tracking hashes.
hashCommentPrefix string
// hashCommentRegexp matches the rule-tracking comment, capturing the rule hash.
hashCommentRegexp *regexp.Regexp
// ourChainsRegexp matches the names of chains that are "ours", i.e. start with one of our
// prefixes.
ourChainsRegexp *regexp.Regexp
// oldInsertRegexp matches inserted rules from old pre rule-hash versions of felix.
oldInsertRegexp *regexp.Regexp
// nftablesMode should be set to true if iptables is using the nftables backend.
nftablesMode bool
iptablesRestoreCmd string
iptablesSaveCmd string
// insertMode is either "insert" or "append"; whether we insert our rules or append them
// to top-level chains.
insertMode string
// Record when we did our most recent reads and writes of the table. We use these to
// calculate the next time we should force a refresh.
lastReadTime time.Time
lastWriteTime time.Time
initialPostWriteInterval time.Duration
postWriteInterval time.Duration
refreshInterval time.Duration
// calicoXtablesLock, if enabled, our implementation of the xtables lock.
calicoXtablesLock sync.Locker
// lockTimeout is the timeout used for iptables-restore's native xtables lock implementation.
lockTimeout time.Duration
// lockTimeout is the lock probe interval used for iptables-restore's native xtables lock
// implementation.
lockProbeInterval time.Duration
logCxt *log.Entry
gaugeNumChains prometheus.Gauge
gaugeNumRules prometheus.Gauge
countNumLinesExecuted prometheus.Counter
// Reusable buffer for writing to iptables.
restoreInputBuffer RestoreInputBuilder
// Factory for making commands, used by UTs to shim exec.Command().
newCmd cmdFactory
// Shims for time.XXX functions:
timeSleep func(d time.Duration)
timeNow func() time.Time
// lookPath is a shim for exec.LookPath.
lookPath func(file string) (string, error)
}
type TableOptions struct {
HistoricChainPrefixes []string
ExtraCleanupRegexPattern string
BackendMode string
InsertMode string
RefreshInterval time.Duration
PostWriteInterval time.Duration
// LockTimeout is the timeout to use for iptables-restore's native xtables lock.
LockTimeout time.Duration
// LockProbeInterval is the probe interval to use for iptables-restore's native xtables lock.
LockProbeInterval time.Duration
// NewCmdOverride for tests, if non-nil, factory to use instead of the real exec.Command()
NewCmdOverride cmdFactory
// SleepOverride for tests, if non-nil, replacement for time.Sleep()
SleepOverride func(d time.Duration)
// NowOverride for tests, if non-nil, replacement for time.Now()
NowOverride func() time.Time
// LookPathOverride for tests, if non-nil, replacement for exec.LookPath()
LookPathOverride func(file string) (string, error)
}
func NewTable(
name string,
ipVersion uint8,
hashPrefix string,
iptablesWriteLock sync.Locker,
detector *FeatureDetector,
options TableOptions,
) *Table {
// Calculate the regex used to match the hash comment. The comment looks like this:
// --comment "cali:abcd1234_-".
hashCommentRegexp := regexp.MustCompile(`--comment "?` + hashPrefix + `([a-zA-Z0-9_-]+)"?`)
ourChainsPattern := "^(" + strings.Join(options.HistoricChainPrefixes, "|") + ")"
ourChainsRegexp := regexp.MustCompile(ourChainsPattern)
oldInsertRegexpParts := []string{}
for _, prefix := range options.HistoricChainPrefixes {
part := fmt.Sprintf("(?:-j|--jump) %s", prefix)
oldInsertRegexpParts = append(oldInsertRegexpParts, part)
}
if options.ExtraCleanupRegexPattern != "" {
oldInsertRegexpParts = append(oldInsertRegexpParts,
options.ExtraCleanupRegexPattern)
}
oldInsertPattern := strings.Join(oldInsertRegexpParts, "|")
oldInsertRegexp := regexp.MustCompile(oldInsertPattern)
// Pre-populate the insert table with empty lists for each kernel chain. Ensures that we
// clean up any chains that we hooked on a previous run.
inserts := map[string][]Rule{}
dirtyInserts := set.New()
for _, kernelChain := range tableToKernelChains[name] {
inserts[kernelChain] = []Rule{}
dirtyInserts.Add(kernelChain)
}
var insertMode string
switch options.InsertMode {
case "", "insert":
insertMode = "insert"
case "append":
insertMode = "append"
default:
log.WithField("insertMode", options.InsertMode).Panic("Unknown insert mode")
}
if options.PostWriteInterval <= minPostWriteInterval {
log.WithFields(log.Fields{
"setValue": options.PostWriteInterval,
"default": minPostWriteInterval,
}).Info("PostWriteInterval too small, defaulting.")
options.PostWriteInterval = minPostWriteInterval
}
// Allow override of exec.Command() and time.Sleep() for test purposes.
newCmd := newRealCmd
if options.NewCmdOverride != nil {
newCmd = options.NewCmdOverride
}
sleep := time.Sleep
if options.SleepOverride != nil {
sleep = options.SleepOverride
}
now := time.Now
if options.NowOverride != nil {
now = options.NowOverride
}
lookPath := exec.LookPath
if options.LookPathOverride != nil {
lookPath = options.LookPathOverride
}
table := &Table{
Name: name,
IPVersion: ipVersion,
featureDetector: detector,
chainToInsertedRules: inserts,
dirtyInserts: dirtyInserts,
chainNameToChain: map[string]*Chain{},
dirtyChains: set.New(),
chainToDataplaneHashes: map[string][]string{},
logCxt: log.WithFields(log.Fields{
"ipVersion": ipVersion,
"table": name,
}),
hashCommentPrefix: hashPrefix,
hashCommentRegexp: hashCommentRegexp,
ourChainsRegexp: ourChainsRegexp,
oldInsertRegexp: oldInsertRegexp,
insertMode: insertMode,
// Initialise the write tracking as if we'd just done a write, this will trigger
// us to recheck the dataplane at exponentially increasing intervals at startup.
// Note: if we didn't do this, the calculation logic would need to be modified
// to cope with zero values for these fields.
lastWriteTime: now(),
initialPostWriteInterval: options.PostWriteInterval,
postWriteInterval: options.PostWriteInterval,
refreshInterval: options.RefreshInterval,
calicoXtablesLock: iptablesWriteLock,
lockTimeout: options.LockTimeout,
lockProbeInterval: options.LockProbeInterval,
newCmd: newCmd,
timeSleep: sleep,
timeNow: now,
lookPath: lookPath,
gaugeNumChains: gaugeNumChains.WithLabelValues(fmt.Sprintf("%d", ipVersion), name),
gaugeNumRules: gaugeNumRules.WithLabelValues(fmt.Sprintf("%d", ipVersion), name),
countNumLinesExecuted: countNumLinesExecuted.WithLabelValues(fmt.Sprintf("%d", ipVersion), name),
}
table.restoreInputBuffer.NumLinesWritten = table.countNumLinesExecuted
iptablesVariant := strings.ToLower(options.BackendMode)
if iptablesVariant == "" {
iptablesVariant = "legacy"
}
if iptablesVariant == "nft" {
log.Info("Enabling iptables-in-nftables-mode workarounds.")
table.nftablesMode = true
}
table.iptablesRestoreCmd = table.findBestBinary(ipVersion, iptablesVariant, "restore")
table.iptablesSaveCmd = table.findBestBinary(ipVersion, iptablesVariant, "save")
return table
}
// findBestBinary tries to find an iptables binary for the specific variant (legacy/nftables mode) and returns the name
// of the binary. Falls back on iptables-restore/iptables-save if the specific variant isn't available.
// Panics if no binary can be found.
func (t *Table) findBestBinary(ipVersion uint8, backendMode, saveOrRestore string) string {
verInfix := ""
if ipVersion == 6 {
verInfix = "6"
}
candidates := []string{
"ip" + verInfix + "tables-" + backendMode + "-" + saveOrRestore,
"ip" + verInfix + "tables-" + saveOrRestore,
}
logCxt := log.WithFields(log.Fields{
"ipVersion": ipVersion,
"backendMode": backendMode,
"saveOrRestore": saveOrRestore,
"candidates": candidates,
})
for _, candidate := range candidates {
_, err := t.lookPath(candidate)
if err == nil {
logCxt.WithField("command", candidate).Info("Looked up iptables command")
return candidate
}
}
logCxt.Panic("Failed to find iptables command")
return ""
}
func (t *Table) SetRuleInsertions(chainName string, rules []Rule) {
t.logCxt.WithField("chainName", chainName).Debug("Updating rule insertions")
oldRules := t.chainToInsertedRules[chainName]
t.chainToInsertedRules[chainName] = rules
numRulesDelta := len(rules) - len(oldRules)
t.gaugeNumRules.Add(float64(numRulesDelta))
t.dirtyInserts.Add(chainName)
// Defensive: make sure we re-read the dataplane state before we make updates. While the
// code was originally designed not to need this, we found that other users of
// iptables-restore can still clobber out updates so it's safest to re-read the state before
// each write.
t.InvalidateDataplaneCache("insertion")
}
func (t *Table) UpdateChains(chains []*Chain) {
for _, chain := range chains {
t.UpdateChain(chain)
}
}
func (t *Table) UpdateChain(chain *Chain) {
t.logCxt.WithField("chainName", chain.Name).Info("Queueing update of chain.")
oldNumRules := 0
if oldChain := t.chainNameToChain[chain.Name]; oldChain != nil {
oldNumRules = len(oldChain.Rules)
}
t.chainNameToChain[chain.Name] = chain
numRulesDelta := len(chain.Rules) - oldNumRules
t.gaugeNumRules.Add(float64(numRulesDelta))
t.dirtyChains.Add(chain.Name)
// Defensive: make sure we re-read the dataplane state before we make updates. While the
// code was originally designed not to need this, we found that other users of
// iptables-restore can still clobber out updates so it's safest to re-read the state before
// each write.
t.InvalidateDataplaneCache("chain update")
}
func (t *Table) RemoveChains(chains []*Chain) {
for _, chain := range chains {
t.RemoveChainByName(chain.Name)
}
}
func (t *Table) RemoveChainByName(name string) {
t.logCxt.WithField("chainName", name).Info("Queing deletion of chain.")
if oldChain, known := t.chainNameToChain[name]; known {
t.gaugeNumRules.Sub(float64(len(oldChain.Rules)))
delete(t.chainNameToChain, name)
t.dirtyChains.Add(name)
}
// Defensive: make sure we re-read the dataplane state before we make updates. While the
// code was originally designed not to need this, we found that other users of
// iptables-restore can still clobber out updates so it's safest to re-read the state before
// each write.
t.InvalidateDataplaneCache("chain removal")
}
func (t *Table) loadDataplaneState() {
// Refresh the cache of feature data.
t.featureDetector.RefreshFeatures()
// Load the hashes from the dataplane.
t.logCxt.Info("Loading current iptables state and checking it is correct.")
t.lastReadTime = t.timeNow()
dataplaneHashes := t.getHashesFromDataplane()
// Check that the rules we think we've programmed are still there and mark any inconsistent
// chains for refresh.
for chainName, expectedHashes := range t.chainToDataplaneHashes {
logCxt := t.logCxt.WithField("chainName", chainName)
if t.dirtyChains.Contains(chainName) || t.dirtyInserts.Contains(chainName) {
// Already an update pending for this chain; no point in flagging it as
// out-of-sync.
logCxt.Debug("Skipping known-dirty chain")
continue
}
dpHashes := dataplaneHashes[chainName]
if !t.ourChainsRegexp.MatchString(chainName) {
// Not one of our chains so it may be one that we're inserting rules into.
insertedRules := t.chainToInsertedRules[chainName]
if len(insertedRules) == 0 {
// This chain shouldn't have any inserts, make sure that's the
// case. This case also covers the case where a chain was removed,
// making dpHashes nil.
dataplaneHasInserts := false
for _, hash := range dpHashes {
if hash != "" {
dataplaneHasInserts = true
break
}
}
if dataplaneHasInserts {
logCxt.WithField("actualRuleIDs", dpHashes).Warn(
"Chain had unexpected inserts, marking for resync")
t.dirtyInserts.Add(chainName)
}
continue
}
// Re-calculate the expected rule insertions based on the current length
// of the chain (since other processes may have inserted/removed rules
// from the chain, throwing off the numbers).
expectedHashes, _ = t.expectedHashesForInsertChain(
chainName,
numEmptyStrings(dpHashes),
)
if !reflect.DeepEqual(dpHashes, expectedHashes) {
logCxt.WithFields(log.Fields{
"expectedRuleIDs": expectedHashes,
"actualRuleIDs": dpHashes,
}).Warn("Detected out-of-sync inserts, marking for resync")
t.dirtyInserts.Add(chainName)
}
} else {
// One of our chains, should match exactly.
if !reflect.DeepEqual(dpHashes, expectedHashes) {
logCxt.Warn("Detected out-of-sync Calico chain, marking for resync")
t.dirtyChains.Add(chainName)
}
}
}
// Now scan for chains that shouldn't be there and mark for deletion.
t.logCxt.Debug("Scanning for unexpected iptables chains")
for chainName, dataplaneHashes := range dataplaneHashes {
logCxt := t.logCxt.WithField("chainName", chainName)
if t.dirtyChains.Contains(chainName) || t.dirtyInserts.Contains(chainName) {
// Already an update pending for this chain.
logCxt.Debug("Skipping known-dirty chain")
continue
}
if _, ok := t.chainToDataplaneHashes[chainName]; ok {
// Chain expected, we'll have checked its contents above.
logCxt.Debug("Skipping expected chain")
continue
}
if !t.ourChainsRegexp.MatchString(chainName) {
// Non-calico chain that is not tracked in chainToDataplaneHashes. We
// haven't seen the chain before and we haven't been asked to insert
// anything into it. Check that it doesn't have an rule insertions in it
// from a previous run of Felix.
for _, hash := range dataplaneHashes {
if hash != "" {
logCxt.Info("Found unexpected insert, marking for cleanup")
t.dirtyInserts.Add(chainName)
break
}
}
continue
}
// Chain exists in dataplane but not in memory, mark as dirty so we'll clean it up.
logCxt.Info("Found unexpected chain, marking for cleanup")
t.dirtyChains.Add(chainName)
}
t.logCxt.Debug("Finished loading iptables state")
t.chainToDataplaneHashes = dataplaneHashes
t.inSyncWithDataPlane = true
}
// expectedHashesForInsertChain calculates the expected hashes for a whole top-level chain
// given our inserts. If we're in append mode, that consists of numNonCalicoRules empty strings
// followed by our hashes; in insert mode, the opposite way round. To avoid recalculation, it
// returns the rule hashes as a second output.
func (t *Table) expectedHashesForInsertChain(
chainName string,
numNonCalicoRules int,
) (allHashes, ourHashes []string) {
insertedRules := t.chainToInsertedRules[chainName]
allHashes = make([]string, len(insertedRules)+numNonCalicoRules)
features := t.featureDetector.GetFeatures()
ourHashes = calculateRuleInsertHashes(chainName, insertedRules, features)
offset := 0
if t.insertMode == "append" {
log.Debug("In append mode, returning our hashes at end.")
offset = numNonCalicoRules
}
for i, hash := range ourHashes {
allHashes[i+offset] = hash
}
return
}
// getHashesFromDataplane loads the current state of our table and parses out the hashes that we
// add to rules. It returns a map with an entry for each chain in the table. Each entry is a slice
// containing the hashes for the rules in that table. Rules with no hashes are represented by
// an empty string.
func (t *Table) getHashesFromDataplane() map[string][]string {
retries := 3
retryDelay := 100 * time.Millisecond
// Retry a few times before we panic. This deals with any transient errors and it prevents
// us from spamming a panic into the log when we're being gracefully shut down by a SIGTERM.
for {
hashes, err := t.attemptToGetHashesFromDataplane()
if err != nil {
countNumSaveErrors.Inc()
var stderr string
if ee, ok := err.(*exec.ExitError); ok {
stderr = string(ee.Stderr)
}
t.logCxt.WithError(err).WithField("stderr", stderr).Warnf("%s command failed", t.iptablesSaveCmd)
if retries > 0 {
retries--
t.timeSleep(retryDelay)
retryDelay *= 2
} else {
t.logCxt.Panicf("%s command failed after retries", t.iptablesSaveCmd)
}
continue
}
return hashes
}
}
// attemptToGetHashesFromDataplane starts an iptables-save subprocess and feeds its output to
// readHashesFrom() via a pipe. It handles the various error cases.
func (t *Table) attemptToGetHashesFromDataplane() (hashes map[string][]string, err error) {
cmd := t.newCmd(t.iptablesSaveCmd, "-t", t.Name)
countNumSaveCalls.Inc()
stdout, err := cmd.StdoutPipe()
if err != nil {
log.WithError(err).Warnf("Failed to get stdout pipe for %s", t.iptablesSaveCmd)
return
}
err = cmd.Start()
if err != nil {
// Failed even before we started, close the pipe. (This would normally be done
// by Wait().
log.WithError(err).Warnf("Failed to start %s", t.iptablesSaveCmd)
closeErr := stdout.Close()
if closeErr != nil {
log.WithError(closeErr).Warn("Error closing stdout after Start() failed.")
}
return
}
hashes, err = t.readHashesFrom(stdout)
if err != nil {
// In case readHashesFrom() returned due to an error that didn't cause the
// process to exit, kill it now.
log.WithError(err).Warnf("Killing %s process after a failure", t.iptablesSaveCmd)
killErr := cmd.Kill()
if killErr != nil {
// If we don't know what state the process is in, we can't Wait() on it.
log.WithError(killErr).Panicf(
"Failed to kill %s process after failure.", t.iptablesSaveCmd)
}
}
waitErr := cmd.Wait()
if waitErr != nil {
log.WithError(waitErr).Warn("iptables save failed")
if err == nil {
err = waitErr
}
}
return
}
// readHashesFrom scans the given reader containing iptables-save output for this table, extracting
// our rule hashes. Entries in the returned map are indexed by chain name. For rules that we
// wrote, the hash is extracted from a comment that we added to the rule. For rules written by
// previous versions of Felix, returns a dummy non-zero value. For rules not written by Felix,
// returns a zero string. Hence, the lengths of the returned values are the lengths of the chains
// whether written by Felix or not.
func (t *Table) readHashesFrom(r io.ReadCloser) (hashes map[string][]string, err error) {
hashes = map[string][]string{}
scanner := bufio.NewScanner(r)
// Figure out if debug logging is enabled so we can skip some WithFields() calls in the
// tight loop below if the log wouldn't be emitted anyway.
debug := log.GetLevel() >= log.DebugLevel
for scanner.Scan() {
// Read the next line of the output.
line := scanner.Bytes()
// Look for lines of the form ":chain-name - [0:0]", which are forward declarations
// for (possibly empty) chains.
logCxt := t.logCxt
if debug {
// Avoid stringifying the line (and hence copying it) unless we're at debug
// level.
logCxt = logCxt.WithField("line", string(line))
logCxt.Debug("Parsing line")
}
captures := chainCreateRegexp.FindSubmatch(line)
if captures != nil {
// Chain forward-reference, make sure the chain exists.
chainName := string(captures[1])
if debug {
logCxt.WithField("chainName", chainName).Debug("Found forward-reference")
}
hashes[chainName] = []string{}
continue
}
// Look for append lines, such as "-A chain-name -m foo --foo bar"; these are the
// actual rules.
captures = appendRegexp.FindSubmatch(line)
if captures == nil {
// Skip any non-append lines.
logCxt.Debug("Not an append, skipping")
continue
}
chainName := string(captures[1])
// Look for one of our hashes on the rule. We record a zero hash for unknown rules
// so that they get cleaned up. Note: we're implicitly capturing the first match
// of the regex. When writing the rules, we ensure that the hash is written as the
// first comment.
hash := ""
captures = t.hashCommentRegexp.FindSubmatch(line)
if captures != nil {
hash = string(captures[1])
if debug {
logCxt.WithField("hash", hash).Debug("Found hash in rule")
}
} else if t.oldInsertRegexp.Find(line) != nil {
logCxt.WithFields(log.Fields{
"rule": line,
"chainName": chainName,
}).Info("Found inserted rule from previous Felix version, marking for cleanup.")
hash = "OLD INSERT RULE"
}
hashes[chainName] = append(hashes[chainName], hash)
}
if scanner.Err() != nil {
log.WithError(scanner.Err()).Error("Failed to read hashes from dataplane")
return nil, scanner.Err()
}
t.logCxt.Debugf("Read hashes from dataplane: %#v", hashes)
return hashes, nil
}
func (t *Table) InvalidateDataplaneCache(reason string) {
logCxt := t.logCxt.WithField("reason", reason)
if !t.inSyncWithDataPlane {
logCxt.Debug("Would invalidate dataplane cache but it was already invalid.")
return
}
logCxt.Info("Invalidating dataplane cache")
t.inSyncWithDataPlane = false
}
func (t *Table) Apply() (rescheduleAfter time.Duration) {
now := t.timeNow()
// We _think_ we're in sync, check if there are any reasons to think we might
// not be in sync.
lastReadToNow := now.Sub(t.lastReadTime)
invalidated := false
if t.refreshInterval > 0 && lastReadToNow > t.refreshInterval {
// Too long since we've forced a refresh.
t.InvalidateDataplaneCache("refresh timer")
invalidated = true
}
// To workaround the possibility of another process clobbering our updates, we refresh the
// dataplane after we do a write at exponentially increasing intervals. We do a refresh
// if the delta from the last write to now is twice the delta from the last read.
for t.postWriteInterval != 0 &&
t.postWriteInterval < time.Hour &&
!now.Before(t.lastWriteTime.Add(t.postWriteInterval)) {
t.postWriteInterval *= 2
t.logCxt.WithField("newPostWriteInterval", t.postWriteInterval).Debug("Updating post-write interval")
if !invalidated {
t.InvalidateDataplaneCache("post update")
invalidated = true
}
}
// Retry until we succeed. There are several reasons that updating iptables may fail:
//
// - A concurrent write may invalidate iptables-restore's compare-and-swap; this manifests
// as a failure on the COMMIT line.
// - Another process may have clobbered some of our state, resulting in inconsistencies
// in what we try to program. This could manifest in a number of ways depending on what
// the other process did.
// - Random transient failure.
//
// It's also possible that we're bugged and trying to write bad data so we give up
// eventually.
retries := 10
backoffTime := 1 * time.Millisecond
failedAtLeastOnce := false
for {
if !t.inSyncWithDataPlane {
// We have reason to believe that our picture of the dataplane is out of
// sync. Refresh it. This may mark more chains as dirty.
t.loadDataplaneState()
}
if err := t.applyUpdates(); err != nil {
if retries > 0 {
retries--
t.logCxt.WithError(err).Warn("Failed to program iptables, will retry")
t.timeSleep(backoffTime)
backoffTime *= 2
t.logCxt.WithError(err).Warn("Retrying...")
failedAtLeastOnce = true
continue
} else {
t.logCxt.WithError(err).Error("Failed to program iptables, loading diags before panic.")
cmd := t.newCmd(t.iptablesSaveCmd, "-t", t.Name)
output, err2 := cmd.Output()
if err2 != nil {
t.logCxt.WithError(err2).Error("Failed to load iptables state")
} else {
t.logCxt.WithField("iptablesState", string(output)).Error("Current state of iptables")
}
t.logCxt.WithError(err).Panic("Failed to program iptables, giving up after retries")
}
}
if failedAtLeastOnce {
t.logCxt.Warn("Succeeded after retry.")
}
break
}
t.gaugeNumChains.Set(float64(len(t.chainNameToChain)))
// Check whether we need to be rescheduled and how soon.
if t.refreshInterval > 0 {
// Refresh interval is set, start with that.
lastReadToNow = now.Sub(t.lastReadTime)
rescheduleAfter = t.refreshInterval - lastReadToNow
}
if t.postWriteInterval < time.Hour {
postWriteReched := t.lastWriteTime.Add(t.postWriteInterval).Sub(now)
if postWriteReched <= 0 {
rescheduleAfter = 1 * time.Millisecond
} else if t.refreshInterval <= 0 || postWriteReched < rescheduleAfter {
rescheduleAfter = postWriteReched
}
}
return
}
func (t *Table) applyUpdates() error {
// If needed, detect the dataplane features.
features := t.featureDetector.GetFeatures()
// Build up the iptables-restore input in an in-memory buffer. This allows us to log out the exact input after
// a failure, which has proven to be a very useful diagnostic tool.
buf := &t.restoreInputBuffer
buf.Reset() // Defensive.
// iptables-restore commands live in per-table transactions.
buf.StartTransaction(t.Name)
// Make a pass over the dirty chains and generate a forward reference for any that we're about to update.
// Writing a forward reference ensures that the chain exists and that it is empty.
t.dirtyChains.Iter(func(item interface{}) error {
chainName := item.(string)
chainNeedsToBeFlushed := false
if t.nftablesMode {
// iptables-nft-restore <v1.8.3 has a bug (https://bugzilla.netfilter.org/show_bug.cgi?id=1348)
// where only the first replace command sets the rule index. Work around that by refreshing the
// whole chain using a flush.
chain := t.chainNameToChain[chainName]
currentHashes := chain.RuleHashes(features)
previousHashes := t.chainToDataplaneHashes[chainName]
t.logCxt.WithFields(log.Fields{
"previous": previousHashes,
"current": currentHashes,
}).Debug("Comparing old to new hashes.")
if len(previousHashes) > 0 && reflect.DeepEqual(currentHashes, previousHashes) {
// Chain is already correct, skip it.
log.Debug("Chain already correct")
return set.RemoveItem
}
chainNeedsToBeFlushed = true
} else if _, ok := t.chainNameToChain[chainName]; !ok {
// About to delete this chain, flush it first to sever dependencies.
chainNeedsToBeFlushed = true
} else if _, ok := t.chainToDataplaneHashes[chainName]; !ok {
// Chain doesn't exist in dataplane, mark it for creation.
chainNeedsToBeFlushed = true
}
if chainNeedsToBeFlushed {
buf.WriteForwardReference(chainName)
}
return nil
})
// Make a second pass over the dirty chains. This time, we write out the rule changes.
newHashes := map[string][]string{}
t.dirtyChains.Iter(func(item interface{}) error {
chainName := item.(string)
if chain, ok := t.chainNameToChain[chainName]; ok {
// Chain update or creation. Scan the chain against its previous hashes
// and replace/append/delete as appropriate.
var previousHashes []string
if t.nftablesMode {
// Due to a bug in iptables nft mode, force a whole-chain rewrite. (See above.)
previousHashes = nil
} else {
// In iptables legacy mode, we compare the rules one by one and apply deltas rule by rule.
previousHashes = t.chainToDataplaneHashes[chainName]
}
currentHashes := chain.RuleHashes(features)
newHashes[chainName] = currentHashes
for i := 0; i < len(previousHashes) || i < len(currentHashes); i++ {
var line string
if i < len(previousHashes) && i < len(currentHashes) {
if previousHashes[i] == currentHashes[i] {
continue
}
// Hash doesn't match, replace the rule.
ruleNum := i + 1 // 1-indexed.
prefixFrag := t.commentFrag(currentHashes[i])
line = chain.Rules[i].RenderReplace(chainName, ruleNum, prefixFrag, features)
} else if i < len(previousHashes) {
// previousHashes was longer, remove the old rules from the end.
ruleNum := len(currentHashes) + 1 // 1-indexed
line = deleteRule(chainName, ruleNum)
} else {
// currentHashes was longer. Append.
prefixFrag := t.commentFrag(currentHashes[i])
line = chain.Rules[i].RenderAppend(chainName, prefixFrag, features)
}
buf.WriteLine(line)
}
}
return nil // Delay clearing the set until we've programmed iptables.
})
// Now calculate iptables updates for our inserted rules, which are used to hook top-level chains.
t.dirtyInserts.Iter(func(item interface{}) error {
chainName := item.(string)
previousHashes := t.chainToDataplaneHashes[chainName]
// Calculate the hashes for our inserted rules.
newChainHashes, newRuleHashes := t.expectedHashesForInsertChain(
chainName, numEmptyStrings(previousHashes))
if reflect.DeepEqual(newChainHashes, previousHashes) {
// Chain is in sync, skip to next one.
return nil
}
// For simplicity, if we've discovered that we're out-of-sync, remove all our
// rules from this chain, then re-insert/re-append them below.
//
// Remove in reverse order so that we don't disturb the rule numbers of rules we're
// about to remove.
for i := len(previousHashes) - 1; i >= 0; i-- {
if previousHashes[i] != "" {
ruleNum := i + 1
line := deleteRule(chainName, ruleNum)
buf.WriteLine(line)
}
}
rules := t.chainToInsertedRules[chainName]
if t.insertMode == "insert" {
t.logCxt.Debug("Rendering insert rules.")
// Since each insert is pushed onto the top of the chain, do the inserts in
// reverse order so that they end up in the correct order in the final
// state of the chain.
for i := len(rules) - 1; i >= 0; i-- {
prefixFrag := t.commentFrag(newRuleHashes[i])
line := rules[i].RenderInsert(chainName, prefixFrag, features)
buf.WriteLine(line)
}
} else {
t.logCxt.Debug("Rendering append rules.")
for i := 0; i < len(rules); i++ {
prefixFrag := t.commentFrag(newRuleHashes[i])
line := rules[i].RenderAppend(chainName, prefixFrag, features)
buf.WriteLine(line)
}
}
newHashes[chainName] = newChainHashes
return nil // Delay clearing the set until we've programmed iptables.
})
if t.nftablesMode {
// The nftables version of iptables-restore requires that chains are unreferenced at the start of the
// transaction before they can be deleted (i.e. it doesn't seem to update the reference calculation as
// rules are deleted). Close the current transaction and open a new one for the deletions in order to
// refresh its state. The buffer will discard a no-op transaction so we don't need to check.
t.logCxt.Debug("In nftables mode, restarting transaction between updates and deletions.")
buf.EndTransaction()
buf.StartTransaction(t.Name)
t.dirtyChains.Iter(func(item interface{}) error {
chainName := item.(string)
if _, ok := t.chainNameToChain[chainName]; !ok {
// Chain deletion
buf.WriteForwardReference(chainName)
}
return nil // Delay clearing the set until we've programmed iptables.
})
}
// Do deletions at the end. This ensures that we don't try to delete any chains that
// are still referenced (because we'll have removed the references in the modify pass
// above). Note: if a chain is being deleted at the same time as a chain that it refers to
// then we'll issue a create+flush instruction in the very first pass, which will sever the
// references.
t.dirtyChains.Iter(func(item interface{}) error {
chainName := item.(string)
if _, ok := t.chainNameToChain[chainName]; !ok {
// Chain deletion
buf.WriteLine(fmt.Sprintf("--delete-chain %s", chainName))
newHashes[chainName] = nil
}
return nil // Delay clearing the set until we've programmed iptables.
})
buf.EndTransaction()
if buf.Empty() {
t.logCxt.Debug("Update ended up being no-op, skipping call to ip(6)tables-restore.")
} else {
// Get the contents of the buffer ready to send to iptables-restore. Warning: for perf, this is directly
// accessing the buffer's internal array; don't touch the buffer after this point.
inputBytes := buf.GetBytesAndReset()
if log.GetLevel() >= log.DebugLevel {
// Only convert (potentially very large slice) to string at debug level.
inputStr := string(inputBytes)
t.logCxt.WithField("iptablesInput", inputStr).Debug("Writing to iptables")
}
var outputBuf, errBuf bytes.Buffer
args := []string{"--noflush", "--verbose"}
if features.RestoreSupportsLock {
// Versions of iptables-restore that support the xtables lock also make it impossible to disable. Make
// sure that we configure it to retry and configure for a short retry interval (the default is to try to
// acquire the lock only once).
lockTimeout := t.lockTimeout.Seconds()
if lockTimeout <= 0 {
// Before iptables-restore added lock support, we were able to disable the lock completely, which
// was indicated by a value <=0 (and was our default). Newer versions of iptables-restore require the
// lock so we override the default and set it to 10s.
lockTimeout = 10
}
lockProbeMicros := t.lockProbeInterval.Nanoseconds() / 1000
timeoutStr := fmt.Sprintf("%.0f", lockTimeout)
intervalStr := fmt.Sprintf("%d", lockProbeMicros)
args = append(args,
"--wait", timeoutStr, // seconds
"--wait-interval", intervalStr, // microseconds
)
log.WithFields(log.Fields{
"timeoutSecs": timeoutStr,
"probeIntervalMicros": intervalStr,
}).Debug("Using native iptables-restore xtables lock.")
}
cmd := t.newCmd(t.iptablesRestoreCmd, args...)
cmd.SetStdin(bytes.NewReader(inputBytes))
cmd.SetStdout(&outputBuf)
cmd.SetStderr(&errBuf)
countNumRestoreCalls.Inc()
// Note: calicoXtablesLock will be a dummy lock if our xtables lock is disabled (i.e. if iptables-restore
// supports the xtables lock itself, or if our implementation is disabled by config.
t.calicoXtablesLock.Lock()
err := cmd.Run()
t.calicoXtablesLock.Unlock()
if err != nil {
// To log out the input, we must convert to string here since, after we return, the buffer can be re-used
// (and the logger may convert to string on a background thread).
inputStr := string(inputBytes)
t.logCxt.WithFields(log.Fields{
"output": outputBuf.String(),
"errorOutput": errBuf.String(),
"error": err,
"input": inputStr,
}).Warn("Failed to execute ip(6)tables-restore command")
t.inSyncWithDataPlane = false
countNumRestoreErrors.Inc()
return err
}
t.lastWriteTime = t.timeNow()
t.postWriteInterval = t.initialPostWriteInterval
}
// Now we've successfully updated iptables, clear the dirty sets. We do this even if we
// found there was nothing to do above, since we may have found out that a dirty chain
// was actually a no-op update.
t.dirtyChains = set.New()
t.dirtyInserts = set.New()
// Store off the updates.
for chainName, hashes := range newHashes {
if hashes == nil {
delete(t.chainToDataplaneHashes, chainName)
} else {
t.chainToDataplaneHashes[chainName] = hashes
}
}
return nil
}
func (t *Table) commentFrag(hash string) string {
return fmt.Sprintf(`-m comment --comment "%s%s"`, t.hashCommentPrefix, hash)
}
func deleteRule(chainName string, ruleNum int) string {
return fmt.Sprintf("-D %s %d", chainName, ruleNum)
}
func calculateRuleInsertHashes(chainName string, rules []Rule, features *Features) []string {
chain := Chain{
Name: chainName,
Rules: rules,
}
return (&chain).RuleHashes(features)
}
func numEmptyStrings(strs []string) int {
count := 0
for _, s := range strs {
if s == "" {
count++
}
}
return count
}
| 1 | 17,083 | I don't think this is used any more, please remove. | projectcalico-felix | go |
@@ -219,7 +219,11 @@ def List(inner_type):
super(_List, self).__init__(
key='List.{inner_type}'.format(inner_type=inner_type.key),
name=None,
- description='List of {inner_type}'.format(inner_type=inner_type.name),
+ description=(
+ 'List of {inner_type}'.format(inner_type=inner_type.name)
+ if inner_type.name is not None
+ else 'List of config values'
+ ),
type_attributes=ConfigTypeAttributes(is_builtin=True),
inner_type=inner_type,
) | 1 | from collections import namedtuple
import six
from dagster import check
from .builtin_enum import BuiltinEnum
class ConfigTypeAttributes(namedtuple('_ConfigTypeAttributes', 'is_builtin is_system_config')):
def __new__(cls, is_builtin=False, is_system_config=False):
return super(ConfigTypeAttributes, cls).__new__(
cls,
is_builtin=check.bool_param(is_builtin, 'is_builtin'),
is_system_config=check.bool_param(is_system_config, 'is_system_config'),
)
DEFAULT_TYPE_ATTRIBUTES = ConfigTypeAttributes()
class ConfigType(object):
def __init__(self, key, name, type_attributes=DEFAULT_TYPE_ATTRIBUTES, description=None):
type_obj = type(self)
if type_obj in ConfigType.__cache:
check.failed(
(
'{type_obj} already in cache. You **must** use the inst() class method '
'to construct ConfigTypes and not the ctor'.format(type_obj=type_obj)
)
)
self.key = check.str_param(key, 'key')
self.name = check.opt_str_param(name, 'name')
self.description = check.opt_str_param(description, 'description')
self.type_attributes = check.inst_param(
type_attributes, 'type_attributes', ConfigTypeAttributes
)
__cache = {}
@classmethod
def inst(cls):
if cls not in ConfigType.__cache:
ConfigType.__cache[cls] = cls() # pylint: disable=E1120
return ConfigType.__cache[cls]
@staticmethod
def from_builtin_enum(builtin_enum):
check.inst_param(builtin_enum, 'builtin_enum', BuiltinEnum)
return _CONFIG_MAP[builtin_enum]
@property
def is_system_config(self):
return self.type_attributes.is_system_config
@property
def is_builtin(self):
return self.type_attributes.is_builtin
@property
def has_fields(self):
return self.is_composite or self.is_selector
@property
def is_scalar(self):
return False
@property
def is_list(self):
return False
@property
def is_nullable(self):
return False
@property
def is_composite(self):
return False
@property
def is_selector(self):
return False
@property
def is_any(self):
return False
@property
def inner_types(self):
return []
@property
def is_enum(self):
return False
# Scalars, Composites, Selectors, Lists, Nullable, Any
class ConfigScalar(ConfigType):
@property
def is_scalar(self):
return True
def is_config_scalar_valid(self, _config_value):
check.not_implemented('must implement')
class ConfigList(ConfigType):
def __init__(self, inner_type, *args, **kwargs):
self.inner_type = check.inst_param(inner_type, 'inner_type', ConfigType)
super(ConfigList, self).__init__(*args, **kwargs)
def is_list(self):
return True
@property
def inner_types(self):
return [self.inner_type] + self.inner_type.inner_types
class ConfigNullable(ConfigType):
def __init__(self, inner_type, *args, **kwargs):
self.inner_type = check.inst_param(inner_type, 'inner_type', ConfigType)
super(ConfigNullable, self).__init__(*args, **kwargs)
@property
def is_nullable(self):
return True
@property
def inner_types(self):
return [self.inner_type] + self.inner_type.inner_types
class ConfigAny(ConfigType):
@property
def is_any(self):
return True
class BuiltinConfigScalar(ConfigScalar):
def __init__(self, description=None):
super(BuiltinConfigScalar, self).__init__(
key=type(self).__name__,
name=type(self).__name__,
description=description,
type_attributes=ConfigTypeAttributes(is_builtin=True),
)
class Int(BuiltinConfigScalar):
def __init__(self):
super(Int, self).__init__(description='')
def is_config_scalar_valid(self, config_value):
return not isinstance(config_value, bool) and isinstance(config_value, six.integer_types)
class _StringishBuiltin(BuiltinConfigScalar):
def is_config_scalar_valid(self, config_value):
return isinstance(config_value, six.string_types)
class String(_StringishBuiltin):
def __init__(self):
super(String, self).__init__(description='')
class Path(_StringishBuiltin):
def __init__(self):
super(Path, self).__init__(description='')
class Bool(BuiltinConfigScalar):
def __init__(self):
super(Bool, self).__init__(description='')
def is_config_scalar_valid(self, config_value):
return isinstance(config_value, bool)
class Float(BuiltinConfigScalar):
def __init__(self):
super(Float, self).__init__(description='')
def is_config_scalar_valid(self, config_value):
return isinstance(config_value, float)
class Any(ConfigAny):
def __init__(self):
super(Any, self).__init__(
key='Any', name='Any', type_attributes=ConfigTypeAttributes(is_builtin=True)
)
def Nullable(inner_type):
check.inst_param(inner_type, 'inner_type', ConfigType)
class _Nullable(ConfigNullable):
def __init__(self):
super(_Nullable, self).__init__(
key='Nullable.{inner_type}'.format(inner_type=inner_type.key),
name=None,
type_attributes=ConfigTypeAttributes(is_builtin=True),
inner_type=inner_type,
)
return _Nullable
def List(inner_type):
check.inst_param(inner_type, 'inner_type', ConfigType)
class _List(ConfigList):
def __init__(self):
super(_List, self).__init__(
key='List.{inner_type}'.format(inner_type=inner_type.key),
name=None,
description='List of {inner_type}'.format(inner_type=inner_type.name),
type_attributes=ConfigTypeAttributes(is_builtin=True),
inner_type=inner_type,
)
return _List
class EnumValue:
def __init__(self, config_value, python_value=None, description=None):
self.config_value = check.str_param(config_value, 'config_value')
self.python_value = config_value if python_value is None else python_value
self.description = check.opt_str_param(description, 'description')
class ConfigEnum(ConfigType):
def __init__(self, name, enum_values):
check.str_param(name, 'name')
super(ConfigEnum, self).__init__(key=name, name=name)
self.enum_values = check.list_param(enum_values, 'enum_values', of_type=EnumValue)
self._valid_python_values = {ev.python_value for ev in enum_values}
check.invariant(len(self._valid_python_values) == len(enum_values))
self._valid_config_values = {ev.config_value for ev in enum_values}
check.invariant(len(self._valid_config_values) == len(enum_values))
@property
def config_values(self):
return [ev.config_value for ev in self.enum_values]
@property
def is_enum(self):
return True
def is_valid_config_enum_value(self, config_value):
return config_value in self._valid_config_values
def to_python_value(self, config_value):
for ev in self.enum_values:
if ev.config_value == config_value:
return ev.python_value
check.failed('should never reach this. config_value should be pre-validated')
def Enum(name, enum_values):
class _EnumType(ConfigEnum):
def __init__(self):
super(_EnumType, self).__init__(name=name, enum_values=enum_values)
return _EnumType
_CONFIG_MAP = {
BuiltinEnum.ANY: Any.inst(),
BuiltinEnum.BOOL: Bool.inst(),
BuiltinEnum.FLOAT: Float.inst(),
BuiltinEnum.INT: Int.inst(),
BuiltinEnum.PATH: Path.inst(),
BuiltinEnum.STRING: String.inst(),
}
ALL_CONFIG_BUILTINS = set(_CONFIG_MAP.values())
| 1 | 12,433 | actually use type_name=print_config_type_to_string(self, with_lines=False) to populate this | dagster-io-dagster | py |
@@ -71,6 +71,13 @@ class Import extends QueueWorkerBase implements ContainerFactoryPluginInterface
foreach ($results as $result) {
$queued = $this->processResult($result, $data, $queued);
}
+
+ // Delete local resource file.
+ if ($this->container->get('config.factory')->get('datastore.settings')->get('delete_local_resource')) {
+ $uuid = "{$identifier}_{$version}";
+ $this->container->get('file_system')->deleteRecursive("public://resources/{$uuid}");
+ }
+
}
catch (\Exception $e) {
$this->log(RfcLogLevel::ERROR, | 1 | <?php
namespace Drupal\datastore\Plugin\QueueWorker;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\common\LoggerTrait;
use Procrastinator\Result;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Processes resource import.
*
* @QueueWorker(
* id = "datastore_import",
* title = @Translation("Queue to process datastore import"),
* cron = {"time" = 60}
* )
*/
class Import extends QueueWorkerBase implements ContainerFactoryPluginInterface {
use LoggerTrait;
private $container;
/**
* Inherited.
*
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new Import($configuration, $plugin_id, $plugin_definition, $container);
}
/**
* Constructs a \Drupal\Component\Plugin\PluginBase object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Symfony\Component\DependencyInjection\ContainerInterface $container
* A dependency injection container.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, ContainerInterface $container) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->container = $container;
}
/**
* {@inheritdoc}
*/
public function processItem($data) {
if (is_object($data) && isset($data->data)) {
$data = $data->data;
}
try {
$identifier = $data['identifier'];
$version = $data['version'];
/** @var \Drupal\datastore\Service $datastore */
$datastore = $this->container->get('dkan.datastore.service');
$results = $datastore->import($identifier, FALSE, $version);
$queued = FALSE;
foreach ($results as $result) {
$queued = $this->processResult($result, $data, $queued);
}
}
catch (\Exception $e) {
$this->log(RfcLogLevel::ERROR,
"Import for {$data['identifier']} returned an error: {$e->getMessage()}");
}
}
/**
* Private.
*/
private function processResult(Result $result, $data, $queued = FALSE) {
$identifier = $data['identifier'];
$version = $data['version'];
$uid = "{$identifier}__{$version}";
$level = RfcLogLevel::INFO;
$message = "";
$status = $result->getStatus();
switch ($status) {
case Result::STOPPED:
if (!$queued) {
$newQueueItemId = $this->requeue($data);
$message = "Import for {$uid} is requeueing. (ID:{$newQueueItemId}).";
$queued = TRUE;
}
break;
case Result::IN_PROGRESS:
case Result::ERROR:
$level = RfcLogLevel::ERROR;
$message = "Import for {$uid} returned an error: {$result->getError()}";
break;
case Result::DONE:
$message = "Import for {$uid} completed.";
break;
}
$this->log('dkan', $message, [], $level);
return $queued;
}
/**
* Requeues the job with extra state information.
*
* @param array $data
* Queue data.
*
* @return mixed
* Queue ID or false if unsuccessful.
*
* @todo: Clarify return value. Documentation suggests it should return ID.
*/
protected function requeue(array $data) {
return $this->container->get('queue')
->get($this->getPluginId())
->createItem($data);
}
}
| 1 | 21,026 | We should be using dependency injection here, instead of fetching the config factory at the last minute from the container. That would allow us to more easily overwrite the "delete_local_resource" setting in tests. | GetDKAN-dkan | php |
@@ -21,8 +21,12 @@ import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.json.HealthCheckModule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class HealthCheckServlet extends HttpServlet {
+ private static final Logger LOG = LoggerFactory.getLogger(HealthCheckServlet.class);
+
public static abstract class ContextListener implements ServletContextListener {
/**
* @return the {@link HealthCheckRegistry} to inject into the servlet context. | 1 | package com.codahale.metrics.servlets;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.ExecutorService;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.codahale.metrics.health.HealthCheck;
import com.codahale.metrics.health.HealthCheckFilter;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.json.HealthCheckModule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
public class HealthCheckServlet extends HttpServlet {
public static abstract class ContextListener implements ServletContextListener {
/**
* @return the {@link HealthCheckRegistry} to inject into the servlet context.
*/
protected abstract HealthCheckRegistry getHealthCheckRegistry();
/**
* @return the {@link ExecutorService} to inject into the servlet context, or {@code null}
* if the health checks should be run in the servlet worker thread.
*/
protected ExecutorService getExecutorService() {
// don't use a thread pool by default
return null;
}
/**
* @return the {@link HealthCheckFilter} that shall be used to filter health checks,
* or {@link HealthCheckFilter#ALL} if the default should be used.
*/
protected HealthCheckFilter getHealthCheckFilter() {
return HealthCheckFilter.ALL;
}
@Override
public void contextInitialized(ServletContextEvent event) {
final ServletContext context = event.getServletContext();
context.setAttribute(HEALTH_CHECK_REGISTRY, getHealthCheckRegistry());
context.setAttribute(HEALTH_CHECK_EXECUTOR, getExecutorService());
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// no-op
}
}
public static final String HEALTH_CHECK_REGISTRY = HealthCheckServlet.class.getCanonicalName() + ".registry";
public static final String HEALTH_CHECK_EXECUTOR = HealthCheckServlet.class.getCanonicalName() + ".executor";
public static final String HEALTH_CHECK_FILTER = HealthCheckServlet.class.getCanonicalName() + ".healthCheckFilter";
private static final long serialVersionUID = -8432996484889177321L;
private static final String CONTENT_TYPE = "application/json";
private transient HealthCheckRegistry registry;
private transient ExecutorService executorService;
private transient HealthCheckFilter filter;
private transient ObjectMapper mapper;
public HealthCheckServlet() {
}
public HealthCheckServlet(HealthCheckRegistry registry) {
this.registry = registry;
}
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
final ServletContext context = config.getServletContext();
if (null == registry) {
final Object registryAttr = context.getAttribute(HEALTH_CHECK_REGISTRY);
if (registryAttr instanceof HealthCheckRegistry) {
this.registry = (HealthCheckRegistry) registryAttr;
} else {
throw new ServletException("Couldn't find a HealthCheckRegistry instance.");
}
}
final Object executorAttr = context.getAttribute(HEALTH_CHECK_EXECUTOR);
if (executorAttr instanceof ExecutorService) {
this.executorService = (ExecutorService) executorAttr;
}
final Object filterAttr = context.getAttribute(HEALTH_CHECK_FILTER);
if (filterAttr instanceof HealthCheckFilter) {
filter = (HealthCheckFilter) filterAttr;
}
if (filter == null) {
filter = HealthCheckFilter.ALL;
}
this.mapper = new ObjectMapper().registerModule(new HealthCheckModule());
}
@Override
public void destroy() {
super.destroy();
registry.shutdown();
}
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
final SortedMap<String, HealthCheck.Result> results = runHealthChecks();
resp.setContentType(CONTENT_TYPE);
resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");
if (results.isEmpty()) {
resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
} else {
if (isAllHealthy(results)) {
resp.setStatus(HttpServletResponse.SC_OK);
} else {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
try (OutputStream output = resp.getOutputStream()) {
getWriter(req).writeValue(output, results);
}
}
private ObjectWriter getWriter(HttpServletRequest request) {
final boolean prettyPrint = Boolean.parseBoolean(request.getParameter("pretty"));
if (prettyPrint) {
return mapper.writerWithDefaultPrettyPrinter();
}
return mapper.writer();
}
private SortedMap<String, HealthCheck.Result> runHealthChecks() {
if (executorService == null) {
return registry.runHealthChecks(filter);
}
return registry.runHealthChecks(executorService, filter);
}
private static boolean isAllHealthy(Map<String, HealthCheck.Result> results) {
for (HealthCheck.Result result : results.values()) {
if (!result.isHealthy()) {
return false;
}
}
return true;
}
}
| 1 | 7,373 | everywhere else in the project, `LOGGER` is used | dropwizard-metrics | java |
@@ -10,7 +10,7 @@ OSM = {
MAX_REQUEST_AREA: <%= Settings.max_request_area.to_json %>,
SERVER_PROTOCOL: <%= Settings.server_protocol.to_json %>,
SERVER_URL: <%= Settings.server_url.to_json %>,
- API_VERSION: <%= Settings.api_version.to_json %>,
+ API_VERSION: <%= Settings.api_versions.min_by(&:to_f).to_json %>,
STATUS: <%= Settings.status.to_json %>,
MAX_NOTE_REQUEST_AREA: <%= Settings.max_note_request_area.to_json %>,
OVERPASS_URL: <%= Settings.overpass_url.to_json %>, | 1 | //= depend_on settings.yml
//= depend_on settings.local.yml
//= require querystring
OSM = {
<% if defined?(PIWIK) %>
PIWIK: <%= PIWIK.to_json %>,
<% end %>
MAX_REQUEST_AREA: <%= Settings.max_request_area.to_json %>,
SERVER_PROTOCOL: <%= Settings.server_protocol.to_json %>,
SERVER_URL: <%= Settings.server_url.to_json %>,
API_VERSION: <%= Settings.api_version.to_json %>,
STATUS: <%= Settings.status.to_json %>,
MAX_NOTE_REQUEST_AREA: <%= Settings.max_note_request_area.to_json %>,
OVERPASS_URL: <%= Settings.overpass_url.to_json %>,
NOMINATIM_URL: <%= Settings.nominatim_url.to_json %>,
GRAPHHOPPER_URL: <%= Settings.graphhopper_url.to_json %>,
FOSSGIS_OSRM_URL: <%= Settings.fossgis_osrm_url.to_json %>,
DEFAULT_LOCALE: <%= I18n.default_locale.to_json %>,
<% if Settings.key?(:thunderforest_key) %>
THUNDERFOREST_KEY: <%= Settings.thunderforest_key.to_json %>,
<% end %>
MARKER_GREEN: <%= image_path("marker-green.png").to_json %>,
MARKER_RED: <%= image_path("marker-red.png").to_json %>,
MARKER_ICON: <%= image_path("images/marker-icon.png").to_json %>,
MARKER_ICON_2X: <%= image_path("images/marker-icon-2x.png").to_json %>,
MARKER_SHADOW: <%= image_path("images/marker-shadow.png").to_json %>,
NEW_NOTE_MARKER: <%= image_path("new_note_marker.png").to_json %>,
OPEN_NOTE_MARKER: <%= image_path("open_note_marker.png").to_json %>,
CLOSED_NOTE_MARKER: <%= image_path("closed_note_marker.png").to_json %>,
SEARCHING: <%= image_path("searching.gif").to_json %>,
apiUrl: function (object) {
var url = "/api/" + OSM.API_VERSION + "/" + object.type + "/" + object.id;
if (object.type === "way" || object.type === "relation") {
url += "/full";
} else if (object.version) {
url += "/" + object.version;
}
return url;
},
params: function(search) {
var params = {};
search = (search || window.location.search).replace('?', '').split(/&|;/);
for (var i = 0; i < search.length; ++i) {
var pair = search[i],
j = pair.indexOf('='),
key = pair.slice(0, j),
val = pair.slice(++j);
try {
params[key] = decodeURIComponent(val);
} catch (e) {
// Ignore parse exceptions
}
}
return params;
},
mapParams: function (search) {
var params = OSM.params(search), mapParams = {}, loc, match;
if (params.mlon && params.mlat) {
mapParams.marker = true;
mapParams.mlon = parseFloat(params.mlon);
mapParams.mlat = parseFloat(params.mlat);
}
// Old-style object parameters; still in use for edit links e.g. /edit?way=1234
if (params.node) {
mapParams.object = {type: 'node', id: parseInt(params.node)};
} else if (params.way) {
mapParams.object = {type: 'way', id: parseInt(params.way)};
} else if (params.relation) {
mapParams.object = {type: 'relation', id: parseInt(params.relation)};
}
var hash = OSM.parseHash(location.hash);
// Decide on a map starting position. Various ways of doing this.
if (hash.center) {
mapParams.lon = hash.center.lng;
mapParams.lat = hash.center.lat;
mapParams.zoom = hash.zoom;
} else if (params.bbox) {
var bbox = params.bbox.split(',');
mapParams.bounds = L.latLngBounds(
[parseFloat(bbox[1]), parseFloat(bbox[0])],
[parseFloat(bbox[3]), parseFloat(bbox[2])]);
} else if (params.minlon && params.minlat && params.maxlon && params.maxlat) {
mapParams.bounds = L.latLngBounds(
[parseFloat(params.minlat), parseFloat(params.minlon)],
[parseFloat(params.maxlat), parseFloat(params.maxlon)]);
} else if (params.mlon && params.mlat) {
mapParams.lon = parseFloat(params.mlon);
mapParams.lat = parseFloat(params.mlat);
mapParams.zoom = parseInt(params.zoom || 12);
} else if (loc = $.cookie('_osm_location')) {
loc = loc.split("|");
mapParams.lon = parseFloat(loc[0]);
mapParams.lat = parseFloat(loc[1]);
mapParams.zoom = parseInt(loc[2]);
} else if (OSM.home) {
mapParams.lon = OSM.home.lon;
mapParams.lat = OSM.home.lat;
mapParams.zoom = 10;
} else if (OSM.location) {
mapParams.bounds = L.latLngBounds(
[OSM.location.minlat,
OSM.location.minlon],
[OSM.location.maxlat,
OSM.location.maxlon]);
} else {
mapParams.lon = -0.1;
mapParams.lat = 51.5;
mapParams.zoom = parseInt(params.zoom || 5);
}
mapParams.layers = hash.layers || (loc && loc[3]) || '';
var scale = parseFloat(params.scale);
if (scale > 0) {
mapParams.zoom = Math.log(360.0 / (scale * 512.0)) / Math.log(2.0);
}
return mapParams;
},
parseHash: function(hash) {
var querystring = require("querystring-component"),
args = {};
var i = hash.indexOf('#');
if (i < 0) {
return args;
}
hash = querystring.parse(hash.substr(i + 1));
var map = (hash.map || '').split('/'),
zoom = parseInt(map[0], 10),
lat = parseFloat(map[1]),
lon = parseFloat(map[2]);
if (!isNaN(zoom) && !isNaN(lat) && !isNaN(lon)) {
args.center = new L.LatLng(lat, lon);
args.zoom = zoom;
}
if (hash.layers) {
args.layers = hash.layers;
}
return args;
},
formatHash: function(args) {
var center, zoom, layers;
if (args instanceof L.Map) {
center = args.getCenter();
zoom = args.getZoom();
layers = args.getLayersCode();
} else {
center = args.center || L.latLng(args.lat, args.lon);
zoom = args.zoom;
layers = args.layers || '';
}
center = center.wrap();
layers = layers.replace('M', '');
var precision = OSM.zoomPrecision(zoom),
hash = '#map=' + zoom +
'/' + center.lat.toFixed(precision) +
'/' + center.lng.toFixed(precision);
if (layers) {
hash += '&layers=' + layers;
}
return hash;
},
zoomPrecision: function(zoom) {
return Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2));
},
locationCookie: function(map) {
var center = map.getCenter().wrap(),
zoom = map.getZoom(),
precision = OSM.zoomPrecision(zoom);
return [center.lng.toFixed(precision), center.lat.toFixed(precision), zoom, map.getLayersCode()].join('|');
},
distance: function(latlng1, latlng2) {
var lat1 = latlng1.lat * Math.PI / 180,
lng1 = latlng1.lng * Math.PI / 180,
lat2 = latlng2.lat * Math.PI / 180,
lng2 = latlng2.lng * Math.PI / 180,
latdiff = lat2 - lat1,
lngdiff = lng2 - lng1;
return 6372795 * 2 * Math.asin(
Math.sqrt(
Math.pow(Math.sin(latdiff / 2), 2) +
Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(lngdiff / 2), 2)
));
}
};
| 1 | 12,092 | Why is this value set to "min_by", and what are the implications of it? Does `&:to_f` play nice with semver (e.g. 1.2.0)? | openstreetmap-openstreetmap-website | rb |
@@ -0,0 +1,9 @@
+/**
+ * Setup configuration for Jest
+ * This file includes gloabl settings for the JEST environment.
+ */
+import 'raf/polyfill';
+import { configure } from 'enzyme';
+import Adapter from 'enzyme-adapter-react-16';
+
+configure({ adapter: new Adapter() }); | 1 | 1 | 17,517 | typo --> gloabl | verdaccio-verdaccio | js |
|
@@ -356,6 +356,12 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := context.WithValue(r.Context(), OriginalURLCtxKey, urlCopy)
r = r.WithContext(c)
+ // Setup a replacer for the request that keeps track of placeholder
+ // values across plugins.
+ replacer := NewReplacer(r, nil, "")
+ c = context.WithValue(r.Context(), ReplacerCtxKey, replacer)
+ r = r.WithContext(c)
+
w.Header().Set("Server", caddy.AppName)
status, _ := s.serveHTTP(w, r) | 1 | // Copyright 2015 Light Code Labs, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package httpserver implements an HTTP server on top of Caddy.
package httpserver
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/lucas-clemente/quic-go/h2quic"
"github.com/mholt/caddy"
"github.com/mholt/caddy/caddyhttp/staticfiles"
"github.com/mholt/caddy/caddytls"
)
// Server is the HTTP server implementation.
type Server struct {
Server *http.Server
quicServer *h2quic.Server
listener net.Listener
listenerMu sync.Mutex
sites []*SiteConfig
connTimeout time.Duration // max time to wait for a connection before force stop
tlsGovChan chan struct{} // close to stop the TLS maintenance goroutine
vhosts *vhostTrie
}
// ensure it satisfies the interface
var _ caddy.GracefulServer = new(Server)
var defaultALPN = []string{"h2", "http/1.1"}
// makeTLSConfig extracts TLS settings from each site config to
// build a tls.Config usable in Caddy HTTP servers. The returned
// config will be nil if TLS is disabled for these sites.
func makeTLSConfig(group []*SiteConfig) (*tls.Config, error) {
var tlsConfigs []*caddytls.Config
for i := range group {
if HTTP2 && len(group[i].TLS.ALPN) == 0 {
// if no application-level protocol was configured up to now,
// default to HTTP/2, then HTTP/1.1 if necessary
group[i].TLS.ALPN = defaultALPN
}
tlsConfigs = append(tlsConfigs, group[i].TLS)
}
return caddytls.MakeTLSConfig(tlsConfigs)
}
func getFallbacks(sites []*SiteConfig) []string {
fallbacks := []string{}
for _, sc := range sites {
if sc.FallbackSite {
fallbacks = append(fallbacks, sc.Addr.Host)
}
}
return fallbacks
}
// NewServer creates a new Server instance that will listen on addr
// and will serve the sites configured in group.
func NewServer(addr string, group []*SiteConfig) (*Server, error) {
s := &Server{
Server: makeHTTPServerWithTimeouts(addr, group),
vhosts: newVHostTrie(),
sites: group,
connTimeout: GracefulTimeout,
}
s.vhosts.fallbackHosts = append(s.vhosts.fallbackHosts, getFallbacks(group)...)
s.Server = makeHTTPServerWithHeaderLimit(s.Server, group)
s.Server.Handler = s // this is weird, but whatever
// extract TLS settings from each site config to build
// a tls.Config, which will not be nil if TLS is enabled
tlsConfig, err := makeTLSConfig(group)
if err != nil {
return nil, err
}
s.Server.TLSConfig = tlsConfig
// if TLS is enabled, make sure we prepare the Server accordingly
if s.Server.TLSConfig != nil {
// enable QUIC if desired (requires HTTP/2)
if HTTP2 && QUIC {
s.quicServer = &h2quic.Server{Server: s.Server}
s.Server.Handler = s.wrapWithSvcHeaders(s.Server.Handler)
}
// wrap the HTTP handler with a handler that does MITM detection
tlsh := &tlsHandler{next: s.Server.Handler}
s.Server.Handler = tlsh // this needs to be the "outer" handler when Serve() is called, for type assertion
// when Serve() creates the TLS listener later, that listener should
// be adding a reference the ClientHello info to a map; this callback
// will be sure to clear out that entry when the connection closes.
s.Server.ConnState = func(c net.Conn, cs http.ConnState) {
// when a connection closes or is hijacked, delete its entry
// in the map, because we are done with it.
if tlsh.listener != nil {
if cs == http.StateHijacked || cs == http.StateClosed {
tlsh.listener.helloInfosMu.Lock()
delete(tlsh.listener.helloInfos, c.RemoteAddr().String())
tlsh.listener.helloInfosMu.Unlock()
}
}
}
// As of Go 1.7, if the Server's TLSConfig is not nil, HTTP/2 is enabled only
// if TLSConfig.NextProtos includes the string "h2"
if HTTP2 && len(s.Server.TLSConfig.NextProtos) == 0 {
// some experimenting shows that this NextProtos must have at least
// one value that overlaps with the NextProtos of any other tls.Config
// that is returned from GetConfigForClient; if there is no overlap,
// the connection will fail (as of Go 1.8, Feb. 2017).
s.Server.TLSConfig.NextProtos = defaultALPN
}
}
// Compile custom middleware for every site (enables virtual hosting)
for _, site := range group {
stack := Handler(staticfiles.FileServer{Root: http.Dir(site.Root), Hide: site.HiddenFiles, IndexPages: site.IndexPages})
for i := len(site.middleware) - 1; i >= 0; i-- {
stack = site.middleware[i](stack)
}
site.middlewareChain = stack
s.vhosts.Insert(site.Addr.VHost(), site)
}
return s, nil
}
// makeHTTPServerWithHeaderLimit apply minimum header limit within a group to given http.Server
func makeHTTPServerWithHeaderLimit(s *http.Server, group []*SiteConfig) *http.Server {
var min int64
for _, cfg := range group {
limit := cfg.Limits.MaxRequestHeaderSize
if limit == 0 {
continue
}
// not set yet
if min == 0 {
min = limit
}
// find a better one
if limit < min {
min = limit
}
}
if min > 0 {
s.MaxHeaderBytes = int(min)
}
return s
}
// makeHTTPServerWithTimeouts makes an http.Server from the group of
// configs in a way that configures timeouts (or, if not set, it uses
// the default timeouts) by combining the configuration of each
// SiteConfig in the group. (Timeouts are important for mitigating
// slowloris attacks.)
func makeHTTPServerWithTimeouts(addr string, group []*SiteConfig) *http.Server {
// find the minimum duration configured for each timeout
var min Timeouts
for _, cfg := range group {
if cfg.Timeouts.ReadTimeoutSet &&
(!min.ReadTimeoutSet || cfg.Timeouts.ReadTimeout < min.ReadTimeout) {
min.ReadTimeoutSet = true
min.ReadTimeout = cfg.Timeouts.ReadTimeout
}
if cfg.Timeouts.ReadHeaderTimeoutSet &&
(!min.ReadHeaderTimeoutSet || cfg.Timeouts.ReadHeaderTimeout < min.ReadHeaderTimeout) {
min.ReadHeaderTimeoutSet = true
min.ReadHeaderTimeout = cfg.Timeouts.ReadHeaderTimeout
}
if cfg.Timeouts.WriteTimeoutSet &&
(!min.WriteTimeoutSet || cfg.Timeouts.WriteTimeout < min.WriteTimeout) {
min.WriteTimeoutSet = true
min.WriteTimeout = cfg.Timeouts.WriteTimeout
}
if cfg.Timeouts.IdleTimeoutSet &&
(!min.IdleTimeoutSet || cfg.Timeouts.IdleTimeout < min.IdleTimeout) {
min.IdleTimeoutSet = true
min.IdleTimeout = cfg.Timeouts.IdleTimeout
}
}
// for the values that were not set, use defaults
if !min.ReadTimeoutSet {
min.ReadTimeout = defaultTimeouts.ReadTimeout
}
if !min.ReadHeaderTimeoutSet {
min.ReadHeaderTimeout = defaultTimeouts.ReadHeaderTimeout
}
if !min.WriteTimeoutSet {
min.WriteTimeout = defaultTimeouts.WriteTimeout
}
if !min.IdleTimeoutSet {
min.IdleTimeout = defaultTimeouts.IdleTimeout
}
// set the final values on the server and return it
return &http.Server{
Addr: addr,
ReadTimeout: min.ReadTimeout,
ReadHeaderTimeout: min.ReadHeaderTimeout,
WriteTimeout: min.WriteTimeout,
IdleTimeout: min.IdleTimeout,
}
}
func (s *Server) wrapWithSvcHeaders(previousHandler http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s.quicServer.SetQuicHeaders(w.Header())
previousHandler.ServeHTTP(w, r)
}
}
// Listen creates an active listener for s that can be
// used to serve requests.
func (s *Server) Listen() (net.Listener, error) {
if s.Server == nil {
return nil, fmt.Errorf("Server field is nil")
}
ln, err := net.Listen("tcp", s.Server.Addr)
if err != nil {
var succeeded bool
if runtime.GOOS == "windows" {
// Windows has been known to keep sockets open even after closing the listeners.
// Tests reveal this error case easily because they call Start() then Stop()
// in succession. TODO: Better way to handle this? And why limit this to Windows?
for i := 0; i < 20; i++ {
time.Sleep(100 * time.Millisecond)
ln, err = net.Listen("tcp", s.Server.Addr)
if err == nil {
succeeded = true
break
}
}
}
if !succeeded {
return nil, err
}
}
if tcpLn, ok := ln.(*net.TCPListener); ok {
ln = tcpKeepAliveListener{TCPListener: tcpLn}
}
cln := ln.(caddy.Listener)
for _, site := range s.sites {
for _, m := range site.listenerMiddleware {
cln = m(cln)
}
}
// Very important to return a concrete caddy.Listener
// implementation for graceful restarts.
return cln.(caddy.Listener), nil
}
// ListenPacket creates udp connection for QUIC if it is enabled,
func (s *Server) ListenPacket() (net.PacketConn, error) {
if QUIC {
udpAddr, err := net.ResolveUDPAddr("udp", s.Server.Addr)
if err != nil {
return nil, err
}
return net.ListenUDP("udp", udpAddr)
}
return nil, nil
}
// Serve serves requests on ln. It blocks until ln is closed.
func (s *Server) Serve(ln net.Listener) error {
s.listenerMu.Lock()
s.listener = ln
s.listenerMu.Unlock()
if s.Server.TLSConfig != nil {
// Create TLS listener - note that we do not replace s.listener
// with this TLS listener; tls.listener is unexported and does
// not implement the File() method we need for graceful restarts
// on POSIX systems.
// TODO: Is this ^ still relevant anymore? Maybe we can now that it's a net.Listener...
ln = newTLSListener(ln, s.Server.TLSConfig)
if handler, ok := s.Server.Handler.(*tlsHandler); ok {
handler.listener = ln.(*tlsHelloListener)
}
// Rotate TLS session ticket keys
s.tlsGovChan = caddytls.RotateSessionTicketKeys(s.Server.TLSConfig)
}
err := s.Server.Serve(ln)
if s.quicServer != nil {
s.quicServer.Close()
}
return err
}
// ServePacket serves QUIC requests on pc until it is closed.
func (s *Server) ServePacket(pc net.PacketConn) error {
if s.quicServer != nil {
err := s.quicServer.Serve(pc.(*net.UDPConn))
return fmt.Errorf("serving QUIC connections: %v", err)
}
return nil
}
// ServeHTTP is the entry point of all HTTP requests.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
// We absolutely need to be sure we stay alive up here,
// even though, in theory, the errors middleware does this.
if rec := recover(); rec != nil {
log.Printf("[PANIC] %v", rec)
DefaultErrorFunc(w, r, http.StatusInternalServerError)
}
}()
// copy the original, unchanged URL into the context
// so it can be referenced by middlewares
urlCopy := *r.URL
if r.URL.User != nil {
userInfo := new(url.Userinfo)
*userInfo = *r.URL.User
urlCopy.User = userInfo
}
c := context.WithValue(r.Context(), OriginalURLCtxKey, urlCopy)
r = r.WithContext(c)
w.Header().Set("Server", caddy.AppName)
status, _ := s.serveHTTP(w, r)
// Fallback error response in case error handling wasn't chained in
if status >= 400 {
DefaultErrorFunc(w, r, status)
}
}
func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
// strip out the port because it's not used in virtual
// hosting; the port is irrelevant because each listener
// is on a different port.
hostname, _, err := net.SplitHostPort(r.Host)
if err != nil {
hostname = r.Host
}
// look up the virtualhost; if no match, serve error
vhost, pathPrefix := s.vhosts.Match(hostname + r.URL.Path)
c := context.WithValue(r.Context(), caddy.CtxKey("path_prefix"), pathPrefix)
r = r.WithContext(c)
if vhost == nil {
// check for ACME challenge even if vhost is nil;
// could be a new host coming online soon
if caddytls.HTTPChallengeHandler(w, r, "localhost", caddytls.DefaultHTTPAlternatePort) {
return 0, nil
}
// otherwise, log the error and write a message to the client
remoteHost, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
remoteHost = r.RemoteAddr
}
WriteSiteNotFound(w, r) // don't add headers outside of this function
log.Printf("[INFO] %s - No such site at %s (Remote: %s, Referer: %s)",
hostname, s.Server.Addr, remoteHost, r.Header.Get("Referer"))
return 0, nil
}
// we still check for ACME challenge if the vhost exists,
// because we must apply its HTTP challenge config settings
if s.proxyHTTPChallenge(vhost, w, r) {
return 0, nil
}
// trim the path portion of the site address from the beginning of
// the URL path, so a request to example.com/foo/blog on the site
// defined as example.com/foo appears as /blog instead of /foo/blog.
if pathPrefix != "/" {
r.URL.Path = strings.TrimPrefix(r.URL.Path, pathPrefix)
if !strings.HasPrefix(r.URL.Path, "/") {
r.URL.Path = "/" + r.URL.Path
}
}
return vhost.middlewareChain.ServeHTTP(w, r)
}
// proxyHTTPChallenge solves the ACME HTTP challenge if r is the HTTP
// request for the challenge. If it is, and if the request has been
// fulfilled (response written), true is returned; false otherwise.
// If you don't have a vhost, just call the challenge handler directly.
func (s *Server) proxyHTTPChallenge(vhost *SiteConfig, w http.ResponseWriter, r *http.Request) bool {
if vhost.Addr.Port != caddytls.HTTPChallengePort {
return false
}
if vhost.TLS != nil && vhost.TLS.Manual {
return false
}
altPort := caddytls.DefaultHTTPAlternatePort
if vhost.TLS != nil && vhost.TLS.AltHTTPPort != "" {
altPort = vhost.TLS.AltHTTPPort
}
return caddytls.HTTPChallengeHandler(w, r, vhost.ListenHost, altPort)
}
// Address returns the address s was assigned to listen on.
func (s *Server) Address() string {
return s.Server.Addr
}
// Stop stops s gracefully (or forcefully after timeout) and
// closes its listener.
func (s *Server) Stop() error {
ctx, cancel := context.WithTimeout(context.Background(), s.connTimeout)
defer cancel()
err := s.Server.Shutdown(ctx)
if err != nil {
return err
}
// signal any TLS governor goroutines to exit
if s.tlsGovChan != nil {
close(s.tlsGovChan)
}
return nil
}
// OnStartupComplete lists the sites served by this server
// and any relevant information, assuming caddy.Quiet == false.
func (s *Server) OnStartupComplete() {
if caddy.Quiet {
return
}
for _, site := range s.sites {
output := site.Addr.String()
if caddy.IsLoopback(s.Address()) && !caddy.IsLoopback(site.Addr.Host) {
output += " (only accessible on this machine)"
}
fmt.Println(output)
log.Println(output)
}
}
// defaultTimeouts stores the default timeout values to use
// if left unset by user configuration. NOTE: Most default
// timeouts are disabled (see issues #1464 and #1733).
var defaultTimeouts = Timeouts{IdleTimeout: 5 * time.Minute}
// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
// connections. It's used by ListenAndServe and ListenAndServeTLS so
// dead TCP connections (e.g. closing laptop mid-download) eventually
// go away.
//
// Borrowed from the Go standard library.
type tcpKeepAliveListener struct {
*net.TCPListener
}
// Accept accepts the connection with a keep-alive enabled.
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
tc, err := ln.AcceptTCP()
if err != nil {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}
// File implements caddy.Listener; it returns the underlying file of the listener.
func (ln tcpKeepAliveListener) File() (*os.File, error) {
return ln.TCPListener.File()
}
// ErrMaxBytesExceeded is the error returned by MaxBytesReader
// when the request body exceeds the limit imposed
var ErrMaxBytesExceeded = errors.New("http: request body too large")
// DefaultErrorFunc responds to an HTTP request with a simple description
// of the specified HTTP status code.
func DefaultErrorFunc(w http.ResponseWriter, r *http.Request, status int) {
WriteTextResponse(w, status, fmt.Sprintf("%d %s\n", status, http.StatusText(status)))
}
const httpStatusMisdirectedRequest = 421 // RFC 7540, 9.1.2
// WriteSiteNotFound writes appropriate error code to w, signaling that
// requested host is not served by Caddy on a given port.
func WriteSiteNotFound(w http.ResponseWriter, r *http.Request) {
status := http.StatusNotFound
if r.ProtoMajor >= 2 {
// TODO: use http.StatusMisdirectedRequest when it gets defined
status = httpStatusMisdirectedRequest
}
WriteTextResponse(w, status, fmt.Sprintf("%d Site %s is not served on this interface\n", status, r.Host))
}
// WriteTextResponse writes body with code status to w. The body will
// be interpreted as plain text.
func WriteTextResponse(w http.ResponseWriter, status int, body string) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
w.Write([]byte(body))
}
// SafePath joins siteRoot and reqPath and converts it to a path that can
// be used to access a path on the local disk. It ensures the path does
// not traverse outside of the site root.
//
// If opening a file, use http.Dir instead.
func SafePath(siteRoot, reqPath string) string {
reqPath = filepath.ToSlash(reqPath)
reqPath = strings.Replace(reqPath, "\x00", "", -1) // NOTE: Go 1.9 checks for null bytes in the syscall package
if siteRoot == "" {
siteRoot = "."
}
return filepath.Join(siteRoot, filepath.FromSlash(path.Clean("/"+reqPath)))
}
// OriginalURLCtxKey is the key for accessing the original, incoming URL on an HTTP request.
const OriginalURLCtxKey = caddy.CtxKey("original_url")
| 1 | 11,647 | Wanted to double-check: does the `log` middleware still set its own "empty" value (should default to `-` at least for the default log format)? | caddyserver-caddy | go |
@@ -273,7 +273,7 @@ public class HttpCommandExecutor implements CommandExecutor, NeedsLocalLogs {
}
if (!GET_ALL_SESSIONS.equals(command.getName())
&& !NEW_SESSION.equals(command.getName())) {
- throw new SessionNotFoundException("Session ID is null");
+ throw new SessionNotFoundException("Session ID is null. Using WebDriver after calling quit()?");
}
}
| 1 | /*
Copyright 2007-2011 Selenium committers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.remote;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NoHttpResponseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.openqa.selenium.UnsupportedCommandException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.logging.LocalLogs;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.NeedsLocalLogs;
import org.openqa.selenium.logging.profiler.HttpProfilerLogEntry;
import org.openqa.selenium.remote.internal.HttpClientFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.BindException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;
import static org.apache.http.protocol.ExecutionContext.HTTP_TARGET_HOST;
import static org.openqa.selenium.remote.DriverCommand.*;
public class HttpCommandExecutor implements CommandExecutor, NeedsLocalLogs {
private static final int MAX_REDIRECTS = 10;
private final HttpHost targetHost;
private final URL remoteServer;
private final Map<String, CommandInfo> nameToUrl;
private final HttpClient client;
private final ErrorCodes errorCodes = new ErrorCodes();
private static HttpClientFactory httpClientFactory;
private LocalLogs logs = LocalLogs.getNullLogger();
public HttpCommandExecutor(URL addressOfRemoteServer) {
this(ImmutableMap.<String, CommandInfo>of(), addressOfRemoteServer);
}
public HttpCommandExecutor(Map<String, CommandInfo> additionalCommands, URL addressOfRemoteServer) {
try {
remoteServer = addressOfRemoteServer == null ?
new URL(System.getProperty("webdriver.remote.server", "http://localhost:4444/wd/hub")) :
addressOfRemoteServer;
} catch (MalformedURLException e) {
throw new WebDriverException(e);
}
HttpParams params = new BasicHttpParams();
// Use the JRE default for the socket linger timeout.
params.setParameter(CoreConnectionPNames.SO_LINGER, -1);
HttpClientParams.setRedirecting(params, false);
synchronized (HttpCommandExecutor.class) {
if (httpClientFactory == null) {
httpClientFactory = new HttpClientFactory();
}
}
client = httpClientFactory.getHttpClient();
if (addressOfRemoteServer != null && addressOfRemoteServer.getUserInfo() != null) {
// Use HTTP Basic auth
UsernamePasswordCredentials credentials = new
UsernamePasswordCredentials(addressOfRemoteServer.getUserInfo());
((DefaultHttpClient) client).getCredentialsProvider().
setCredentials(AuthScope.ANY, credentials);
}
// Some machines claim "localhost.localdomain" is the same as "localhost".
// This assumption is not always true.
String host = remoteServer.getHost().replace(".localdomain", "");
targetHost = new HttpHost(
host, remoteServer.getPort(), remoteServer.getProtocol());
ImmutableMap.Builder<String, CommandInfo> builder = ImmutableMap.builder();
for (Map.Entry<String, CommandInfo> entry : additionalCommands.entrySet()) {
builder.put(entry.getKey(), entry.getValue());
}
builder
.put(GET_ALL_SESSIONS, get("/sessions"))
.put(NEW_SESSION, post("/session"))
.put(GET_CAPABILITIES, get("/session/:sessionId"))
.put(QUIT, delete("/session/:sessionId"))
.put(GET_CURRENT_WINDOW_HANDLE, get("/session/:sessionId/window_handle"))
.put(GET_WINDOW_HANDLES, get("/session/:sessionId/window_handles"))
.put(GET, post("/session/:sessionId/url"))
// The Alert API is still experimental and should not be used.
.put(GET_ALERT, get("/session/:sessionId/alert"))
.put(DISMISS_ALERT, post("/session/:sessionId/dismiss_alert"))
.put(ACCEPT_ALERT, post("/session/:sessionId/accept_alert"))
.put(GET_ALERT_TEXT, get("/session/:sessionId/alert_text"))
.put(SET_ALERT_VALUE, post("/session/:sessionId/alert_text"))
.put(GO_FORWARD, post("/session/:sessionId/forward"))
.put(GO_BACK, post("/session/:sessionId/back"))
.put(REFRESH, post("/session/:sessionId/refresh"))
.put(EXECUTE_SCRIPT, post("/session/:sessionId/execute"))
.put(EXECUTE_ASYNC_SCRIPT, post("/session/:sessionId/execute_async"))
.put(GET_CURRENT_URL, get("/session/:sessionId/url"))
.put(GET_TITLE, get("/session/:sessionId/title"))
.put(GET_PAGE_SOURCE, get("/session/:sessionId/source"))
.put(SCREENSHOT, get("/session/:sessionId/screenshot"))
.put(SET_BROWSER_VISIBLE, post("/session/:sessionId/visible"))
.put(IS_BROWSER_VISIBLE, get("/session/:sessionId/visible"))
.put(FIND_ELEMENT, post("/session/:sessionId/element"))
.put(FIND_ELEMENTS, post("/session/:sessionId/elements"))
.put(GET_ACTIVE_ELEMENT, post("/session/:sessionId/element/active"))
.put(FIND_CHILD_ELEMENT, post("/session/:sessionId/element/:id/element"))
.put(FIND_CHILD_ELEMENTS, post("/session/:sessionId/element/:id/elements"))
.put(CLICK_ELEMENT, post("/session/:sessionId/element/:id/click"))
.put(CLEAR_ELEMENT, post("/session/:sessionId/element/:id/clear"))
.put(SUBMIT_ELEMENT, post("/session/:sessionId/element/:id/submit"))
.put(GET_ELEMENT_TEXT, get("/session/:sessionId/element/:id/text"))
.put(SEND_KEYS_TO_ELEMENT, post("/session/:sessionId/element/:id/value"))
.put(UPLOAD_FILE, post("/session/:sessionId/file"))
.put(GET_ELEMENT_VALUE, get("/session/:sessionId/element/:id/value"))
.put(GET_ELEMENT_TAG_NAME, get("/session/:sessionId/element/:id/name"))
.put(IS_ELEMENT_SELECTED, get("/session/:sessionId/element/:id/selected"))
.put(IS_ELEMENT_ENABLED, get("/session/:sessionId/element/:id/enabled"))
.put(IS_ELEMENT_DISPLAYED, get("/session/:sessionId/element/:id/displayed"))
.put(HOVER_OVER_ELEMENT, post("/session/:sessionId/element/:id/hover"))
.put(GET_ELEMENT_LOCATION, get("/session/:sessionId/element/:id/location"))
.put(GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW,
get("/session/:sessionId/element/:id/location_in_view"))
.put(GET_ELEMENT_SIZE, get("/session/:sessionId/element/:id/size"))
.put(GET_ELEMENT_ATTRIBUTE, get("/session/:sessionId/element/:id/attribute/:name"))
.put(ELEMENT_EQUALS, get("/session/:sessionId/element/:id/equals/:other"))
.put(GET_ALL_COOKIES, get("/session/:sessionId/cookie"))
.put(ADD_COOKIE, post("/session/:sessionId/cookie"))
.put(DELETE_ALL_COOKIES, delete("/session/:sessionId/cookie"))
.put(DELETE_COOKIE, delete("/session/:sessionId/cookie/:name"))
.put(SWITCH_TO_FRAME, post("/session/:sessionId/frame"))
.put(SWITCH_TO_WINDOW, post("/session/:sessionId/window"))
.put(GET_WINDOW_SIZE, get("/session/:sessionId/window/:windowHandle/size"))
.put(GET_WINDOW_POSITION, get("/session/:sessionId/window/:windowHandle/position"))
.put(SET_WINDOW_SIZE, post("/session/:sessionId/window/:windowHandle/size"))
.put(SET_WINDOW_POSITION, post("/session/:sessionId/window/:windowHandle/position"))
.put(MAXIMIZE_WINDOW, post("/session/:sessionId/window/:windowHandle/maximize"))
.put(CLOSE, delete("/session/:sessionId/window"))
.put(DRAG_ELEMENT, post("/session/:sessionId/element/:id/drag"))
.put(GET_ELEMENT_VALUE_OF_CSS_PROPERTY,
get("/session/:sessionId/element/:id/css/:propertyName"))
.put(IMPLICITLY_WAIT, post("/session/:sessionId/timeouts/implicit_wait"))
.put(SET_SCRIPT_TIMEOUT, post("/session/:sessionId/timeouts/async_script"))
.put(SET_TIMEOUT, post("/session/:sessionId/timeouts"))
.put(EXECUTE_SQL, post("/session/:sessionId/execute_sql"))
.put(GET_LOCATION, get("/session/:sessionId/location"))
.put(SET_LOCATION, post("/session/:sessionId/location"))
.put(GET_APP_CACHE_STATUS, get("/session/:sessionId/application_cache/status"))
.put(IS_BROWSER_ONLINE, get("/session/:sessionId/browser_connection"))
.put(SET_BROWSER_ONLINE, post("/session/:sessionId/browser_connection"))
// TODO (user): Would it be better to combine this command with
// GET_LOCAL_STORAGE_SIZE?
.put(GET_LOCAL_STORAGE_ITEM, get("/session/:sessionId/local_storage/key/:key"))
.put(REMOVE_LOCAL_STORAGE_ITEM, delete("/session/:sessionId/local_storage/key/:key"))
.put(GET_LOCAL_STORAGE_KEYS, get("/session/:sessionId/local_storage"))
.put(SET_LOCAL_STORAGE_ITEM, post("/session/:sessionId/local_storage"))
.put(CLEAR_LOCAL_STORAGE, delete("/session/:sessionId/local_storage"))
.put(GET_LOCAL_STORAGE_SIZE, get("/session/:sessionId/local_storage/size"))
// TODO (user): Would it be better to combine this command with
// GET_SESSION_STORAGE_SIZE?
.put(GET_SESSION_STORAGE_ITEM, get("/session/:sessionId/session_storage/key/:key"))
.put(REMOVE_SESSION_STORAGE_ITEM, delete("/session/:sessionId/session_storage/key/:key"))
.put(GET_SESSION_STORAGE_KEYS, get("/session/:sessionId/session_storage"))
.put(SET_SESSION_STORAGE_ITEM, post("/session/:sessionId/session_storage"))
.put(CLEAR_SESSION_STORAGE, delete("/session/:sessionId/session_storage"))
.put(GET_SESSION_STORAGE_SIZE, get("/session/:sessionId/session_storage/size"))
.put(GET_SCREEN_ORIENTATION, get("/session/:sessionId/orientation"))
.put(SET_SCREEN_ORIENTATION, post("/session/:sessionId/orientation"))
// Interactions-related commands.
.put(CLICK, post("/session/:sessionId/click"))
.put(DOUBLE_CLICK, post("/session/:sessionId/doubleclick"))
.put(MOUSE_DOWN, post("/session/:sessionId/buttondown"))
.put(MOUSE_UP, post("/session/:sessionId/buttonup"))
.put(MOVE_TO, post("/session/:sessionId/moveto"))
.put(SEND_KEYS_TO_ACTIVE_ELEMENT, post("/session/:sessionId/keys"))
// IME related commands.
.put(IME_GET_AVAILABLE_ENGINES, get("/session/:sessionId/ime/available_engines"))
.put(IME_GET_ACTIVE_ENGINE, get("/session/:sessionId/ime/active_engine"))
.put(IME_IS_ACTIVATED, get("/session/:sessionId/ime/activated"))
.put(IME_DEACTIVATE, post("/session/:sessionId/ime/deactivate"))
.put(IME_ACTIVATE_ENGINE, post("/session/:sessionId/ime/activate"))
// Advanced Touch API commands
// TODO(berrada): Refactor single tap with mouse click.
.put(TOUCH_SINGLE_TAP, post("/session/:sessionId/touch/click"))
.put(TOUCH_DOWN, post("/session/:sessionId/touch/down"))
.put(TOUCH_UP, post("/session/:sessionId/touch/up"))
.put(TOUCH_MOVE, post("/session/:sessionId/touch/move"))
.put(TOUCH_SCROLL, post("/session/:sessionId/touch/scroll"))
.put(TOUCH_DOUBLE_TAP, post("/session/:sessionId/touch/doubleclick"))
.put(TOUCH_LONG_PRESS, post("/session/:sessionId/touch/longclick"))
.put(TOUCH_FLICK, post("/session/:sessionId/touch/flick"))
.put(GET_LOG, post("/session/:sessionId/log"))
.put(GET_AVAILABLE_LOG_TYPES, get("/session/:sessionId/log/types"))
.put(STATUS, get("/status"));
nameToUrl = builder.build();
}
public void setLocalLogs(LocalLogs logs) {
this.logs = logs;
}
private void log(String logType, LogEntry entry) {
logs.addEntry(logType, entry);
}
public URL getAddressOfRemoteServer() {
return remoteServer;
}
public Response execute(Command command) throws IOException {
HttpContext context = new BasicHttpContext();
if (command.getSessionId() == null) {
if (QUIT.equals(command.getName())) {
return new Response();
}
if (!GET_ALL_SESSIONS.equals(command.getName())
&& !NEW_SESSION.equals(command.getName())) {
throw new SessionNotFoundException("Session ID is null");
}
}
CommandInfo info = nameToUrl.get(command.getName());
try {
HttpUriRequest httpMethod = info.getMethod(remoteServer, command);
setAcceptHeader(httpMethod);
if (httpMethod instanceof HttpPost) {
String payload = new BeanToJsonConverter().convert(command.getParameters());
((HttpPost) httpMethod).setEntity(new StringEntity(payload, "utf-8"));
httpMethod.addHeader("Content-Type", "application/json; charset=utf-8");
}
// Do not allow web proxy caches to cache responses to "get" commands
if (httpMethod instanceof HttpGet) {
httpMethod.addHeader("Cache-Control", "no-cache");
}
log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), true));
HttpResponse response = fallBackExecute(context, httpMethod);
log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), false));
response = followRedirects(client, context, response, /* redirect count */0);
final EntityWithEncoding entityWithEncoding = new EntityWithEncoding(response.getEntity());
return createResponse(response, context, entityWithEncoding);
} catch (UnsupportedCommandException e) {
if (e.getMessage() == null || "".equals(e.getMessage())) {
throw new UnsupportedOperationException(
"No information from server. Command name was: " + command.getName(),
e.getCause());
}
throw e;
}
}
private HttpResponse fallBackExecute(HttpContext context, HttpUriRequest httpMethod)
throws IOException {
try {
return client.execute(targetHost, httpMethod, context);
} catch (BindException e) {
// If we get this, there's a chance we've used all the local ephemeral sockets
// Sleep for a bit to let the OS reclaim them, then try the request again.
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
throw Throwables.propagate(ie);
}
} catch (NoHttpResponseException e) {
// If we get this, there's a chance we've used all the remote ephemeral sockets
// Sleep for a bit to let the OS reclaim them, then try the request again.
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
throw Throwables.propagate(ie);
}
}
return client.execute(targetHost, httpMethod, context);
}
private void setAcceptHeader(HttpUriRequest httpMethod) {
httpMethod.addHeader("Accept", "application/json, image/png");
}
private HttpResponse followRedirects(
HttpClient client, HttpContext context, HttpResponse response, int redirectCount) {
if (!isRedirect(response)) {
return response;
}
try {
// Make sure that the previous connection is freed.
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
EntityUtils.consume(httpEntity);
}
} catch (IOException e) {
throw new WebDriverException(e);
}
if (redirectCount > MAX_REDIRECTS) {
throw new WebDriverException("Maximum number of redirects exceeded. Aborting");
}
String location = response.getFirstHeader("location").getValue();
URI uri;
try {
uri = buildUri(context, location);
HttpGet get = new HttpGet(uri);
setAcceptHeader(get);
HttpResponse newResponse = client.execute(targetHost, get, context);
return followRedirects(client, context, newResponse, redirectCount + 1);
} catch (URISyntaxException e) {
throw new WebDriverException(e);
} catch (ClientProtocolException e) {
throw new WebDriverException(e);
} catch (IOException e) {
throw new WebDriverException(e);
}
}
private URI buildUri(HttpContext context, String location) throws URISyntaxException {
URI uri;
uri = new URI(location);
if (!uri.isAbsolute()) {
HttpHost host = (HttpHost) context.getAttribute(HTTP_TARGET_HOST);
uri = new URI(host.toURI() + location);
}
return uri;
}
private boolean isRedirect(HttpResponse response) {
int code = response.getStatusLine().getStatusCode();
return (code == 301 || code == 302 || code == 303 || code == 307)
&& response.containsHeader("location");
}
class EntityWithEncoding {
private final String charSet;
private final byte[] content;
EntityWithEncoding(HttpEntity entity) throws IOException {
try {
if (entity != null) {
content = EntityUtils.toByteArray(entity);
Charset entityCharset = ContentType.getOrDefault(entity).getCharset();
charSet = entityCharset != null ? entityCharset.name() : null;
} else {
content = new byte[0];
charSet = null;
}
} finally {
EntityUtils.consume(entity);
}
}
public String getContentString()
throws UnsupportedEncodingException {
return new String(content, charSet != null ? charSet : "utf-8");
}
public byte[] getContent() {
return content;
}
public boolean hasEntityContent() {
return content != null;
}
}
private Response createResponse(HttpResponse httpResponse, HttpContext context,
EntityWithEncoding entityWithEncoding) throws IOException {
final Response response;
Header header = httpResponse.getFirstHeader("Content-Type");
if (header != null && header.getValue().startsWith("application/json")) {
String responseAsText = entityWithEncoding.getContentString();
try {
response = new JsonToBeanConverter().convert(Response.class, responseAsText);
} catch (ClassCastException e) {
if (responseAsText != null && "".equals(responseAsText)) {
// The remote server has died, but has already set some headers.
// Normally this occurs when the final window of the firefox driver
// is closed on OS X. Return null, as the return value _should_ be
// being ignored. This is not an elegant solution.
return null;
}
throw new WebDriverException("Cannot convert text to response: " + responseAsText, e);
}
} else {
response = new Response();
if (header != null && header.getValue().startsWith("image/png")) {
response.setValue(entityWithEncoding.getContent());
} else if (entityWithEncoding.hasEntityContent()) {
response.setValue(entityWithEncoding.getContentString());
}
HttpHost finalHost = (HttpHost) context.getAttribute(HTTP_TARGET_HOST);
String uri = finalHost.toURI();
String sessionId = HttpSessionId.getSessionId(uri);
if (sessionId != null) {
response.setSessionId(sessionId);
}
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (!(statusCode > 199 && statusCode < 300)) {
// 4xx represents an unknown command or a bad request.
if (statusCode > 399 && statusCode < 500) {
response.setStatus(ErrorCodes.UNKNOWN_COMMAND);
} else if (statusCode > 499 && statusCode < 600) {
// 5xx represents an internal server error. The response status should already be set, but
// if not, set it to a general error code.
if (response.getStatus() == ErrorCodes.SUCCESS) {
response.setStatus(ErrorCodes.UNHANDLED_ERROR);
}
} else {
response.setStatus(ErrorCodes.UNHANDLED_ERROR);
}
}
if (response.getValue() instanceof String) {
// We normalise to \n because Java will translate this to \r\n
// if this is suitable on our platform, and if we have \r\n, java will
// turn this into \r\r\n, which would be Bad!
response.setValue(((String) response.getValue()).replace("\r\n", "\n"));
}
}
response.setState(errorCodes.toState(response.getStatus()));
return response;
}
private static CommandInfo get(String url) {
return new CommandInfo(url, HttpVerb.GET);
}
private static CommandInfo post(String url) {
return new CommandInfo(url, HttpVerb.POST);
}
private static CommandInfo delete(String url) {
return new CommandInfo(url, HttpVerb.DELETE);
}
}
| 1 | 10,691 | It would be better to just change RWD to throw IllegalStateException if you attempt to execute a command after quit (unless it's a second call to quit()) | SeleniumHQ-selenium | java |
@@ -14,12 +14,13 @@ module Bolt
def print_head; end
- def initialize(color, verbose, trace, stream = $stdout)
+ def initialize(color, verbose, trace, spin, stream = $stdout)
super
# Plans and without_default_logging() calls can both be nested, so we
# track each of them with a "stack" consisting of an integer.
@plan_depth = 0
@disable_depth = 0
+ @pinwheel = %w[- \\ | /]
end
def colorize(color, string) | 1 | # frozen_string_literal: true
require 'bolt/pal'
module Bolt
class Outputter
class Human < Bolt::Outputter
COLORS = {
red: "31",
green: "32",
yellow: "33",
cyan: "36"
}.freeze
def print_head; end
def initialize(color, verbose, trace, stream = $stdout)
super
# Plans and without_default_logging() calls can both be nested, so we
# track each of them with a "stack" consisting of an integer.
@plan_depth = 0
@disable_depth = 0
end
def colorize(color, string)
if @color && @stream.isatty
"\033[#{COLORS[color]}m#{string}\033[0m"
else
string
end
end
def remove_trail(string)
string.sub(/\s\z/, '')
end
def wrap(string, width = 80)
string.gsub(/(.{1,#{width}})(\s+|\Z)/, "\\1\n")
end
def handle_event(event)
case event[:type]
when :enable_default_output
@disable_depth -= 1
when :disable_default_output
@disable_depth += 1
when :message
print_message(event[:message])
end
if enabled?
case event[:type]
when :node_start
print_start(event[:target]) if @verbose
when :node_result
print_result(event[:result]) if @verbose
when :step_start
print_step_start(**event) if plan_logging?
when :step_finish
print_step_finish(**event) if plan_logging?
when :plan_start
print_plan_start(event)
when :plan_finish
print_plan_finish(event)
end
end
end
def enabled?
@disable_depth == 0
end
def plan_logging?
@plan_depth > 0
end
def print_start(target)
@stream.puts(colorize(:green, "Started on #{target.safe_name}..."))
end
def print_result(result)
if result.success?
@stream.puts(colorize(:green, "Finished on #{result.target.safe_name}:"))
else
@stream.puts(colorize(:red, "Failed on #{result.target.safe_name}:"))
end
if result.error_hash
@stream.puts(colorize(:red, remove_trail(indent(2, result.error_hash['msg']))))
end
if result.is_a?(Bolt::ApplyResult) && @verbose
result.resource_logs.each do |log|
# Omit low-level info/debug messages
next if %w[info debug].include?(log['level'])
message = format_log(log)
@stream.puts(indent(2, message))
end
end
# Only print results if there's something other than empty string and hash
if result.value.empty? || (result.value.keys == ['_output'] && !result.message?)
@stream.puts(indent(2, "#{result.action.capitalize} completed successfully with no result"))
else
# Only print messages that have something other than whitespace
if result.message?
@stream.puts(remove_trail(indent(2, result.message)))
end
# Use special handling if the result looks like a command or script result
if result.generic_value.keys == %w[stdout stderr exit_code]
safe_value = result.safe_value
unless safe_value['stdout'].strip.empty?
@stream.puts(indent(2, "STDOUT:"))
@stream.puts(indent(4, safe_value['stdout']))
end
unless safe_value['stderr'].strip.empty?
@stream.puts(indent(2, "STDERR:"))
@stream.puts(indent(4, safe_value['stderr']))
end
elsif result.generic_value.any?
@stream.puts(indent(2, ::JSON.pretty_generate(result.generic_value)))
end
end
end
def format_log(log)
color = case log['level']
when 'warn'
:yellow
when 'err'
:red
end
source = "#{log['source']}: " if log['source']
message = "#{log['level'].capitalize}: #{source}#{log['message']}"
message = colorize(color, message) if color
message
end
def print_step_start(description:, targets:, **_kwargs)
target_str = if targets.length > 5
"#{targets.count} targets"
else
targets.map(&:safe_name).join(', ')
end
@stream.puts(colorize(:green, "Starting: #{description} on #{target_str}"))
end
def print_step_finish(description:, result:, duration:, **_kwargs)
failures = result.error_set.length
plural = failures == 1 ? '' : 's'
message = "Finished: #{description} with #{failures} failure#{plural} in #{duration.round(2)} sec"
@stream.puts(colorize(:green, message))
end
def print_plan_start(event)
@plan_depth += 1
# We use this event to both mark the start of a plan _and_ to enable
# plan logging for `apply`, so only log the message if we were called
# with a plan
if event[:plan]
@stream.puts(colorize(:green, "Starting: plan #{event[:plan]}"))
end
end
def print_plan_finish(event)
@plan_depth -= 1
plan = event[:plan]
duration = event[:duration]
@stream.puts(colorize(:green, "Finished: plan #{plan} in #{duration_to_string(duration)}"))
end
def print_summary(results, elapsed_time = nil)
ok_set = results.ok_set
unless ok_set.empty?
@stream.puts format('Successful on %<size>d target%<plural>s: %<names>s',
size: ok_set.size,
plural: ok_set.size == 1 ? '' : 's',
names: ok_set.targets.map(&:safe_name).join(','))
end
error_set = results.error_set
unless error_set.empty?
@stream.puts colorize(:red,
format('Failed on %<size>d target%<plural>s: %<names>s',
size: error_set.size,
plural: error_set.size == 1 ? '' : 's',
names: error_set.targets.map(&:safe_name).join(',')))
end
total_msg = format('Ran on %<size>d target%<plural>s',
size: results.size,
plural: results.size == 1 ? '' : 's')
total_msg << " in #{duration_to_string(elapsed_time)}" unless elapsed_time.nil?
@stream.puts total_msg
end
def print_table(results, padding_left = 0, padding_right = 3)
# lazy-load expensive gem code
require 'terminal-table'
@stream.puts Terminal::Table.new(
rows: results,
style: {
border_x: '',
border_y: '',
border_i: '',
padding_left: padding_left,
padding_right: padding_right,
border_top: false,
border_bottom: false
}
)
end
def print_tasks(tasks, modulepath)
command = Bolt::Util.powershell? ? 'Get-BoltTask -Task <TASK NAME>' : 'bolt task show <TASK NAME>'
tasks.any? ? print_table(tasks) : print_message('No available tasks')
print_message("\nMODULEPATH:\n#{modulepath.join(File::PATH_SEPARATOR)}\n"\
"\nUse '#{command}' to view "\
"details and parameters for a specific task.")
end
# @param [Hash] task A hash representing the task
def print_task_info(task)
# Building lots of strings...
pretty_params = +""
task_info = +""
usage = if Bolt::Util.powershell?
+"Invoke-BoltTask -Name #{task.name} -Targets <targets>"
else
+"bolt task run #{task.name} --targets <targets>"
end
task.parameters&.each do |k, v|
pretty_params << "- #{k}: #{v['type'] || 'Any'}\n"
pretty_params << " Default: #{v['default'].inspect}\n" if v.key?('default')
pretty_params << " #{v['description']}\n" if v['description']
usage << if v['type'].start_with?("Optional")
" [#{k}=<value>]"
else
" #{k}=<value>"
end
end
if task.supports_noop
usage << Bolt::Util.powershell? ? '[-Noop]' : '[--noop]'
end
task_info << "\n#{task.name}"
task_info << " - #{task.description}" if task.description
task_info << "\n\n"
task_info << "USAGE:\n#{usage}\n\n"
task_info << "PARAMETERS:\n#{pretty_params}\n" unless pretty_params.empty?
task_info << "MODULE:\n"
path = task.files.first['path'].chomp("/tasks/#{task.files.first['name']}")
task_info << if path.start_with?(Bolt::Config::Modulepath::MODULES_PATH)
"built-in module"
else
path
end
@stream.puts(task_info)
end
# @param [Hash] plan A hash representing the plan
def print_plan_info(plan)
# Building lots of strings...
pretty_params = +""
plan_info = +""
usage = if Bolt::Util.powershell?
+"Invoke-BoltPlan -Name #{plan['name']}"
else
+"bolt plan run #{plan['name']}"
end
plan['parameters'].each do |name, p|
pretty_params << "- #{name}: #{p['type']}\n"
pretty_params << " Default: #{p['default_value']}\n" unless p['default_value'].nil?
pretty_params << " #{p['description']}\n" if p['description']
usage << (p.include?('default_value') ? " [#{name}=<value>]" : " #{name}=<value>")
end
plan_info << "\n#{plan['name']}"
plan_info << " - #{plan['description']}" if plan['description']
plan_info << "\n\n"
plan_info << "USAGE:\n#{usage}\n\n"
plan_info << "PARAMETERS:\n#{pretty_params}\n" unless plan['parameters'].empty?
plan_info << "MODULE:\n"
path = plan['module']
plan_info << if path.start_with?(Bolt::Config::Modulepath::MODULES_PATH)
"built-in module"
else
path
end
@stream.puts(plan_info)
end
def print_plans(plans, modulepath)
command = Bolt::Util.powershell? ? 'Get-BoltPlan -Name <PLAN NAME>' : 'bolt plan show <PLAN NAME>'
plans.any? ? print_table(plans) : print_message('No available plans')
print_message("\nMODULEPATH:\n#{modulepath.join(File::PATH_SEPARATOR)}\n"\
"\nUse '#{command}' to view "\
"details and parameters for a specific plan.")
end
def print_topics(topics)
print_message("Available topics are:")
print_message(topics.join("\n"))
print_message("\nUse 'bolt guide <TOPIC>' to view a specific guide.")
end
def print_guide(guide, _topic)
@stream.puts(guide)
end
def print_module_list(module_list)
module_list.each do |path, modules|
if (mod = modules.find { |m| m[:internal_module_group] })
@stream.puts(colorize(:cyan, mod[:internal_module_group]))
else
@stream.puts(colorize(:cyan, path))
end
if modules.empty?
@stream.puts('(no modules installed)')
else
module_info = modules.map do |m|
version = if m[:version].nil?
m[:internal_module_group].nil? ? '(no metadata)' : '(built-in)'
else
m[:version]
end
[m[:name], version]
end
print_table(module_info, 2, 1)
end
@stream.write("\n")
end
end
def print_targets(target_list, inventoryfile)
adhoc = colorize(:yellow, "(Not found in inventory file)")
targets = []
targets += target_list[:inventory].map { |target| [target.name, nil] }
targets += target_list[:adhoc].map { |target| [target.name, adhoc] }
if targets.any?
print_table(targets, 0, 2)
@stream.puts
end
@stream.puts "INVENTORY FILE:"
if File.exist?(inventoryfile)
@stream.puts inventoryfile
else
@stream.puts wrap("Tried to load inventory from #{inventoryfile}, but the file does not exist")
end
@stream.puts "\nTARGET COUNT:"
@stream.puts "#{targets.count} total, #{target_list[:inventory].count} from inventory, "\
"#{target_list[:adhoc].count} adhoc"
end
def print_target_info(targets)
@stream.puts ::JSON.pretty_generate(
"targets": targets.map(&:detail)
)
count = "#{targets.count} target#{'s' unless targets.count == 1}"
@stream.puts colorize(:green, count)
end
def print_groups(groups)
count = "#{groups.count} group#{'s' unless groups.count == 1}"
@stream.puts groups.join("\n")
@stream.puts colorize(:green, count)
end
# @param [Bolt::ResultSet] apply_result A ResultSet object representing the result of a `bolt apply`
def print_apply_result(apply_result, elapsed_time)
print_summary(apply_result, elapsed_time)
end
# @param [Bolt::PlanResult] plan_result A PlanResult object
def print_plan_result(plan_result)
value = plan_result.value
case value
when nil
@stream.puts("Plan completed successfully with no result")
when Bolt::ApplyFailure, Bolt::RunFailure
print_result_set(value.result_set)
when Bolt::ResultSet
print_result_set(value)
else
@stream.puts(::JSON.pretty_generate(plan_result, quirks_mode: true))
end
end
def print_result_set(result_set)
result_set.each { |result| print_result(result) }
print_summary(result_set)
end
def print_puppetfile_result(success, puppetfile, moduledir)
if success
@stream.puts("Successfully synced modules from #{puppetfile} to #{moduledir}")
else
@stream.puts(colorize(:red, "Failed to sync modules from #{puppetfile} to #{moduledir}"))
end
end
def fatal_error(err)
@stream.puts(colorize(:red, err.message))
if err.is_a? Bolt::RunFailure
@stream.puts ::JSON.pretty_generate(err.result_set)
end
if @trace && err.backtrace
err.backtrace.each do |line|
@stream.puts(colorize(:red, "\t#{line}"))
end
end
end
def print_message(message)
@stream.puts(message)
end
def print_error(message)
@stream.puts(colorize(:red, message))
end
def print_prompt(prompt)
@stream.print(colorize(:cyan, indent(4, prompt)))
end
def print_prompt_error(message)
@stream.puts(colorize(:red, indent(4, message)))
end
def print_action_step(step)
first, *remaining = wrap(step, 76).lines
first = indent(2, "→ #{first}")
remaining = remaining.map { |line| indent(4, line) }
step = [first, *remaining, "\n"].join
@stream.puts(step)
end
def print_action_error(error)
# Running everything through 'wrap' messes with newlines. Separating
# into lines and wrapping each individually ensures separate errors are
# distinguishable.
first, *remaining = error.lines
first = colorize(:red, indent(2, "→ #{wrap(first, 76)}"))
wrapped = remaining.map { |l| wrap(l) }
to_print = wrapped.map { |line| colorize(:red, indent(4, line)) }
step = [first, *to_print, "\n"].join
@stream.puts(step)
end
def duration_to_string(duration)
hrs = (duration / 3600).floor
mins = ((duration % 3600) / 60).floor
secs = (duration % 60)
if hrs > 0
"#{hrs} hr, #{mins} min, #{secs.round} sec"
elsif mins > 0
"#{mins} min, #{secs.round} sec"
else
# Include 2 decimal places if the duration is under a minute
"#{secs.round(2)} sec"
end
end
end
end
end
| 1 | 17,208 | Is this going to be configurable? If not, it should just be removed for now. | puppetlabs-bolt | rb |
@@ -23,6 +23,13 @@ See :ref:`Parameter` for more info on how to define parameters.
import abc
import datetime
import warnings
+import json
+from json import JSONEncoder
+from collections import OrderedDict
+import collections
+import operator
+import functools
+
try:
from ConfigParser import NoOptionError, NoSectionError
except ImportError: | 1 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
''' Parameters are one of the core concepts of Luigi.
All Parameters sit on :class:`~luigi.task.Task` classes.
See :ref:`Parameter` for more info on how to define parameters.
'''
import abc
import datetime
import warnings
try:
from ConfigParser import NoOptionError, NoSectionError
except ImportError:
from configparser import NoOptionError, NoSectionError
from luigi import task_register
from luigi import six
from luigi import configuration
from luigi.cmdline_parser import CmdlineParser
_no_value = object()
class ParameterException(Exception):
"""
Base exception.
"""
pass
class MissingParameterException(ParameterException):
"""
Exception signifying that there was a missing Parameter.
"""
pass
class UnknownParameterException(ParameterException):
"""
Exception signifying that an unknown Parameter was supplied.
"""
pass
class DuplicateParameterException(ParameterException):
"""
Exception signifying that a Parameter was specified multiple times.
"""
pass
class Parameter(object):
"""
An untyped Parameter
Parameters are objects set on the Task class level to make it possible to parameterize tasks.
For instance:
.. code:: python
class MyTask(luigi.Task):
foo = luigi.Parameter()
class RequiringTask(luigi.Task):
def requires(self):
return MyTask(foo="hello")
def run(self):
print(self.requires().foo) # prints "hello"
This makes it possible to instantiate multiple tasks, eg ``MyTask(foo='bar')`` and
``MyTask(foo='baz')``. The task will then have the ``foo`` attribute set appropriately.
When a task is instantiated, it will first use any argument as the value of the parameter, eg.
if you instantiate ``a = TaskA(x=44)`` then ``a.x == 44``. When the value is not provided, the
value will be resolved in this order of falling priority:
* Any value provided on the command line:
- To the root task (eg. ``--param xyz``)
- Then to the class, using the qualified task name syntax (eg. ``--TaskA-param xyz``).
* With ``[TASK_NAME]>PARAM_NAME: <serialized value>`` syntax. See :ref:`ParamConfigIngestion`
* Any default value set using the ``default`` flag.
There are subclasses of ``Parameter`` that define what type the parameter has. This is not
enforced within Python, but are used for command line interaction.
Parameter objects may be reused, but you must then set the ``positional=False`` flag.
"""
_counter = 0 # non-atomically increasing counter used for ordering parameters.
def __init__(self, default=_no_value, is_global=False, significant=True, description=None,
config_path=None, positional=True, always_in_help=False):
"""
:param default: the default value for this parameter. This should match the type of the
Parameter, i.e. ``datetime.date`` for ``DateParameter`` or ``int`` for
``IntParameter``. By default, no default is stored and
the value must be specified at runtime.
:param bool significant: specify ``False`` if the parameter should not be treated as part of
the unique identifier for a Task. An insignificant Parameter might
also be used to specify a password or other sensitive information
that should not be made public via the scheduler. Default:
``True``.
:param str description: A human-readable string describing the purpose of this Parameter.
For command-line invocations, this will be used as the `help` string
shown to users. Default: ``None``.
:param dict config_path: a dictionary with entries ``section`` and ``name``
specifying a config file entry from which to read the
default value for this parameter. DEPRECATED.
Default: ``None``.
:param bool positional: If true, you can set the argument as a
positional argument. It's true by default but we recommend
``positional=False`` for abstract base classes and similar cases.
:param bool always_in_help: For the --help option in the command line
parsing. Set true to always show in --help.
"""
self._default = default
if is_global:
warnings.warn("is_global support is removed. Assuming positional=False",
DeprecationWarning,
stacklevel=2)
positional = False
self.significant = significant # Whether different values for this parameter will differentiate otherwise equal tasks
self.positional = positional
self.description = description
self.always_in_help = always_in_help
if config_path is not None and ('section' not in config_path or 'name' not in config_path):
raise ParameterException('config_path must be a hash containing entries for section and name')
self.__config = config_path
self._counter = Parameter._counter # We need to keep track of this to get the order right (see Task class)
Parameter._counter += 1
def _get_value_from_config(self, section, name):
"""Loads the default from the config. Returns _no_value if it doesn't exist"""
conf = configuration.get_config()
try:
value = conf.get(section, name)
except (NoSectionError, NoOptionError):
return _no_value
return self.parse(value)
def _get_value(self, task_name, param_name):
for value, warn in self._value_iterator(task_name, param_name):
if value != _no_value:
if warn:
warnings.warn(warn, DeprecationWarning)
return value
return _no_value
def _value_iterator(self, task_name, param_name):
"""
Yield the parameter values, with optional deprecation warning as second tuple value.
The parameter value will be whatever non-_no_value that is yielded first.
"""
cp_parser = CmdlineParser.get_instance()
if cp_parser:
dest = self._parser_global_dest(param_name, task_name)
found = getattr(cp_parser.known_args, dest, None)
yield (self._parse_or_no_value(found), None)
yield (self._get_value_from_config(task_name, param_name), None)
yield (self._get_value_from_config(task_name, param_name.replace('_', '-')),
'Configuration [{}] {} (with dashes) should be avoided. Please use underscores.'.format(
task_name, param_name))
if self.__config:
yield (self._get_value_from_config(self.__config['section'], self.__config['name']),
'The use of the configuration [{}] {} is deprecated. Please use [{}] {}'.format(
self.__config['section'], self.__config['name'], task_name, param_name))
yield (self._default, None)
def has_task_value(self, task_name, param_name):
return self._get_value(task_name, param_name) != _no_value
def task_value(self, task_name, param_name):
value = self._get_value(task_name, param_name)
if value == _no_value:
raise MissingParameterException("No default specified")
else:
return self.normalize(value)
def parse(self, x):
"""
Parse an individual value from the input.
The default implementation is the identity function, but subclasses should override
this method for specialized parsing.
:param str x: the value to parse.
:return: the parsed value.
"""
return x # default impl
def serialize(self, x):
"""
Opposite of :py:meth:`parse`.
Converts the value ``x`` to a string.
:param x: the value to serialize.
"""
return str(x)
def normalize(self, x):
"""
Given a parsed parameter value, normalizes it.
The value can either be the result of parse(), the default value or
arguments passed into the task's constructor by instantiation.
This is very implementation defined, but can be used to validate/clamp
valid values. For example, if you wanted to only accept even integers,
and "correct" odd values to the nearest integer, you can implement
normalize as ``x // 2 * 2``.
"""
return x # default impl
def next_in_enumeration(self, _value):
"""
If your Parameter type has an enumerable ordering of values. You can
choose to override this method. This method is used by the
:py:mod:`luigi.execution_summary` module for pretty printing
purposes. Enabling it to pretty print tasks like ``MyTask(num=1),
MyTask(num=2), MyTask(num=3)`` to ``MyTask(num=1..3)``.
:param value: The value
:return: The next value, like "value + 1". Or ``None`` if there's no enumerable ordering.
"""
return None
def _parse_or_no_value(self, x):
if not x:
return _no_value
else:
return self.parse(x)
@staticmethod
def _parser_global_dest(param_name, task_name):
return task_name + '_' + param_name
@staticmethod
def _parser_action():
return "store"
_UNIX_EPOCH = datetime.datetime.utcfromtimestamp(0)
class _DateParameterBase(Parameter):
"""
Base class Parameter for date (not datetime).
"""
def __init__(self, interval=1, start=None, **kwargs):
super(_DateParameterBase, self).__init__(**kwargs)
self.interval = interval
self.start = start if start is not None else _UNIX_EPOCH.date()
@abc.abstractproperty
def date_format(self):
"""
Override me with a :py:meth:`~datetime.date.strftime` string.
"""
pass
def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date()
def serialize(self, dt):
"""
Converts the date to a string using the :py:attr:`~_DateParameterBase.date_format`.
"""
if dt is None:
return str(dt)
return dt.strftime(self.date_format)
class DateParameter(_DateParameterBase):
"""
Parameter whose value is a :py:class:`~datetime.date`.
A DateParameter is a Date string formatted ``YYYY-MM-DD``. For example, ``2013-07-10`` specifies
July 10, 2013.
"""
date_format = '%Y-%m-%d'
def next_in_enumeration(self, value):
return value + datetime.timedelta(days=self.interval)
def normalize(self, value):
if value is None:
return None
if isinstance(value, datetime.datetime):
value = value.date()
delta = (value - self.start).days % self.interval
return value - datetime.timedelta(days=delta)
class MonthParameter(DateParameter):
"""
Parameter whose value is a :py:class:`~datetime.date`, specified to the month
(day of :py:class:`~datetime.date` is "rounded" to first of the month).
A MonthParameter is a Date string formatted ``YYYY-MM``. For example, ``2013-07`` specifies
July of 2013.
"""
date_format = '%Y-%m'
def _add_months(self, date, months):
"""
Add ``months`` months to ``date``.
Unfortunately we can't use timedeltas to add months because timedelta counts in days
and there's no foolproof way to add N months in days without counting the number of
days per month.
"""
year = date.year + (date.month + months - 1) // 12
month = (date.month + months - 1) % 12 + 1
return datetime.date(year=year, month=month, day=1)
def next_in_enumeration(self, value):
return self._add_months(value, self.interval)
def normalize(self, value):
if value is None:
return None
months_since_start = (value.year - self.start.year) * 12 + (value.month - self.start.month)
months_since_start -= months_since_start % self.interval
return self._add_months(self.start, months_since_start)
class YearParameter(DateParameter):
"""
Parameter whose value is a :py:class:`~datetime.date`, specified to the year
(day and month of :py:class:`~datetime.date` is "rounded" to first day of the year).
A YearParameter is a Date string formatted ``YYYY``.
"""
date_format = '%Y'
def next_in_enumeration(self, value):
return value.replace(year=value.year + self.interval)
def normalize(self, value):
if value is None:
return None
delta = (value.year - self.start.year) % self.interval
return datetime.date(year=value.year - delta, month=1, day=1)
class _DatetimeParameterBase(Parameter):
"""
Base class Parameter for datetime
"""
def __init__(self, interval=1, start=None, **kwargs):
super(_DatetimeParameterBase, self).__init__(**kwargs)
self.interval = interval
self.start = start if start is not None else _UNIX_EPOCH
@abc.abstractproperty
def date_format(self):
"""
Override me with a :py:meth:`~datetime.date.strftime` string.
"""
pass
@abc.abstractproperty
def _timedelta(self):
"""
How to move one interval of this type forward (i.e. not counting self.interval).
"""
pass
def parse(self, s):
"""
Parses a string to a :py:class:`~datetime.datetime`.
"""
return datetime.datetime.strptime(s, self.date_format)
def serialize(self, dt):
"""
Converts the date to a string using the :py:attr:`~_DatetimeParameterBase.date_format`.
"""
if dt is None:
return str(dt)
return dt.strftime(self.date_format)
def normalize(self, dt):
"""
Clamp dt to every Nth :py:attr:`~_DatetimeParameterBase.interval` starting at
:py:attr:`~_DatetimeParameterBase.start`.
"""
if dt is None:
return None
dt = dt.replace(microsecond=0) # remove microseconds, to avoid float rounding issues.
delta = (dt - self.start).total_seconds()
granularity = (self._timedelta * self.interval).total_seconds()
return dt - datetime.timedelta(seconds=delta % granularity)
def next_in_enumeration(self, value):
return value + self._timedelta * self.interval
class DateHourParameter(_DatetimeParameterBase):
"""
Parameter whose value is a :py:class:`~datetime.datetime` specified to the hour.
A DateHourParameter is a `ISO 8601 <http://en.wikipedia.org/wiki/ISO_8601>`_ formatted
date and time specified to the hour. For example, ``2013-07-10T19`` specifies July 10, 2013 at
19:00.
"""
date_format = '%Y-%m-%dT%H' # ISO 8601 is to use 'T'
_timedelta = datetime.timedelta(hours=1)
class DateMinuteParameter(_DatetimeParameterBase):
"""
Parameter whose value is a :py:class:`~datetime.datetime` specified to the minute.
A DateMinuteParameter is a `ISO 8601 <http://en.wikipedia.org/wiki/ISO_8601>`_ formatted
date and time specified to the minute. For example, ``2013-07-10T1907`` specifies July 10, 2013 at
19:07.
The interval parameter can be used to clamp this parameter to every N minutes, instead of every minute.
"""
date_format = '%Y-%m-%dT%H%M'
_timedelta = datetime.timedelta(minutes=1)
deprecated_date_format = '%Y-%m-%dT%HH%M'
def parse(self, s):
try:
value = datetime.datetime.strptime(s, self.deprecated_date_format)
warnings.warn(
'Using "H" between hours and minutes is deprecated, omit it instead.',
DeprecationWarning,
stacklevel=2
)
return value
except ValueError:
return super(DateMinuteParameter, self).parse(s)
class IntParameter(Parameter):
"""
Parameter whose value is an ``int``.
"""
def parse(self, s):
"""
Parses an ``int`` from the string using ``int()``.
"""
return int(s)
def next_in_enumeration(self, value):
return value + 1
class FloatParameter(Parameter):
"""
Parameter whose value is a ``float``.
"""
def parse(self, s):
"""
Parses a ``float`` from the string using ``float()``.
"""
return float(s)
class BoolParameter(Parameter):
"""
A Parameter whose value is a ``bool``. This parameter have an implicit
default value of ``False``.
"""
def __init__(self, *args, **kwargs):
super(BoolParameter, self).__init__(*args, **kwargs)
if self._default == _no_value:
self._default = False
def parse(self, s):
"""
Parses a ``bool`` from the string, matching 'true' or 'false' ignoring case.
"""
return {'true': True, 'false': False}[str(s).lower()]
def normalize(self, value):
# coerce anything truthy to True
return bool(value) if value is not None else None
@staticmethod
def _parser_action():
return 'store_true'
class BooleanParameter(BoolParameter):
"""
DEPRECATED. Use :py:class:`~BoolParameter`
"""
def __init__(self, *args, **kwargs):
warnings.warn(
'BooleanParameter is deprecated, use BoolParameter instead',
DeprecationWarning,
stacklevel=2
)
super(BooleanParameter, self).__init__(*args, **kwargs)
class DateIntervalParameter(Parameter):
"""
A Parameter whose value is a :py:class:`~luigi.date_interval.DateInterval`.
Date Intervals are specified using the ISO 8601 date notation for dates
(eg. "2015-11-04"), months (eg. "2015-05"), years (eg. "2015"), or weeks
(eg. "2015-W35"). In addition, it also supports arbitrary date intervals
provided as two dates separated with a dash (eg. "2015-11-04-2015-12-04").
"""
def parse(self, s):
"""
Parses a :py:class:`~luigi.date_interval.DateInterval` from the input.
see :py:mod:`luigi.date_interval`
for details on the parsing of DateIntervals.
"""
# TODO: can we use xml.utils.iso8601 or something similar?
from luigi import date_interval as d
for cls in [d.Year, d.Month, d.Week, d.Date, d.Custom]:
i = cls.parse(s)
if i:
return i
raise ValueError('Invalid date interval - could not be parsed')
class TimeDeltaParameter(Parameter):
"""
Class that maps to timedelta using strings in any of the following forms:
* ``n {w[eek[s]]|d[ay[s]]|h[our[s]]|m[inute[s]|s[second[s]]}`` (e.g. "1 week 2 days" or "1 h")
Note: multiple arguments must be supplied in longest to shortest unit order
* ISO 8601 duration ``PnDTnHnMnS`` (each field optional, years and months not supported)
* ISO 8601 duration ``PnW``
See https://en.wikipedia.org/wiki/ISO_8601#Durations
"""
def _apply_regex(self, regex, input):
import re
re_match = re.match(regex, input)
if re_match:
kwargs = {}
has_val = False
for k, v in six.iteritems(re_match.groupdict(default="0")):
val = int(v)
has_val = has_val or val != 0
kwargs[k] = val
if has_val:
return datetime.timedelta(**kwargs)
def _parseIso8601(self, input):
def field(key):
return r"(?P<%s>\d+)%s" % (key, key[0].upper())
def optional_field(key):
return "(%s)?" % field(key)
# A little loose: ISO 8601 does not allow weeks in combination with other fields, but this regex does (as does python timedelta)
regex = "P(%s|%s(T%s)?)" % (field("weeks"), optional_field("days"), "".join([optional_field(key) for key in ["hours", "minutes", "seconds"]]))
return self._apply_regex(regex, input)
def _parseSimple(self, input):
keys = ["weeks", "days", "hours", "minutes", "seconds"]
# Give the digits a regex group name from the keys, then look for text with the first letter of the key,
# optionally followed by the rest of the word, with final char (the "s") optional
regex = "".join([r"((?P<%s>\d+) ?%s(%s)?(%s)? ?)?" % (k, k[0], k[1:-1], k[-1]) for k in keys])
return self._apply_regex(regex, input)
def parse(self, input):
"""
Parses a time delta from the input.
See :py:class:`TimeDeltaParameter` for details on supported formats.
"""
result = self._parseIso8601(input)
if not result:
result = self._parseSimple(input)
if result:
return result
else:
raise ParameterException("Invalid time delta - could not parse %s" % input)
class TaskParameter(Parameter):
"""
A parameter that takes another luigi task class.
When used programatically, the parameter should be specified
directly with the :py:class:`luigi.task.Task` (sub) class. Like
``MyMetaTask(my_task_param=my_tasks.MyTask)``. On the command line,
you specify the :py:attr:`luigi.task.Task.task_family`. Like
.. code-block:: console
$ luigi --module my_tasks MyMetaTask --my_task_param my_namespace.MyTask
Where ``my_namespace.MyTask`` is defined in the ``my_tasks`` python module.
When the :py:class:`luigi.task.Task` class is instantiated to an object.
The value will always be a task class (and not a string).
"""
def parse(self, input):
"""
Parse a task_famly using the :class:`~luigi.task_register.Register`
"""
return task_register.Register.get_task_cls(input)
def serialize(self, cls):
"""
Converts the :py:class:`luigi.task.Task` (sub) class to its family name.
"""
return cls.task_family
class EnumParameter(Parameter):
"""
A parameter whose value is an :class:`~enum.Enum`.
In the task definition, use
.. code-block:: python
class Models(enum.IntEnum):
Honda = 1
class MyTask(luigi.Task):
my_param = luigi.EnumParameter(enum=Models)
At the command line, use,
.. code-block:: console
$ luigi --module my_tasks MyTask --my-param Honda
"""
def __init__(self, *args, **kwargs):
if 'enum' not in kwargs:
raise ParameterException('An enum class must be specified.')
self._enum = kwargs.pop('enum')
super(EnumParameter, self).__init__(*args, **kwargs)
def parse(self, s):
try:
return self._enum[s]
except KeyError:
raise ValueError('Invalid enum value - could not be parsed')
def serialize(self, e):
return e.name
| 1 | 14,360 | Maybe just one import line - `from collections import OrderedDict, Mapping` ? | spotify-luigi | py |
@@ -37,8 +37,8 @@ public class NonRuleWithAllPropertyTypes extends AbstractRule {
public static final StringMultiProperty MULTI_STR = new StringMultiProperty("multiStr", "Multiple string values",
new String[] {"hello", "world"}, 5.0f, '|');
public static final PropertyDescriptor<Integer> SINGLE_INT = PropertyFactory.intProperty("singleInt").desc("Single integer value").require(inRange(1, 10)).defaultValue(8).build();
- public static final IntegerMultiProperty MULTI_INT = new IntegerMultiProperty("multiInt", "Multiple integer values",
- 0, 10, new Integer[] {1, 2, 3, 4}, 5.0f);
+ public static final PropertyDescriptor<List<Integer>> MULTI_INT = PropertyFactory.intListProperty("multiInt").desc("Multiple integer values").requireEach(inRange(0, 10)).defaultValues(1, 2, 3, 4).build();
+
public static final LongProperty SINGLE_LONG = new LongProperty("singleLong", "Single long value", 1L, 10L, 8L,
3.0f);
public static final LongMultiProperty MULTI_LONG = new LongMultiProperty("multiLong", "Multiple long values", 0L, | 1 | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.properties;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.inRange;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.AbstractRule;
import net.sourceforge.pmd.util.ClassUtil;
/**
* A non-functional rule containing all property types. Used for testing UIs.
*
* Steps required to use with Eclipse Plugin:
*
* update your chosen ruleset xml file to include this 'rule' compile new PMD
* jars copy both the pmd5.0.jar and pmd-test-5.0.jar to the eclipse-plugin/lib
* directory update the /manifest.mf file to ensure it includes the
* pmd-test-5.0.jar
*
* @author Brian Remedios
*/
public class NonRuleWithAllPropertyTypes extends AbstractRule {
// descriptors are public to enable us to write external tests
public static final StringProperty SINGLE_STR = new StringProperty("singleStr", "String value", "hello world", 3.0f);
public static final StringMultiProperty MULTI_STR = new StringMultiProperty("multiStr", "Multiple string values",
new String[] {"hello", "world"}, 5.0f, '|');
public static final PropertyDescriptor<Integer> SINGLE_INT = PropertyFactory.intProperty("singleInt").desc("Single integer value").require(inRange(1, 10)).defaultValue(8).build();
public static final IntegerMultiProperty MULTI_INT = new IntegerMultiProperty("multiInt", "Multiple integer values",
0, 10, new Integer[] {1, 2, 3, 4}, 5.0f);
public static final LongProperty SINGLE_LONG = new LongProperty("singleLong", "Single long value", 1L, 10L, 8L,
3.0f);
public static final LongMultiProperty MULTI_LONG = new LongMultiProperty("multiLong", "Multiple long values", 0L,
10L, new Long[] {1L, 2L, 3L, 4L}, 5.0f);
public static final BooleanProperty SINGLE_BOOL = new BooleanProperty("singleBool", "Single boolean value", true,
6.0f);
public static final BooleanMultiProperty MULTI_BOOL = new BooleanMultiProperty("multiBool",
"Multiple boolean values", new Boolean[] {true, false}, 5.0f);
public static final CharacterProperty SINGLE_CHAR = new CharacterProperty("singleChar", "Single character", 'a',
5.0f);
public static final CharacterMultiProperty MULTI_CHAR = new CharacterMultiProperty("multiChar",
"Multiple characters", new Character[] {'a', 'e', 'i', 'o', 'u'}, 6.0f, '|');
public static final FloatProperty SINGLE_FLOAT = new FloatProperty("singleFloat", "Single float value", .9f, 10f, .9f,
5.0f);
public static final FloatMultiProperty MULTI_FLOAT = new FloatMultiProperty("multiFloat", "Multiple float values",
0f, 5f, new Float[] {1f, 2f, 3f}, 6.0f);
public static final TypeProperty SINGLE_TYPE = new TypeProperty("singleType", "Single type", String.class,
new String[] {"java.lang"}, 5.0f);
public static final TypeMultiProperty MULTI_TYPE = new TypeMultiProperty("multiType", "Multiple types",
Arrays.<Class>asList(Integer.class, Object.class), new String[] {"java.lang"}, 6.0f);
private static final Map<String, Class> ENUM_MAPPINGS;
static {
Map<String, Class> tmp = new HashMap<>();
tmp.put("String", String.class);
tmp.put("Object", Object.class);
ENUM_MAPPINGS = Collections.unmodifiableMap(tmp);
}
public static final EnumeratedProperty<Class> ENUM_TYPE = new EnumeratedProperty<>("enumType", "Enumerated choices", ENUM_MAPPINGS, Object.class, Class.class, 5.0f);
public static final EnumeratedMultiProperty<Class> MULTI_ENUM_TYPE = new EnumeratedMultiProperty<>("multiEnumType", "Multiple enumerated choices", ENUM_MAPPINGS,
Arrays.<Class>asList(String.class, Object.class), Class.class, 5.0f);
private static final Method STRING_LENGTH = ClassUtil.methodFor(String.class, "length", ClassUtil.EMPTY_CLASS_ARRAY);
public static final MethodProperty SINGLE_METHOD = new MethodProperty("singleMethod", "Single method",
STRING_LENGTH, new String[] {"java.lang"}, 5.0f);
private static final Method STRING_TO_LOWER_CASE = ClassUtil.methodFor(String.class, "toLowerCase",
ClassUtil.EMPTY_CLASS_ARRAY);
public static final MethodMultiProperty MULTI_METHOD = new MethodMultiProperty("multiMethod", "Multiple methods",
new Method[] {STRING_LENGTH, STRING_TO_LOWER_CASE}, new String[] {"java.lang"}, 6.0f);
public NonRuleWithAllPropertyTypes() {
super();
definePropertyDescriptor(SINGLE_STR);
definePropertyDescriptor(MULTI_STR);
definePropertyDescriptor(SINGLE_INT);
definePropertyDescriptor(MULTI_INT);
definePropertyDescriptor(SINGLE_LONG);
definePropertyDescriptor(MULTI_LONG);
definePropertyDescriptor(SINGLE_BOOL);
definePropertyDescriptor(MULTI_BOOL);
definePropertyDescriptor(SINGLE_CHAR);
definePropertyDescriptor(MULTI_CHAR);
definePropertyDescriptor(SINGLE_FLOAT);
definePropertyDescriptor(MULTI_FLOAT);
definePropertyDescriptor(SINGLE_TYPE);
definePropertyDescriptor(MULTI_TYPE);
definePropertyDescriptor(ENUM_TYPE);
definePropertyDescriptor(SINGLE_METHOD);
definePropertyDescriptor(MULTI_METHOD);
definePropertyDescriptor(MULTI_ENUM_TYPE);
}
@Override
public void apply(List<? extends Node> nodes, RuleContext ctx) {
}
}
| 1 | 14,998 | Btw this class probably doesn't belong in PMD. It says it's there to test UIs, but arguably UIs can use their own test fixtures, and this in in src/test so probably not even shipped anywhere. | pmd-pmd | java |
@@ -50,6 +50,8 @@ describe( 'AMPContainerSelect', () => {
registry.dispatch( STORE_NAME ).setAccountID( accountID );
registry.dispatch( STORE_NAME ).receiveGetAccounts( [ account ] );
registry.dispatch( STORE_NAME ).receiveGetContainers( [ ...webContainers, ...ampContainers ], { accountID } );
+ registry.dispatch( STORE_NAME ).finishResolution( 'getAccounts', [] );
+ registry.dispatch( STORE_NAME ).finishResolution( 'getContainers', [ accountID ] );
const { getAllByRole } = render( <AMPContainerSelect />, { registry } );
| 1 | /**
* AMP Container Select component tests.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import AMPContainerSelect from './AMPContainerSelect';
import { fireEvent, render, act } from '../../../../../../tests/js/test-utils';
import { STORE_NAME, CONTEXT_WEB, CONTEXT_AMP, CONTAINER_CREATE } from '../../datastore/constants';
import { STORE_NAME as CORE_SITE, AMP_MODE_PRIMARY, AMP_MODE_SECONDARY } from '../../../../googlesitekit/datastore/site/constants';
import { createTestRegistry, freezeFetch, untilResolved } from '../../../../../../tests/js/utils';
import * as factories from '../../datastore/__factories__';
describe( 'AMPContainerSelect', () => {
let registry;
beforeEach( () => {
registry = createTestRegistry();
// Set settings to prevent fetch in resolver.
registry.dispatch( STORE_NAME ).setSettings( {} );
// Set set no existing tag.
registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
// Set site info to prevent error in resolver.
registry.dispatch( CORE_SITE ).receiveSiteInfo( { ampMode: AMP_MODE_PRIMARY } );
} );
it( 'should render an option for each AMP container of the currently selected account.', () => {
const account = factories.accountBuilder();
const webContainers = factories.buildContainers(
3, { accountId: account.accountId, usageContext: [ CONTEXT_WEB ] } // eslint-disable-line sitekit/camelcase-acronyms
);
const ampContainers = factories.buildContainers(
3, { accountId: account.accountId, usageContext: [ CONTEXT_AMP ] } // eslint-disable-line sitekit/camelcase-acronyms
);
const accountID = account.accountId; // eslint-disable-line sitekit/camelcase-acronyms
registry.dispatch( STORE_NAME ).setAccountID( accountID );
registry.dispatch( STORE_NAME ).receiveGetAccounts( [ account ] );
registry.dispatch( STORE_NAME ).receiveGetContainers( [ ...webContainers, ...ampContainers ], { accountID } );
const { getAllByRole } = render( <AMPContainerSelect />, { registry } );
const listItems = getAllByRole( 'menuitem', { hidden: true } );
// Note: we do length + 1 here because there should also be an item for
// "Set up a new container".
expect( listItems ).toHaveLength( webContainers.length + 1 );
expect(
listItems.some( ( { dataset } ) => dataset.value === CONTAINER_CREATE )
).toBe( true );
} );
it( 'should have a "Set up a new container" item at the end of the list', () => {
const { account, containers } = factories.buildAccountWithContainers(
{ container: { usageContext: [ CONTEXT_AMP ] } }
);
const accountID = account.accountId; // eslint-disable-line sitekit/camelcase-acronyms
registry.dispatch( STORE_NAME ).setAccountID( accountID );
registry.dispatch( STORE_NAME ).receiveGetAccounts( [ account ] );
registry.dispatch( STORE_NAME ).receiveGetContainers( containers, { accountID } );
const { getAllByRole } = render( <AMPContainerSelect />, { registry } );
const listItems = getAllByRole( 'menuitem', { hidden: true } );
expect( listItems.pop() ).toHaveTextContent( /set up a new container/i );
} );
it( 'can select the "Set up a new container" option', async () => {
const { account, containers } = factories.buildAccountWithContainers(
{ container: { usageContext: [ CONTEXT_AMP ] } }
);
const accountID = account.accountId; // eslint-disable-line sitekit/camelcase-acronyms
registry.dispatch( STORE_NAME ).setAccountID( accountID );
registry.dispatch( STORE_NAME ).receiveGetAccounts( [ account ] );
registry.dispatch( STORE_NAME ).receiveGetContainers( containers, { accountID } );
const { container, getByText } = render( <AMPContainerSelect />, { registry } );
fireEvent.click( container.querySelector( '.mdc-select__selected-text' ) );
fireEvent.click( getByText( /set up a new container/i ) );
expect( container.querySelector( '.mdc-select__selected-text' ) ).toHaveTextContent( /set up a new container/i );
} );
it( 'should update the container ID and internal container ID when selected', async () => {
const { account, containers } = factories.buildAccountWithContainers(
{ container: { usageContext: [ CONTEXT_AMP ] } }
);
const ampContainer = containers[ 0 ];
const accountID = account.accountId; // eslint-disable-line sitekit/camelcase-acronyms
registry.dispatch( STORE_NAME ).setAccountID( accountID );
registry.dispatch( STORE_NAME ).receiveGetAccounts( [ account ] );
registry.dispatch( STORE_NAME ).receiveGetContainers( containers, { accountID } );
const { container, getByText } = render( <AMPContainerSelect />, { registry } );
expect( registry.select( STORE_NAME ).getAMPContainerID() ).toBeFalsy();
expect( registry.select( STORE_NAME ).getInternalAMPContainerID() ).toBeFalsy();
fireEvent.click( container.querySelector( '.mdc-select__selected-text' ) );
await act( async () => {
fireEvent.click( getByText( ampContainer.name ) );
await untilResolved( registry, STORE_NAME ).getContainers( accountID );
} );
expect( registry.select( STORE_NAME ).getAMPContainerID() ).toBe( ampContainer.publicId ); // eslint-disable-line sitekit/camelcase-acronyms
expect( registry.select( STORE_NAME ).getInternalAMPContainerID() ).toBe( ampContainer.containerId ); // eslint-disable-line sitekit/camelcase-acronyms
} );
it( 'should render a loading state while accounts have not been loaded', () => {
freezeFetch( /^\/google-site-kit\/v1\/modules\/tagmanager\/data\/accounts/ );
const { queryByRole } = render( <AMPContainerSelect />, { registry } );
expect( queryByRole( 'menu', { hidden: true } ) ).not.toBeInTheDocument();
expect( queryByRole( 'progressbar' ) ).toBeInTheDocument();
} );
it( 'should render a loading state while containers are loading', () => {
freezeFetch( /^\/google-site-kit\/v1\/modules\/tagmanager\/data\/containers/ );
const account = factories.accountBuilder();
const accountID = account.accountId; // eslint-disable-line sitekit/camelcase-acronyms
registry.dispatch( STORE_NAME ).receiveGetAccounts( [ account ] );
registry.dispatch( STORE_NAME ).setAccountID( accountID );
const { queryByRole } = render( <AMPContainerSelect />, { registry } );
expect( queryByRole( 'menu', { hidden: true } ) ).not.toBeInTheDocument();
expect( queryByRole( 'progressbar' ) ).toBeInTheDocument();
} );
it( 'should be labeled as "Container" in a primary AMP context', () => {
const { account, containers } = factories.buildAccountWithContainers();
const accountID = account.accountId; // eslint-disable-line sitekit/camelcase-acronyms
registry.dispatch( STORE_NAME ).setAccountID( accountID );
registry.dispatch( STORE_NAME ).receiveGetAccounts( [ account ] );
registry.dispatch( STORE_NAME ).receiveGetContainers( containers, { accountID } );
registry.dispatch( CORE_SITE ).receiveSiteInfo( { ampMode: AMP_MODE_PRIMARY } );
const { container } = render( <AMPContainerSelect />, { registry } );
expect( container.querySelector( '.mdc-floating-label' ) ).toHaveTextContent( /Container/i );
} );
it( 'should be labeled as "AMP Container" in a secondary AMP context', () => {
const { account, containers } = factories.buildAccountWithContainers();
const accountID = account.accountId; // eslint-disable-line sitekit/camelcase-acronyms
registry.dispatch( STORE_NAME ).setAccountID( accountID );
registry.dispatch( STORE_NAME ).receiveGetAccounts( [ account ] );
registry.dispatch( STORE_NAME ).receiveGetContainers( containers, { accountID } );
registry.dispatch( CORE_SITE ).receiveSiteInfo( { ampMode: AMP_MODE_SECONDARY } );
const { container } = render( <AMPContainerSelect />, { registry } );
expect( container.querySelector( '.mdc-floating-label' ) ).toHaveTextContent( /AMP Container/i );
} );
it( 'should render nothing in a non-AMP context', () => {
const account = factories.accountBuilder();
registry.dispatch( STORE_NAME ).receiveGetAccounts( [ account ] );
registry.dispatch( CORE_SITE ).receiveSiteInfo( { ampMode: false } );
const { queryByRole, container } = render( <AMPContainerSelect />, { registry } );
expect( queryByRole( 'progressbar' ) ).not.toBeInTheDocument();
expect( queryByRole( 'menu', { hidden: true } ) ).not.toBeInTheDocument();
expect( container ).toBeEmptyDOMElement();
} );
} );
| 1 | 32,635 | Maybe we can group each `finishResolution` call with the corresponding `receiveGet...` call? That would make the connection more clear when reading the code. | google-site-kit-wp | js |
@@ -109,9 +109,9 @@ class ServerConnectionMixin(object):
self.disconnect()
"""
- def __init__(self, server_address=None):
+ def __init__(self, server_address=None, source_address=None):
super(ServerConnectionMixin, self).__init__()
- self.server_conn = ServerConnection(server_address)
+ self.server_conn = ServerConnection(server_address, source_address)
self.__check_self_connect()
def __check_self_connect(self): | 1 | from __future__ import (absolute_import, print_function, division)
import sys
import six
from netlib import tcp
from ..models import ServerConnection
from ..exceptions import ProtocolException
from netlib.exceptions import TcpException
class _LayerCodeCompletion(object):
"""
Dummy class that provides type hinting in PyCharm, which simplifies development a lot.
"""
def __init__(self, **mixin_args): # pragma: nocover
super(_LayerCodeCompletion, self).__init__(**mixin_args)
if True:
return
self.config = None
"""@type: libmproxy.proxy.ProxyConfig"""
self.client_conn = None
"""@type: libmproxy.models.ClientConnection"""
self.server_conn = None
"""@type: libmproxy.models.ServerConnection"""
self.channel = None
"""@type: libmproxy.controller.Channel"""
self.ctx = None
"""@type: libmproxy.protocol.Layer"""
class Layer(_LayerCodeCompletion):
"""
Base class for all layers. All other protocol layers should inherit from this class.
"""
def __init__(self, ctx, **mixin_args):
"""
Each layer usually passes itself to its child layers as a context. Properties of the
context are transparently mapped to the layer, so that the following works:
.. code-block:: python
root_layer = Layer(None)
root_layer.client_conn = 42
sub_layer = Layer(root_layer)
print(sub_layer.client_conn) # 42
The root layer is passed a :py:class:`libmproxy.proxy.RootContext` object,
which provides access to :py:attr:`.client_conn <libmproxy.proxy.RootContext.client_conn>`,
:py:attr:`.next_layer <libmproxy.proxy.RootContext.next_layer>` and other basic attributes.
Args:
ctx: The (read-only) parent layer / context.
"""
self.ctx = ctx
"""
The parent layer.
:type: :py:class:`Layer`
"""
super(Layer, self).__init__(**mixin_args)
def __call__(self):
"""Logic of the layer.
Returns:
Once the protocol has finished without exceptions.
Raises:
~libmproxy.exceptions.ProtocolException: if an exception occurs. No other exceptions must be raised.
"""
raise NotImplementedError()
def __getattr__(self, name):
"""
Attributes not present on the current layer are looked up on the context.
"""
return getattr(self.ctx, name)
@property
def layers(self):
"""
List of all layers, including the current layer (``[self, self.ctx, self.ctx.ctx, ...]``)
"""
return [self] + self.ctx.layers
def __repr__(self):
return type(self).__name__
class ServerConnectionMixin(object):
"""
Mixin that provides a layer with the capabilities to manage a server connection.
The server address can be passed in the constructor or set by calling :py:meth:`set_server`.
Subclasses are responsible for calling :py:meth:`disconnect` before returning.
Recommended Usage:
.. code-block:: python
class MyLayer(Layer, ServerConnectionMixin):
def __call__(self):
try:
# Do something.
finally:
if self.server_conn:
self.disconnect()
"""
def __init__(self, server_address=None):
super(ServerConnectionMixin, self).__init__()
self.server_conn = ServerConnection(server_address)
self.__check_self_connect()
def __check_self_connect(self):
"""
We try to protect the proxy from _accidentally_ connecting to itself,
e.g. because of a failed transparent lookup or an invalid configuration.
"""
address = self.server_conn.address
if address:
self_connect = (
address.port == self.config.port and
address.host in ("localhost", "127.0.0.1", "::1")
)
if self_connect:
raise ProtocolException(
"Invalid server address: {}\r\n"
"The proxy shall not connect to itself.".format(repr(address))
)
def set_server(self, address, server_tls=None, sni=None):
"""
Sets a new server address. If there is an existing connection, it will be closed.
Raises:
~libmproxy.exceptions.ProtocolException:
if ``server_tls`` is ``True``, but there was no TLS layer on the
protocol stack which could have processed this.
"""
if self.server_conn:
self.disconnect()
self.log("Set new server address: " + repr(address), "debug")
self.server_conn.address = address
self.__check_self_connect()
if server_tls:
raise ProtocolException(
"Cannot upgrade to TLS, no TLS layer on the protocol stack."
)
def disconnect(self):
"""
Deletes (and closes) an existing server connection.
Must not be called if there is no existing connection.
"""
self.log("serverdisconnect", "debug", [repr(self.server_conn.address)])
address = self.server_conn.address
self.server_conn.finish()
self.server_conn.close()
self.channel.tell("serverdisconnect", self.server_conn)
self.server_conn = ServerConnection(address)
def connect(self):
"""
Establishes a server connection.
Must not be called if there is an existing connection.
Raises:
~libmproxy.exceptions.ProtocolException: if the connection could not be established.
"""
if not self.server_conn.address:
raise ProtocolException("Cannot connect to server, no server address given.")
self.log("serverconnect", "debug", [repr(self.server_conn.address)])
self.channel.ask("serverconnect", self.server_conn)
try:
self.server_conn.connect()
except TcpException as e:
six.reraise(
ProtocolException,
ProtocolException(
"Server connection to {} failed: {}".format(
repr(self.server_conn.address), str(e)
)
),
sys.exc_info()[2]
)
class Kill(Exception):
"""
Signal that both client and server connection(s) should be killed immediately.
"""
| 1 | 10,958 | Can we take this out of the constructor here and just use the config value? (This would also make the other proxy mode cases obsolete) | mitmproxy-mitmproxy | py |
@@ -1350,9 +1350,14 @@ class RustGenerator : public BaseGenerator {
code_ +=
" if self.{{FIELD_TYPE_FIELD_NAME}}_type() == "
"{{U_ELEMENT_ENUM_TYPE}} {";
- code_ +=
- " self.{{FIELD_NAME}}().map(|u| "
- "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))";
+ if (!field.required) {
+ code_ +=
+ " self.{{FIELD_NAME}}().map(|u| "
+ "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))";
+ } else {
+ code_ += " let u = self.{{FIELD_NAME}}();";
+ code_ += " Some({{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))";
+ }
code_ += " } else {";
code_ += " None";
code_ += " }"; | 1 | /*
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// independent from idl_parser, since this code is not needed for most clients
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
namespace flatbuffers {
// Convert a camelCaseIdentifier or CamelCaseIdentifier to a
// snake_case_indentifier.
std::string MakeSnakeCase(const std::string &in) {
std::string s;
for (size_t i = 0; i < in.length(); i++) {
if (i == 0) {
s += static_cast<char>(tolower(in[0]));
} else if (in[i] == '_') {
s += '_';
} else if (!islower(in[i])) {
// Prevent duplicate underscores for Upper_Snake_Case strings
// and UPPERCASE strings.
if (islower(in[i - 1])) { s += '_'; }
s += static_cast<char>(tolower(in[i]));
} else {
s += in[i];
}
}
return s;
}
// Convert a string to all uppercase.
std::string MakeUpper(const std::string &in) {
std::string s;
for (size_t i = 0; i < in.length(); i++) {
s += static_cast<char>(toupper(in[i]));
}
return s;
}
// Encapsulate all logical field types in this enum. This allows us to write
// field logic based on type switches, instead of branches on the properties
// set on the Type.
// TODO(rw): for backwards compatibility, we can't use a strict `enum class`
// declaration here. could we use the `-Wswitch-enum` warning to
// achieve the same effect?
enum FullType {
ftInteger = 0,
ftFloat = 1,
ftBool = 2,
ftStruct = 3,
ftTable = 4,
ftEnumKey = 5,
ftUnionKey = 6,
ftUnionValue = 7,
// TODO(rw): bytestring?
ftString = 8,
ftVectorOfInteger = 9,
ftVectorOfFloat = 10,
ftVectorOfBool = 11,
ftVectorOfEnumKey = 12,
ftVectorOfStruct = 13,
ftVectorOfTable = 14,
ftVectorOfString = 15,
ftVectorOfUnionValue = 16,
};
// Convert a Type to a FullType (exhaustive).
FullType GetFullType(const Type &type) {
// N.B. The order of these conditionals matters for some types.
if (type.base_type == BASE_TYPE_STRING) {
return ftString;
} else if (type.base_type == BASE_TYPE_STRUCT) {
if (type.struct_def->fixed) {
return ftStruct;
} else {
return ftTable;
}
} else if (type.base_type == BASE_TYPE_VECTOR) {
switch (GetFullType(type.VectorType())) {
case ftInteger: {
return ftVectorOfInteger;
}
case ftFloat: {
return ftVectorOfFloat;
}
case ftBool: {
return ftVectorOfBool;
}
case ftStruct: {
return ftVectorOfStruct;
}
case ftTable: {
return ftVectorOfTable;
}
case ftString: {
return ftVectorOfString;
}
case ftEnumKey: {
return ftVectorOfEnumKey;
}
case ftUnionKey:
case ftUnionValue: {
FLATBUFFERS_ASSERT(false && "vectors of unions are unsupported");
break;
}
default: {
FLATBUFFERS_ASSERT(false && "vector of vectors are unsupported");
}
}
} else if (type.enum_def != nullptr) {
if (type.enum_def->is_union) {
if (type.base_type == BASE_TYPE_UNION) {
return ftUnionValue;
} else if (IsInteger(type.base_type)) {
return ftUnionKey;
} else {
FLATBUFFERS_ASSERT(false && "unknown union field type");
}
} else {
return ftEnumKey;
}
} else if (IsScalar(type.base_type)) {
if (IsBool(type.base_type)) {
return ftBool;
} else if (IsInteger(type.base_type)) {
return ftInteger;
} else if (IsFloat(type.base_type)) {
return ftFloat;
} else {
FLATBUFFERS_ASSERT(false && "unknown number type");
}
}
FLATBUFFERS_ASSERT(false && "completely unknown type");
// this is only to satisfy the compiler's return analysis.
return ftBool;
}
// If the second parameter is false then wrap the first with Option<...>
std::string WrapInOptionIfNotRequired(std::string s, bool required) {
if (required) {
return s;
} else {
return "Option<" + s + ">";
}
}
// If the second parameter is false then add .unwrap()
std::string AddUnwrapIfRequired(std::string s, bool required) {
if (required) {
return s + ".unwrap()";
} else {
return s;
}
}
namespace rust {
class RustGenerator : public BaseGenerator {
public:
RustGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "", "::", "rs"),
cur_name_space_(nullptr) {
const char *keywords[] = {
// list taken from:
// https://doc.rust-lang.org/book/second-edition/appendix-01-keywords.html
//
// we write keywords one per line so that we can easily compare them with
// changes to that webpage in the future.
// currently-used keywords
"as", "break", "const", "continue", "crate", "else", "enum", "extern",
"false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod",
"move", "mut", "pub", "ref", "return", "Self", "self", "static", "struct",
"super", "trait", "true", "type", "unsafe", "use", "where", "while",
// future possible keywords
"abstract", "alignof", "become", "box", "do", "final", "macro",
"offsetof", "override", "priv", "proc", "pure", "sizeof", "typeof",
"unsized", "virtual", "yield",
// other rust terms we should not use
"std", "usize", "isize", "u8", "i8", "u16", "i16", "u32", "i32", "u64",
"i64", "u128", "i128", "f32", "f64",
// These are terms the code generator can implement on types.
//
// In Rust, the trait resolution rules (as described at
// https://github.com/rust-lang/rust/issues/26007) mean that, as long
// as we impl table accessors as inherent methods, we'll never create
// conflicts with these keywords. However, that's a fairly nuanced
// implementation detail, and how we implement methods could change in
// the future. as a result, we proactively block these out as reserved
// words.
"follow", "push", "size", "alignment", "to_little_endian",
"from_little_endian", nullptr
};
for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
}
// Iterate through all definitions we haven't generated code for (enums,
// structs, and tables) and output them to a single file.
bool generate() {
code_.Clear();
code_ += "// " + std::string(FlatBuffersGeneratedWarning()) + "\n\n";
assert(!cur_name_space_);
// Generate imports for the global scope in case no namespace is used
// in the schema file.
GenNamespaceImports(0);
code_ += "";
// Generate all code in their namespaces, once, because Rust does not
// permit re-opening modules.
//
// TODO(rw): Use a set data structure to reduce namespace evaluations from
// O(n**2) to O(n).
for (auto ns_it = parser_.namespaces_.begin();
ns_it != parser_.namespaces_.end(); ++ns_it) {
const auto &ns = *ns_it;
// Generate code for all the enum declarations.
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
const auto &enum_def = **it;
if (enum_def.defined_namespace != ns) { continue; }
if (!enum_def.generated) {
SetNameSpace(enum_def.defined_namespace);
GenEnum(enum_def);
}
}
// Generate code for all structs.
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
const auto &struct_def = **it;
if (struct_def.defined_namespace != ns) { continue; }
if (struct_def.fixed && !struct_def.generated) {
SetNameSpace(struct_def.defined_namespace);
GenStruct(struct_def);
}
}
// Generate code for all tables.
for (auto it = parser_.structs_.vec.begin();
it != parser_.structs_.vec.end(); ++it) {
const auto &struct_def = **it;
if (struct_def.defined_namespace != ns) { continue; }
if (!struct_def.fixed && !struct_def.generated) {
SetNameSpace(struct_def.defined_namespace);
GenTable(struct_def);
}
}
// Generate global helper functions.
if (parser_.root_struct_def_) {
auto &struct_def = *parser_.root_struct_def_;
if (struct_def.defined_namespace != ns) { continue; }
SetNameSpace(struct_def.defined_namespace);
GenRootTableFuncs(struct_def);
}
}
if (cur_name_space_) SetNameSpace(nullptr);
const auto file_path = GeneratedFileName(path_, file_name_, parser_.opts);
const auto final_code = code_.ToString();
return SaveFile(file_path.c_str(), final_code, false);
}
private:
CodeWriter code_;
std::set<std::string> keywords_;
// This tracks the current namespace so we can insert namespace declarations.
const Namespace *cur_name_space_;
const Namespace *CurrentNameSpace() const { return cur_name_space_; }
// Determine if a Type needs a lifetime template parameter when used in the
// Rust builder args.
bool TableBuilderTypeNeedsLifetime(const Type &type) const {
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
case ftBool:
case ftEnumKey:
case ftUnionKey:
case ftUnionValue: {
return false;
}
default: {
return true;
}
}
}
// Determine if a table args rust type needs a lifetime template parameter.
bool TableBuilderArgsNeedsLifetime(const StructDef &struct_def) const {
FLATBUFFERS_ASSERT(!struct_def.fixed);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
if (field.deprecated) { continue; }
if (TableBuilderTypeNeedsLifetime(field.value.type)) { return true; }
}
return false;
}
// Determine if a Type needs to be copied (for endian safety) when used in a
// Struct.
bool StructMemberAccessNeedsCopy(const Type &type) const {
switch (GetFullType(type)) {
case ftInteger: // requires endian swap
case ftFloat: // requires endian swap
case ftBool: // no endian-swap, but do the copy for UX consistency
case ftEnumKey: {
return true;
} // requires endian swap
case ftStruct: {
return false;
} // no endian swap
default: {
// logic error: no other types can be struct members.
FLATBUFFERS_ASSERT(false && "invalid struct member type");
return false; // only to satisfy compiler's return analysis
}
}
}
std::string EscapeKeyword(const std::string &name) const {
return keywords_.find(name) == keywords_.end() ? name : name + "_";
}
std::string Name(const Definition &def) const {
return EscapeKeyword(def.name);
}
std::string Name(const EnumVal &ev) const { return EscapeKeyword(ev.name); }
std::string WrapInNameSpace(const Definition &def) const {
return WrapInNameSpace(def.defined_namespace, Name(def));
}
std::string WrapInNameSpace(const Namespace *ns,
const std::string &name) const {
if (CurrentNameSpace() == ns) return name;
std::string prefix = GetRelativeNamespaceTraversal(CurrentNameSpace(), ns);
return prefix + name;
}
// Determine the namespace traversal needed from the Rust crate root.
// This may be useful in the future for referring to included files, but is
// currently unused.
std::string GetAbsoluteNamespaceTraversal(const Namespace *dst) const {
std::stringstream stream;
stream << "::";
for (auto d = dst->components.begin(); d != dst->components.end(); ++d) {
stream << MakeSnakeCase(*d) + "::";
}
return stream.str();
}
// Determine the relative namespace traversal needed to reference one
// namespace from another namespace. This is useful because it does not force
// the user to have a particular file layout. (If we output absolute
// namespace paths, that may require users to organize their Rust crates in a
// particular way.)
std::string GetRelativeNamespaceTraversal(const Namespace *src,
const Namespace *dst) const {
// calculate the path needed to reference dst from src.
// example: f(A::B::C, A::B::C) -> (none)
// example: f(A::B::C, A::B) -> super::
// example: f(A::B::C, A::B::D) -> super::D
// example: f(A::B::C, A) -> super::super::
// example: f(A::B::C, D) -> super::super::super::D
// example: f(A::B::C, D::E) -> super::super::super::D::E
// example: f(A, D::E) -> super::D::E
// does not include leaf object (typically a struct type).
size_t i = 0;
std::stringstream stream;
auto s = src->components.begin();
auto d = dst->components.begin();
for (;;) {
if (s == src->components.end()) { break; }
if (d == dst->components.end()) { break; }
if (*s != *d) { break; }
++s;
++d;
++i;
}
for (; s != src->components.end(); ++s) { stream << "super::"; }
for (; d != dst->components.end(); ++d) {
stream << MakeSnakeCase(*d) + "::";
}
return stream.str();
}
// Generate a comment from the schema.
void GenComment(const std::vector<std::string> &dc, const char *prefix = "") {
std::string text;
::flatbuffers::GenComment(dc, &text, nullptr, prefix);
code_ += text + "\\";
}
// Return a Rust type from the table in idl.h.
std::string GetTypeBasic(const Type &type) const {
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
case ftBool:
case ftEnumKey:
case ftUnionKey: {
break;
}
default: {
FLATBUFFERS_ASSERT(false && "incorrect type given");
}
}
// clang-format off
static const char * const ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
RTYPE, ...) \
#RTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
// clang-format on
if (type.enum_def) { return WrapInNameSpace(*type.enum_def); }
return ctypename[type.base_type];
}
// Look up the native type for an enum. This will always be an integer like
// u8, i32, etc.
std::string GetEnumTypeForDecl(const Type &type) {
const auto ft = GetFullType(type);
if (!(ft == ftEnumKey || ft == ftUnionKey)) {
FLATBUFFERS_ASSERT(false && "precondition failed in GetEnumTypeForDecl");
}
// clang-format off
static const char *ctypename[] = {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \
RTYPE, ...) \
#RTYPE,
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD
};
// clang-format on
// Enums can be bools, but their Rust representation must be a u8, as used
// in the repr attribute (#[repr(bool)] is an invalid attribute).
if (type.base_type == BASE_TYPE_BOOL) return "u8";
return ctypename[type.base_type];
}
// Return a Rust type for any type (scalar, table, struct) specifically for
// using a FlatBuffer.
std::string GetTypeGet(const Type &type) const {
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
case ftBool:
case ftEnumKey:
case ftUnionKey: {
return GetTypeBasic(type);
}
case ftTable: {
return WrapInNameSpace(type.struct_def->defined_namespace,
type.struct_def->name) +
"<'a>";
}
default: {
return WrapInNameSpace(type.struct_def->defined_namespace,
type.struct_def->name);
}
}
}
std::string GetEnumValUse(const EnumDef &enum_def,
const EnumVal &enum_val) const {
return Name(enum_def) + "::" + Name(enum_val);
}
// Generate an enum declaration,
// an enum string lookup table,
// an enum match function,
// and an enum array of values
void GenEnum(const EnumDef &enum_def) {
code_.SetValue("ENUM_NAME", Name(enum_def));
code_.SetValue("BASE_TYPE", GetEnumTypeForDecl(enum_def.underlying_type));
GenComment(enum_def.doc_comment);
code_ += "#[allow(non_camel_case_types)]";
code_ += "#[repr({{BASE_TYPE}})]";
code_ +=
"#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]";
code_ += "pub enum " + Name(enum_def) + " {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
const auto &ev = **it;
GenComment(ev.doc_comment, " ");
code_.SetValue("KEY", Name(ev));
code_.SetValue("VALUE", enum_def.ToString(ev));
code_ += " {{KEY}} = {{VALUE}},";
}
const EnumVal *minv = enum_def.MinValue();
const EnumVal *maxv = enum_def.MaxValue();
FLATBUFFERS_ASSERT(minv && maxv);
code_ += "";
code_ += "}";
code_ += "";
code_.SetValue("ENUM_NAME", Name(enum_def));
code_.SetValue("ENUM_NAME_SNAKE", MakeSnakeCase(Name(enum_def)));
code_.SetValue("ENUM_NAME_CAPS", MakeUpper(MakeSnakeCase(Name(enum_def))));
code_.SetValue("ENUM_MIN_BASE_VALUE", enum_def.ToString(*minv));
code_.SetValue("ENUM_MAX_BASE_VALUE", enum_def.ToString(*maxv));
// Generate enum constants, and impls for Follow, EndianScalar, and Push.
code_ += "pub const ENUM_MIN_{{ENUM_NAME_CAPS}}: {{BASE_TYPE}} = \\";
code_ += "{{ENUM_MIN_BASE_VALUE}};";
code_ += "pub const ENUM_MAX_{{ENUM_NAME_CAPS}}: {{BASE_TYPE}} = \\";
code_ += "{{ENUM_MAX_BASE_VALUE}};";
code_ += "";
code_ += "impl<'a> flatbuffers::Follow<'a> for {{ENUM_NAME}} {";
code_ += " type Inner = Self;";
code_ += " #[inline]";
code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
code_ += " flatbuffers::read_scalar_at::<Self>(buf, loc)";
code_ += " }";
code_ += "}";
code_ += "";
code_ += "impl flatbuffers::EndianScalar for {{ENUM_NAME}} {";
code_ += " #[inline]";
code_ += " fn to_little_endian(self) -> Self {";
code_ += " let n = {{BASE_TYPE}}::to_le(self as {{BASE_TYPE}});";
code_ += " let p = &n as *const {{BASE_TYPE}} as *const {{ENUM_NAME}};";
code_ += " unsafe { *p }";
code_ += " }";
code_ += " #[inline]";
code_ += " fn from_little_endian(self) -> Self {";
code_ += " let n = {{BASE_TYPE}}::from_le(self as {{BASE_TYPE}});";
code_ += " let p = &n as *const {{BASE_TYPE}} as *const {{ENUM_NAME}};";
code_ += " unsafe { *p }";
code_ += " }";
code_ += "}";
code_ += "";
code_ += "impl flatbuffers::Push for {{ENUM_NAME}} {";
code_ += " type Output = {{ENUM_NAME}};";
code_ += " #[inline]";
code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {";
code_ +=
" flatbuffers::emplace_scalar::<{{ENUM_NAME}}>"
"(dst, *self);";
code_ += " }";
code_ += "}";
code_ += "";
// Generate an array of all enumeration values.
auto num_fields = NumToString(enum_def.size());
code_ += "#[allow(non_camel_case_types)]";
code_ += "pub const ENUM_VALUES_{{ENUM_NAME_CAPS}}:[{{ENUM_NAME}}; " +
num_fields + "] = [";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
const auto &ev = **it;
auto value = GetEnumValUse(enum_def, ev);
auto suffix = *it != enum_def.Vals().back() ? "," : "";
code_ += " " + value + suffix;
}
code_ += "];";
code_ += "";
// Generate a string table for enum values.
// Problem is, if values are very sparse that could generate really big
// tables. Ideally in that case we generate a map lookup instead, but for
// the moment we simply don't output a table at all.
auto range = enum_def.Distance();
// Average distance between values above which we consider a table
// "too sparse". Change at will.
static const uint64_t kMaxSparseness = 5;
if (range / static_cast<uint64_t>(enum_def.size()) < kMaxSparseness) {
code_ += "#[allow(non_camel_case_types)]";
code_ += "pub const ENUM_NAMES_{{ENUM_NAME_CAPS}}:[&'static str; " +
NumToString(range + 1) + "] = [";
auto val = enum_def.Vals().front();
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end();
++it) {
auto ev = *it;
for (auto k = enum_def.Distance(val, ev); k > 1; --k) {
code_ += " \"\",";
}
val = ev;
auto suffix = *it != enum_def.Vals().back() ? "," : "";
code_ += " \"" + Name(*ev) + "\"" + suffix;
}
code_ += "];";
code_ += "";
code_ +=
"pub fn enum_name_{{ENUM_NAME_SNAKE}}(e: {{ENUM_NAME}}) -> "
"&'static str {";
code_ += " let index = e as {{BASE_TYPE}}\\";
if (enum_def.MinValue()->IsNonZero()) {
auto vals = GetEnumValUse(enum_def, *enum_def.MinValue());
code_ += " - " + vals + " as {{BASE_TYPE}}\\";
}
code_ += ";";
code_ += " ENUM_NAMES_{{ENUM_NAME_CAPS}}[index as usize]";
code_ += "}";
code_ += "";
}
if (enum_def.is_union) {
// Generate tyoesafe offset(s) for unions
code_.SetValue("NAME", Name(enum_def));
code_.SetValue("UNION_OFFSET_NAME", Name(enum_def) + "UnionTableOffset");
code_ += "pub struct {{UNION_OFFSET_NAME}} {}";
}
}
std::string GetFieldOffsetName(const FieldDef &field) {
return "VT_" + MakeUpper(Name(field));
}
std::string GetDefaultConstant(const FieldDef &field) {
return field.value.type.base_type == BASE_TYPE_FLOAT
? field.value.constant + ""
: field.value.constant;
}
std::string GetDefaultScalarValue(const FieldDef &field) {
switch (GetFullType(field.value.type)) {
case ftInteger: {
return GetDefaultConstant(field);
}
case ftFloat: {
return GetDefaultConstant(field);
}
case ftBool: {
return field.value.constant == "0" ? "false" : "true";
}
case ftUnionKey:
case ftEnumKey: {
auto ev = field.value.type.enum_def->FindByValue(field.value.constant);
assert(ev);
return WrapInNameSpace(field.value.type.enum_def->defined_namespace,
GetEnumValUse(*field.value.type.enum_def, *ev));
}
// All pointer-ish types have a default value of None, because they are
// wrapped in Option.
default: {
return "None";
}
}
}
// Create the return type for fields in the *BuilderArgs structs that are
// used to create Tables.
//
// Note: we could make all inputs to the BuilderArgs be an Option, as well
// as all outputs. But, the UX of Flatbuffers is that the user doesn't get to
// know if the value is default or not, because there are three ways to
// return a default value:
// 1) return a stored value that happens to be the default,
// 2) return a hardcoded value because the relevant vtable field is not in
// the vtable, or
// 3) return a hardcoded value because the vtable field value is set to zero.
std::string TableBuilderArgsDefnType(const FieldDef &field,
const std::string &lifetime) {
const Type &type = field.value.type;
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
case ftBool: {
const auto typname = GetTypeBasic(type);
return typname;
}
case ftStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "Option<&" + lifetime + " " + typname + ">";
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "Option<flatbuffers::WIPOffset<" + typname + "<" + lifetime +
">>>";
}
case ftString: {
return "Option<flatbuffers::WIPOffset<&" + lifetime + " str>>";
}
case ftEnumKey:
case ftUnionKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return typname;
}
case ftUnionValue: {
return "Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>>";
}
case ftVectorOfInteger:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", " + typname + ">>>";
}
case ftVectorOfBool: {
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", bool>>>";
}
case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", " + typname + ">>>";
}
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", " + typname + ">>>";
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime +
">>>>>";
}
case ftVectorOfString: {
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>>>";
}
case ftVectorOfUnionValue: {
const auto typname =
WrapInNameSpace(*type.enum_def) + "UnionTableOffset";
return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<"
"flatbuffers::Table<" +
lifetime + ">>>>";
}
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
std::string TableBuilderArgsDefaultValue(const FieldDef &field) {
return GetDefaultScalarValue(field);
}
std::string TableBuilderAddFuncDefaultValue(const FieldDef &field) {
// All branches of switch do the same action!
switch (GetFullType(field.value.type)) {
case ftUnionKey:
case ftEnumKey: {
const std::string basetype =
GetTypeBasic(field.value.type); //<- never used
return GetDefaultScalarValue(field);
}
default: {
return GetDefaultScalarValue(field);
}
}
}
std::string TableBuilderArgsAddFuncType(const FieldDef &field,
const std::string &lifetime) {
const Type &type = field.value.type;
switch (GetFullType(field.value.type)) {
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " +
typname + ">>";
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime +
">>>>";
}
case ftVectorOfInteger:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " +
typname + ">>";
}
case ftVectorOfBool: {
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", bool>>";
}
case ftVectorOfString: {
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>>";
}
case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " +
typname + ">>";
}
case ftVectorOfUnionValue: {
return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<flatbuffers::Table<" + lifetime +
">>>";
}
case ftEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return typname;
}
case ftStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "&" + lifetime + " " + typname + "";
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "flatbuffers::WIPOffset<" + typname + "<" + lifetime + ">>";
}
case ftInteger:
case ftFloat: {
const auto typname = GetTypeBasic(type);
return typname;
}
case ftBool: {
return "bool";
}
case ftString: {
return "flatbuffers::WIPOffset<&" + lifetime + " str>";
}
case ftUnionKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return typname;
}
case ftUnionValue: {
return "flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>";
}
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
std::string TableBuilderArgsAddFuncBody(const FieldDef &field) {
const Type &type = field.value.type;
switch (GetFullType(field.value.type)) {
case ftInteger:
case ftFloat: {
const auto typname = GetTypeBasic(field.value.type);
return "self.fbb_.push_slot::<" + typname + ">";
}
case ftBool: {
return "self.fbb_.push_slot::<bool>";
}
case ftEnumKey:
case ftUnionKey: {
const auto underlying_typname = GetTypeBasic(type);
return "self.fbb_.push_slot::<" + underlying_typname + ">";
}
case ftStruct: {
const std::string typname = WrapInNameSpace(*type.struct_def);
return "self.fbb_.push_slot_always::<&" + typname + ">";
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<" +
typname + ">>";
}
case ftUnionValue:
case ftString:
case ftVectorOfInteger:
case ftVectorOfFloat:
case ftVectorOfBool:
case ftVectorOfEnumKey:
case ftVectorOfStruct:
case ftVectorOfTable:
case ftVectorOfString:
case ftVectorOfUnionValue: {
return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>";
}
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
std::string GenTableAccessorFuncReturnType(const FieldDef &field,
const std::string &lifetime) {
const Type &type = field.value.type;
switch (GetFullType(field.value.type)) {
case ftInteger:
case ftFloat: {
const auto typname = GetTypeBasic(type);
return typname;
}
case ftBool: {
return "bool";
}
case ftStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return WrapInOptionIfNotRequired("&" + lifetime + " " + typname,
field.required);
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return WrapInOptionIfNotRequired(typname + "<" + lifetime + ">",
field.required);
}
case ftEnumKey:
case ftUnionKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return typname;
}
case ftUnionValue: {
return WrapInOptionIfNotRequired("flatbuffers::Table<" + lifetime + ">",
field.required);
}
case ftString: {
return WrapInOptionIfNotRequired("&" + lifetime + " str",
field.required);
}
case ftVectorOfInteger:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
if (IsOneByte(type.VectorType().base_type)) {
return WrapInOptionIfNotRequired(
"&" + lifetime + " [" + typname + "]", field.required);
}
return WrapInOptionIfNotRequired(
"flatbuffers::Vector<" + lifetime + ", " + typname + ">",
field.required);
}
case ftVectorOfBool: {
return WrapInOptionIfNotRequired("&" + lifetime + " [bool]",
field.required);
}
case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return WrapInOptionIfNotRequired(
"flatbuffers::Vector<" + lifetime + ", " + typname + ">",
field.required);
}
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]",
field.required);
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<" +
typname + "<" + lifetime + ">>>",
field.required);
}
case ftVectorOfString: {
return WrapInOptionIfNotRequired(
"flatbuffers::Vector<" + lifetime +
", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>",
field.required);
}
case ftVectorOfUnionValue: {
FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported");
// TODO(rw): when we do support these, we should consider using the
// Into trait to convert tables to typesafe union values.
return "INVALID_CODE_GENERATION"; // for return analysis
}
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
std::string GenTableAccessorFuncBody(const FieldDef &field,
const std::string &lifetime,
const std::string &offset_prefix) {
const std::string offset_name =
offset_prefix + "::" + GetFieldOffsetName(field);
const Type &type = field.value.type;
switch (GetFullType(field.value.type)) {
case ftInteger:
case ftFloat:
case ftBool: {
const auto typname = GetTypeBasic(type);
const auto default_value = GetDefaultScalarValue(field);
return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" +
default_value + ")).unwrap()";
}
case ftStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return AddUnwrapIfRequired(
"self._tab.get::<" + typname + ">(" + offset_name + ", None)",
field.required);
}
case ftTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return AddUnwrapIfRequired(
"self._tab.get::<flatbuffers::ForwardsUOffset<" + typname + "<" +
lifetime + ">>>(" + offset_name + ", None)",
field.required);
}
case ftUnionValue: {
return AddUnwrapIfRequired(
"self._tab.get::<flatbuffers::ForwardsUOffset<"
"flatbuffers::Table<" +
lifetime + ">>>(" + offset_name + ", None)",
field.required);
}
case ftUnionKey:
case ftEnumKey: {
const auto underlying_typname = GetTypeBasic(type); //<- never used
const auto typname = WrapInNameSpace(*type.enum_def);
const auto default_value = GetDefaultScalarValue(field);
return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" +
default_value + ")).unwrap()";
}
case ftString: {
return AddUnwrapIfRequired(
"self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(" +
offset_name + ", None)",
field.required);
}
case ftVectorOfInteger:
case ftVectorOfFloat: {
const auto typname = GetTypeBasic(type.VectorType());
std::string s =
"self._tab.get::<flatbuffers::ForwardsUOffset<"
"flatbuffers::Vector<" +
lifetime + ", " + typname + ">>>(" + offset_name + ", None)";
// single-byte values are safe to slice
if (IsOneByte(type.VectorType().base_type)) {
s += ".map(|v| v.safe_slice())";
}
return AddUnwrapIfRequired(s, field.required);
}
case ftVectorOfBool: {
return AddUnwrapIfRequired(
"self._tab.get::<flatbuffers::ForwardsUOffset<"
"flatbuffers::Vector<" +
lifetime + ", bool>>>(" + offset_name +
", None).map(|v| v.safe_slice())",
field.required);
}
case ftVectorOfEnumKey: {
const auto typname = WrapInNameSpace(*type.enum_def);
return AddUnwrapIfRequired(
"self._tab.get::<flatbuffers::ForwardsUOffset<"
"flatbuffers::Vector<" +
lifetime + ", " + typname + ">>>(" + offset_name + ", None)",
field.required);
}
case ftVectorOfStruct: {
const auto typname = WrapInNameSpace(*type.struct_def);
return AddUnwrapIfRequired(
"self._tab.get::<flatbuffers::ForwardsUOffset<"
"flatbuffers::Vector<" +
typname + ">>>(" + offset_name +
", None).map(|v| v.safe_slice() )",
field.required);
}
case ftVectorOfTable: {
const auto typname = WrapInNameSpace(*type.struct_def);
return AddUnwrapIfRequired(
"self._tab.get::<flatbuffers::ForwardsUOffset<"
"flatbuffers::Vector<flatbuffers::ForwardsUOffset<" +
typname + "<" + lifetime + ">>>>>(" + offset_name + ", None)",
field.required);
}
case ftVectorOfString: {
return AddUnwrapIfRequired(
"self._tab.get::<flatbuffers::ForwardsUOffset<"
"flatbuffers::Vector<flatbuffers::ForwardsUOffset<&" +
lifetime + " str>>>>(" + offset_name + ", None)",
field.required);
}
case ftVectorOfUnionValue: {
FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported");
return "INVALID_CODE_GENERATION"; // for return analysis
}
}
return "INVALID_CODE_GENERATION"; // for return analysis
}
bool TableFieldReturnsOption(const Type &type) {
switch (GetFullType(type)) {
case ftInteger:
case ftFloat:
case ftBool:
case ftEnumKey:
case ftUnionKey: return false;
default: return true;
}
}
// Generates a fully-qualified name getter for use with --gen-name-strings
void GenFullyQualifiedNameGetter(const StructDef &struct_def,
const std::string &name) {
code_ += " pub const fn get_fully_qualified_name() -> &'static str {";
code_ += " \"" +
struct_def.defined_namespace->GetFullyQualifiedName(name) + "\"";
code_ += " }";
code_ += "";
}
// Generate an accessor struct, builder struct, and create function for a
// table.
void GenTable(const StructDef &struct_def) {
code_.SetValue("STRUCT_NAME", Name(struct_def));
code_.SetValue("OFFSET_TYPELABEL", Name(struct_def) + "Offset");
code_.SetValue("STRUCT_NAME_SNAKECASE", MakeSnakeCase(Name(struct_def)));
// Generate an offset type, the base type, the Follow impl, and the
// init_from_table impl.
code_ += "pub enum {{OFFSET_TYPELABEL}} {}";
code_ += "#[derive(Copy, Clone, Debug, PartialEq)]";
code_ += "";
GenComment(struct_def.doc_comment);
code_ += "pub struct {{STRUCT_NAME}}<'a> {";
code_ += " pub _tab: flatbuffers::Table<'a>,";
code_ += "}";
code_ += "";
code_ += "impl<'a> flatbuffers::Follow<'a> for {{STRUCT_NAME}}<'a> {";
code_ += " type Inner = {{STRUCT_NAME}}<'a>;";
code_ += " #[inline]";
code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
code_ += " Self {";
code_ += " _tab: flatbuffers::Table { buf: buf, loc: loc },";
code_ += " }";
code_ += " }";
code_ += "}";
code_ += "";
code_ += "impl<'a> {{STRUCT_NAME}}<'a> {";
if (parser_.opts.generate_name_strings) {
GenFullyQualifiedNameGetter(struct_def, struct_def.name);
}
code_ += " #[inline]";
code_ +=
" pub fn init_from_table(table: flatbuffers::Table<'a>) -> "
"Self {";
code_ += " {{STRUCT_NAME}} {";
code_ += " _tab: table,";
code_ += " }";
code_ += " }";
// Generate a convenient create* function that uses the above builder
// to create a table in one function call.
code_.SetValue("MAYBE_US", struct_def.fields.vec.size() == 0 ? "_" : "");
code_.SetValue("MAYBE_LT",
TableBuilderArgsNeedsLifetime(struct_def) ? "<'args>" : "");
code_ += " #[allow(unused_mut)]";
code_ += " pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>(";
code_ +=
" _fbb: "
"&'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,";
code_ +=
" {{MAYBE_US}}args: &'args {{STRUCT_NAME}}Args{{MAYBE_LT}})"
" -> flatbuffers::WIPOffset<{{STRUCT_NAME}}<'bldr>> {";
code_ += " let mut builder = {{STRUCT_NAME}}Builder::new(_fbb);";
for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1;
size; size /= 2) {
for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); ++it) {
const auto &field = **it;
// TODO(rw): fully understand this sortbysize usage
if (!field.deprecated && (!struct_def.sortbysize ||
size == SizeOf(field.value.type.base_type))) {
code_.SetValue("FIELD_NAME", Name(field));
if (TableFieldReturnsOption(field.value.type)) {
code_ +=
" if let Some(x) = args.{{FIELD_NAME}} "
"{ builder.add_{{FIELD_NAME}}(x); }";
} else {
code_ += " builder.add_{{FIELD_NAME}}(args.{{FIELD_NAME}});";
}
}
}
}
code_ += " builder.finish()";
code_ += " }";
code_ += "";
// Generate field id constants.
if (struct_def.fields.vec.size() > 0) {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
if (field.deprecated) {
// Deprecated fields won't be accessible.
continue;
}
code_.SetValue("OFFSET_NAME", GetFieldOffsetName(field));
code_.SetValue("OFFSET_VALUE", NumToString(field.value.offset));
code_ +=
" pub const {{OFFSET_NAME}}: flatbuffers::VOffsetT = "
"{{OFFSET_VALUE}};";
}
code_ += "";
}
// Generate the accessors. Each has one of two forms:
//
// If a value can be None:
// pub fn name(&'a self) -> Option<user_facing_type> {
// self._tab.get::<internal_type>(offset, defaultval)
// }
//
// If a value is always Some:
// pub fn name(&'a self) -> user_facing_type {
// self._tab.get::<internal_type>(offset, defaultval).unwrap()
// }
const auto offset_prefix = Name(struct_def);
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
if (field.deprecated) {
// Deprecated fields won't be accessible.
continue;
}
code_.SetValue("FIELD_NAME", Name(field));
code_.SetValue("RETURN_TYPE",
GenTableAccessorFuncReturnType(field, "'a"));
code_.SetValue("FUNC_BODY",
GenTableAccessorFuncBody(field, "'a", offset_prefix));
GenComment(field.doc_comment, " ");
code_ += " #[inline]";
code_ += " pub fn {{FIELD_NAME}}(&self) -> {{RETURN_TYPE}} {";
code_ += " {{FUNC_BODY}}";
code_ += " }";
// Generate a comparison function for this field if it is a key.
if (field.key) { GenKeyFieldMethods(field); }
// Generate a nested flatbuffer field, if applicable.
auto nested = field.attributes.Lookup("nested_flatbuffer");
if (nested) {
std::string qualified_name = nested->constant;
auto nested_root = parser_.LookupStruct(nested->constant);
if (nested_root == nullptr) {
qualified_name = parser_.current_namespace_->GetFullyQualifiedName(
nested->constant);
nested_root = parser_.LookupStruct(qualified_name);
}
FLATBUFFERS_ASSERT(nested_root); // Guaranteed to exist by parser.
(void)nested_root;
code_.SetValue("OFFSET_NAME",
offset_prefix + "::" + GetFieldOffsetName(field));
code_ +=
" pub fn {{FIELD_NAME}}_nested_flatbuffer(&'a self) -> "
" Option<{{STRUCT_NAME}}<'a>> {";
code_ += " match self.{{FIELD_NAME}}() {";
code_ += " None => { None }";
code_ += " Some(data) => {";
code_ += " use self::flatbuffers::Follow;";
code_ +=
" Some(<flatbuffers::ForwardsUOffset"
"<{{STRUCT_NAME}}<'a>>>::follow(data, 0))";
code_ += " },";
code_ += " }";
code_ += " }";
}
}
// Explicit specializations for union accessors
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
if (field.deprecated || field.value.type.base_type != BASE_TYPE_UNION) {
continue;
}
auto u = field.value.type.enum_def;
code_.SetValue("FIELD_NAME", Name(field));
code_.SetValue("FIELD_TYPE_FIELD_NAME", field.name);
for (auto u_it = u->Vals().begin(); u_it != u->Vals().end(); ++u_it) {
auto &ev = **u_it;
if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
auto table_init_type =
WrapInNameSpace(ev.union_type.struct_def->defined_namespace,
ev.union_type.struct_def->name);
code_.SetValue(
"U_ELEMENT_ENUM_TYPE",
WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev)));
code_.SetValue("U_ELEMENT_TABLE_TYPE", table_init_type);
code_.SetValue("U_ELEMENT_NAME", MakeSnakeCase(Name(ev)));
code_ += " #[inline]";
code_ += " #[allow(non_snake_case)]";
code_ +=
" pub fn {{FIELD_NAME}}_as_{{U_ELEMENT_NAME}}(&self) -> "
"Option<{{U_ELEMENT_TABLE_TYPE}}<'a>> {";
// If the user defined schemas name a field that clashes with a
// language reserved word, flatc will try to escape the field name by
// appending an underscore. This works well for most cases, except
// one. When generating union accessors (and referring to them
// internally within the code generated here), an extra underscore
// will be appended to the name, causing build failures.
//
// This only happens when unions have members that overlap with
// language reserved words.
//
// To avoid this problem the type field name is used unescaped here:
code_ +=
" if self.{{FIELD_TYPE_FIELD_NAME}}_type() == "
"{{U_ELEMENT_ENUM_TYPE}} {";
code_ +=
" self.{{FIELD_NAME}}().map(|u| "
"{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))";
code_ += " } else {";
code_ += " None";
code_ += " }";
code_ += " }";
code_ += "";
}
}
code_ += "}"; // End of table impl.
code_ += "";
// Generate an args struct:
code_.SetValue("MAYBE_LT",
TableBuilderArgsNeedsLifetime(struct_def) ? "<'a>" : "");
code_ += "pub struct {{STRUCT_NAME}}Args{{MAYBE_LT}} {";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
if (!field.deprecated) {
code_.SetValue("PARAM_NAME", Name(field));
code_.SetValue("PARAM_TYPE", TableBuilderArgsDefnType(field, "'a "));
code_ += " pub {{PARAM_NAME}}: {{PARAM_TYPE}},";
}
}
code_ += "}";
// Generate an impl of Default for the *Args type:
code_ += "impl<'a> Default for {{STRUCT_NAME}}Args{{MAYBE_LT}} {";
code_ += " #[inline]";
code_ += " fn default() -> Self {";
code_ += " {{STRUCT_NAME}}Args {";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
if (!field.deprecated) {
code_.SetValue("PARAM_VALUE", TableBuilderArgsDefaultValue(field));
code_.SetValue("REQ", field.required ? " // required field" : "");
code_.SetValue("PARAM_NAME", Name(field));
code_ += " {{PARAM_NAME}}: {{PARAM_VALUE}},{{REQ}}";
}
}
code_ += " }";
code_ += " }";
code_ += "}";
// Generate a builder struct:
code_ += "pub struct {{STRUCT_NAME}}Builder<'a: 'b, 'b> {";
code_ += " fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,";
code_ +=
" start_: flatbuffers::WIPOffset<"
"flatbuffers::TableUnfinishedWIPOffset>,";
code_ += "}";
// Generate builder functions:
code_ += "impl<'a: 'b, 'b> {{STRUCT_NAME}}Builder<'a, 'b> {";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
if (!field.deprecated) {
const bool is_scalar = IsScalar(field.value.type.base_type);
std::string offset = GetFieldOffsetName(field);
// Generate functions to add data, which take one of two forms.
//
// If a value has a default:
// fn add_x(x_: type) {
// fbb_.push_slot::<type>(offset, x_, Some(default));
// }
//
// If a value does not have a default:
// fn add_x(x_: type) {
// fbb_.push_slot_always::<type>(offset, x_);
// }
code_.SetValue("FIELD_NAME", Name(field));
code_.SetValue("FIELD_OFFSET", Name(struct_def) + "::" + offset);
code_.SetValue("FIELD_TYPE", TableBuilderArgsAddFuncType(field, "'b "));
code_.SetValue("FUNC_BODY", TableBuilderArgsAddFuncBody(field));
code_ += " #[inline]";
code_ +=
" pub fn add_{{FIELD_NAME}}(&mut self, {{FIELD_NAME}}: "
"{{FIELD_TYPE}}) {";
if (is_scalar) {
code_.SetValue("FIELD_DEFAULT_VALUE",
TableBuilderAddFuncDefaultValue(field));
code_ +=
" {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}}, "
"{{FIELD_DEFAULT_VALUE}});";
} else {
code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}});";
}
code_ += " }";
}
}
// Struct initializer (all fields required);
code_ += " #[inline]";
code_ +=
" pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> "
"{{STRUCT_NAME}}Builder<'a, 'b> {";
code_.SetValue("NUM_FIELDS", NumToString(struct_def.fields.vec.size()));
code_ += " let start = _fbb.start_table();";
code_ += " {{STRUCT_NAME}}Builder {";
code_ += " fbb_: _fbb,";
code_ += " start_: start,";
code_ += " }";
code_ += " }";
// finish() function.
code_ += " #[inline]";
code_ +=
" pub fn finish(self) -> "
"flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>> {";
code_ += " let o = self.fbb_.end_table(self.start_);";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
if (!field.deprecated && field.required) {
code_.SetValue("FIELD_NAME", MakeSnakeCase(Name(field)));
code_.SetValue("OFFSET_NAME", GetFieldOffsetName(field));
code_ +=
" self.fbb_.required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}},"
"\"{{FIELD_NAME}}\");";
}
}
code_ += " flatbuffers::WIPOffset::new(o.value())";
code_ += " }";
code_ += "}";
code_ += "";
}
// Generate functions to compare tables and structs by key. This function
// must only be called if the field key is defined.
void GenKeyFieldMethods(const FieldDef &field) {
FLATBUFFERS_ASSERT(field.key);
code_.SetValue("KEY_TYPE", GenTableAccessorFuncReturnType(field, ""));
code_ += " #[inline]";
code_ +=
" pub fn key_compare_less_than(&self, o: &{{STRUCT_NAME}}) -> "
" bool {";
code_ += " self.{{FIELD_NAME}}() < o.{{FIELD_NAME}}()";
code_ += " }";
code_ += "";
code_ += " #[inline]";
code_ +=
" pub fn key_compare_with_value(&self, val: {{KEY_TYPE}}) -> "
" ::std::cmp::Ordering {";
code_ += " let key = self.{{FIELD_NAME}}();";
code_ += " key.cmp(&val)";
code_ += " }";
}
// Generate functions for accessing the root table object. This function
// must only be called if the root table is defined.
void GenRootTableFuncs(const StructDef &struct_def) {
FLATBUFFERS_ASSERT(parser_.root_struct_def_ && "root table not defined");
auto name = Name(struct_def);
code_.SetValue("STRUCT_NAME", name);
code_.SetValue("STRUCT_NAME_SNAKECASE", MakeSnakeCase(name));
code_.SetValue("STRUCT_NAME_CAPS", MakeUpper(MakeSnakeCase(name)));
// The root datatype accessors:
code_ += "#[inline]";
code_ +=
"pub fn get_root_as_{{STRUCT_NAME_SNAKECASE}}<'a>(buf: &'a [u8])"
" -> {{STRUCT_NAME}}<'a> {";
code_ += " flatbuffers::get_root::<{{STRUCT_NAME}}<'a>>(buf)";
code_ += "}";
code_ += "";
code_ += "#[inline]";
code_ +=
"pub fn get_size_prefixed_root_as_{{STRUCT_NAME_SNAKECASE}}"
"<'a>(buf: &'a [u8]) -> {{STRUCT_NAME}}<'a> {";
code_ +=
" flatbuffers::get_size_prefixed_root::<{{STRUCT_NAME}}<'a>>"
"(buf)";
code_ += "}";
code_ += "";
if (parser_.file_identifier_.length()) {
// Declare the identifier
code_ += "pub const {{STRUCT_NAME_CAPS}}_IDENTIFIER: &'static str\\";
code_ += " = \"" + parser_.file_identifier_ + "\";";
code_ += "";
// Check if a buffer has the identifier.
code_ += "#[inline]";
code_ += "pub fn {{STRUCT_NAME_SNAKECASE}}_buffer_has_identifier\\";
code_ += "(buf: &[u8]) -> bool {";
code_ += " return flatbuffers::buffer_has_identifier(buf, \\";
code_ += "{{STRUCT_NAME_CAPS}}_IDENTIFIER, false);";
code_ += "}";
code_ += "";
code_ += "#[inline]";
code_ += "pub fn {{STRUCT_NAME_SNAKECASE}}_size_prefixed\\";
code_ += "_buffer_has_identifier(buf: &[u8]) -> bool {";
code_ += " return flatbuffers::buffer_has_identifier(buf, \\";
code_ += "{{STRUCT_NAME_CAPS}}_IDENTIFIER, true);";
code_ += "}";
code_ += "";
}
if (parser_.file_extension_.length()) {
// Return the extension
code_ += "pub const {{STRUCT_NAME_CAPS}}_EXTENSION: &'static str = \\";
code_ += "\"" + parser_.file_extension_ + "\";";
code_ += "";
}
// Finish a buffer with a given root object:
code_.SetValue("OFFSET_TYPELABEL", Name(struct_def) + "Offset");
code_ += "#[inline]";
code_ += "pub fn finish_{{STRUCT_NAME_SNAKECASE}}_buffer<'a, 'b>(";
code_ += " fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>,";
code_ += " root: flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>>) {";
if (parser_.file_identifier_.length()) {
code_ += " fbb.finish(root, Some({{STRUCT_NAME_CAPS}}_IDENTIFIER));";
} else {
code_ += " fbb.finish(root, None);";
}
code_ += "}";
code_ += "";
code_ += "#[inline]";
code_ +=
"pub fn finish_size_prefixed_{{STRUCT_NAME_SNAKECASE}}_buffer"
"<'a, 'b>("
"fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, "
"root: flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>>) {";
if (parser_.file_identifier_.length()) {
code_ +=
" fbb.finish_size_prefixed(root, "
"Some({{STRUCT_NAME_CAPS}}_IDENTIFIER));";
} else {
code_ += " fbb.finish_size_prefixed(root, None);";
}
code_ += "}";
}
static void GenPadding(
const FieldDef &field, std::string *code_ptr, int *id,
const std::function<void(int bits, std::string *code_ptr, int *id)> &f) {
if (field.padding) {
for (int i = 0; i < 4; i++) {
if (static_cast<int>(field.padding) & (1 << i)) {
f((1 << i) * 8, code_ptr, id);
}
}
assert(!(field.padding & ~0xF));
}
}
static void PaddingDefinition(int bits, std::string *code_ptr, int *id) {
*code_ptr +=
" padding" + NumToString((*id)++) + "__: u" + NumToString(bits) + ",";
}
static void PaddingInitializer(int bits, std::string *code_ptr, int *id) {
(void)bits;
*code_ptr += "padding" + NumToString((*id)++) + "__: 0,";
}
// Generate an accessor struct with constructor for a flatbuffers struct.
void GenStruct(const StructDef &struct_def) {
// Generates manual padding and alignment.
// Variables are private because they contain little endian data on all
// platforms.
GenComment(struct_def.doc_comment);
code_.SetValue("ALIGN", NumToString(struct_def.minalign));
code_.SetValue("STRUCT_NAME", Name(struct_def));
code_ += "// struct {{STRUCT_NAME}}, aligned to {{ALIGN}}";
code_ += "#[repr(C, align({{ALIGN}}))]";
// PartialEq is useful to derive because we can correctly compare structs
// for equality by just comparing their underlying byte data. This doesn't
// hold for PartialOrd/Ord.
code_ += "#[derive(Clone, Copy, Debug, PartialEq)]";
code_ += "pub struct {{STRUCT_NAME}} {";
int padding_id = 0;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
code_.SetValue("FIELD_TYPE", GetTypeGet(field.value.type));
code_.SetValue("FIELD_NAME", Name(field));
code_ += " {{FIELD_NAME}}_: {{FIELD_TYPE}},";
if (field.padding) {
std::string padding;
GenPadding(field, &padding, &padding_id, PaddingDefinition);
code_ += padding;
}
}
code_ += "} // pub struct {{STRUCT_NAME}}";
// Generate impls for SafeSliceAccess (because all structs are endian-safe),
// Follow for the value type, Follow for the reference type, Push for the
// value type, and Push for the reference type.
code_ += "impl flatbuffers::SafeSliceAccess for {{STRUCT_NAME}} {}";
code_ += "impl<'a> flatbuffers::Follow<'a> for {{STRUCT_NAME}} {";
code_ += " type Inner = &'a {{STRUCT_NAME}};";
code_ += " #[inline]";
code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
code_ += " <&'a {{STRUCT_NAME}}>::follow(buf, loc)";
code_ += " }";
code_ += "}";
code_ += "impl<'a> flatbuffers::Follow<'a> for &'a {{STRUCT_NAME}} {";
code_ += " type Inner = &'a {{STRUCT_NAME}};";
code_ += " #[inline]";
code_ += " fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {";
code_ += " flatbuffers::follow_cast_ref::<{{STRUCT_NAME}}>(buf, loc)";
code_ += " }";
code_ += "}";
code_ += "impl<'b> flatbuffers::Push for {{STRUCT_NAME}} {";
code_ += " type Output = {{STRUCT_NAME}};";
code_ += " #[inline]";
code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {";
code_ += " let src = unsafe {";
code_ +=
" ::std::slice::from_raw_parts("
"self as *const {{STRUCT_NAME}} as *const u8, Self::size())";
code_ += " };";
code_ += " dst.copy_from_slice(src);";
code_ += " }";
code_ += "}";
code_ += "impl<'b> flatbuffers::Push for &'b {{STRUCT_NAME}} {";
code_ += " type Output = {{STRUCT_NAME}};";
code_ += "";
code_ += " #[inline]";
code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {";
code_ += " let src = unsafe {";
code_ +=
" ::std::slice::from_raw_parts("
"*self as *const {{STRUCT_NAME}} as *const u8, Self::size())";
code_ += " };";
code_ += " dst.copy_from_slice(src);";
code_ += " }";
code_ += "}";
code_ += "";
code_ += "";
// Generate a constructor that takes all fields as arguments.
code_ += "impl {{STRUCT_NAME}} {";
std::string arg_list;
std::string init_list;
padding_id = 0;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
const auto member_name = Name(field) + "_";
const auto reference =
StructMemberAccessNeedsCopy(field.value.type) ? "" : "&'a ";
const auto arg_name = "_" + Name(field);
const auto arg_type = reference + GetTypeGet(field.value.type);
if (it != struct_def.fields.vec.begin()) { arg_list += ", "; }
arg_list += arg_name + ": ";
arg_list += arg_type;
init_list += " " + member_name;
if (StructMemberAccessNeedsCopy(field.value.type)) {
init_list += ": " + arg_name + ".to_little_endian(),\n";
} else {
init_list += ": *" + arg_name + ",\n";
}
}
code_.SetValue("ARG_LIST", arg_list);
code_.SetValue("INIT_LIST", init_list);
code_ += " pub fn new<'a>({{ARG_LIST}}) -> Self {";
code_ += " {{STRUCT_NAME}} {";
code_ += "{{INIT_LIST}}";
padding_id = 0;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
if (field.padding) {
std::string padding;
GenPadding(field, &padding, &padding_id, PaddingInitializer);
code_ += " " + padding;
}
}
code_ += " }";
code_ += " }";
if (parser_.opts.generate_name_strings) {
GenFullyQualifiedNameGetter(struct_def, struct_def.name);
}
// Generate accessor methods for the struct.
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
auto field_type = TableBuilderArgsAddFuncType(field, "'a");
auto member = "self." + Name(field) + "_";
auto value = StructMemberAccessNeedsCopy(field.value.type)
? member + ".from_little_endian()"
: member;
code_.SetValue("FIELD_NAME", Name(field));
code_.SetValue("FIELD_TYPE", field_type);
code_.SetValue("FIELD_VALUE", value);
code_.SetValue("REF", IsStruct(field.value.type) ? "&" : "");
GenComment(field.doc_comment, " ");
code_ += " pub fn {{FIELD_NAME}}<'a>(&'a self) -> {{FIELD_TYPE}} {";
code_ += " {{REF}}{{FIELD_VALUE}}";
code_ += " }";
// Generate a comparison function for this field if it is a key.
if (field.key) { GenKeyFieldMethods(field); }
}
code_ += "}";
code_ += "";
}
void GenNamespaceImports(const int white_spaces) {
std::string indent = std::string(white_spaces, ' ');
code_ += "";
for (auto it = parser_.included_files_.begin();
it != parser_.included_files_.end(); ++it) {
if (it->second.empty()) continue;
auto noext = flatbuffers::StripExtension(it->second);
auto basename = flatbuffers::StripPath(noext);
code_ += indent + "use crate::" + basename + "_generated::*;";
}
code_ += indent + "use std::mem;";
code_ += indent + "use std::cmp::Ordering;";
code_ += "";
code_ += indent + "extern crate flatbuffers;";
code_ += indent + "use self::flatbuffers::EndianScalar;";
}
// Set up the correct namespace. This opens a namespace if the current
// namespace is different from the target namespace. This function
// closes and opens the namespaces only as necessary.
//
// The file must start and end with an empty (or null) namespace so that
// namespaces are properly opened and closed.
void SetNameSpace(const Namespace *ns) {
if (cur_name_space_ == ns) { return; }
// Compute the size of the longest common namespace prefix.
// If cur_name_space is A::B::C::D and ns is A::B::E::F::G,
// the common prefix is A::B:: and we have old_size = 4, new_size = 5
// and common_prefix_size = 2
size_t old_size = cur_name_space_ ? cur_name_space_->components.size() : 0;
size_t new_size = ns ? ns->components.size() : 0;
size_t common_prefix_size = 0;
while (common_prefix_size < old_size && common_prefix_size < new_size &&
ns->components[common_prefix_size] ==
cur_name_space_->components[common_prefix_size]) {
common_prefix_size++;
}
// Close cur_name_space in reverse order to reach the common prefix.
// In the previous example, D then C are closed.
for (size_t j = old_size; j > common_prefix_size; --j) {
code_ += "} // pub mod " + cur_name_space_->components[j - 1];
}
if (old_size != common_prefix_size) { code_ += ""; }
// open namespace parts to reach the ns namespace
// in the previous example, E, then F, then G are opened
for (auto j = common_prefix_size; j != new_size; ++j) {
code_ += "#[allow(unused_imports, dead_code)]";
code_ += "pub mod " + MakeSnakeCase(ns->components[j]) + " {";
// Generate local namespace imports.
GenNamespaceImports(2);
}
if (new_size != common_prefix_size) { code_ += ""; }
cur_name_space_ = ns;
}
};
} // namespace rust
bool GenerateRust(const Parser &parser, const std::string &path,
const std::string &file_name) {
rust::RustGenerator generator(parser, path, file_name);
return generator.generate();
}
std::string RustMakeRule(const Parser &parser, const std::string &path,
const std::string &file_name) {
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
rust::RustGenerator generator(parser, path, file_name);
std::string make_rule =
generator.GeneratedFileName(path, filebase, parser.opts) + ": ";
auto included_files = parser.GetIncludedFilesRecursive(file_name);
for (auto it = included_files.begin(); it != included_files.end(); ++it) {
make_rule += " " + *it;
}
return make_rule;
}
} // namespace flatbuffers
// TODO(rw): Generated code should import other generated files.
// TODO(rw): Generated code should refer to namespaces in included files in a
// way that makes them referrable.
// TODO(rw): Generated code should indent according to nesting level.
// TODO(rw): Generated code should generate endian-safe Debug impls.
// TODO(rw): Generated code could use a Rust-only enum type to access unions,
// instead of making the user use _type() to manually switch.
// TODO(maxburke): There should be test schemas added that use language
// keywords as fields of structs, tables, unions, enums, to make sure
// that internal code generated references escaped names correctly.
// TODO(maxburke): We should see if there is a more flexible way of resolving
// module paths for use declarations. Right now if schemas refer to
// other flatbuffer files, the include paths in emitted Rust bindings
// are crate-relative which may undesirable.
| 1 | 18,024 | Please flip the conditional to be `if (field.required) { ... }`. | google-flatbuffers | java |
@@ -11,7 +11,10 @@ describe 'User creation when logging in with Oauth to view a protected page' do
get '/auth/myusa/callback'
}.to change { User.count }.by(1)
- expect(User.last.email_address).to eq('[email protected]')
+ new_user = User.last
+ expect(new_user.email_address).to eq('[email protected]')
+ expect(new_user.first_name).to eq("Georgie")
+ expect(new_user.last_name).to eq("Jetsonian")
end
it 'does not create a user if the current user already exists' do | 1 | describe 'User creation when logging in with Oauth to view a protected page' do
StructUser = Struct.new(:email_address, :first_name, :last_name)
before do
user = StructUser.new('[email protected]', 'Georgie', 'Jetsonian')
setup_mock_auth(:myusa, user)
end
it 'creates a new user if the current user does not already exist' do
expect {
get '/auth/myusa/callback'
}.to change { User.count }.by(1)
expect(User.last.email_address).to eq('[email protected]')
end
it 'does not create a user if the current user already exists' do
create(:user, email_address: '[email protected]')
expect {
get '/auth/myusa/callback'
}.to_not change { User.count }
end
it 'redirects a newly logged in user to the carts screen' do
create(:user, email_address: '[email protected]')
expect {
get '/auth/myusa/callback'
}.to_not change { User.count }
expect(response).to redirect_to('/proposals')
end
end
| 1 | 15,373 | should we create a fixture without first name and last name and have a spec like this one that uses it to make sure nothing errors out when they are not present? | 18F-C2 | rb |
@@ -35,4 +35,9 @@ interface PythonSnippetSet<Element> {
* Generates the result module with a set of accumulated imports.
*/
Doc generateModule(Element element, Doc body, Iterable<String> imports);
+
+ /**
+ * Generate the example snippet for the code documentation.
+ */
+ Doc generateMethodSampleCode(PythonDocConfig config);
} | 1 | /* Copyright 2016 Google Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.codegen.py;
import com.google.api.tools.framework.snippet.Doc;
/**
* Entry points for a Python snippet set.
*/
interface PythonSnippetSet<Element> {
/**
* Generates the result filename for the generated document
*/
Doc generateFilename(Element element);
/**
* Generates a body of the module for the element where imports may be generated.
*/
Doc generateBody(Element element);
/**
* Generates the result module with a set of accumulated imports.
*/
Doc generateModule(Element element, Doc body, Iterable<String> imports);
}
| 1 | 15,181 | It seems odd to require all Python snippets to have this method when it's not relevant for messages.snip or the discovery snippets. (I see that we're already doing something similar with generateModule/generateBody where some of the implementations are empty. This also seems strange to me.) | googleapis-gapic-generator | java |
@@ -122,6 +122,7 @@ public class PrivateTransactionSimulator {
publicWorldState.updater(),
disposablePrivateState.updater(),
header,
+ Hash.ZERO, // PMT hash is not needed as this private transaction doesn't exist
transaction,
protocolSpec.getMiningBeneficiaryCalculator().calculateBeneficiary(header),
new DebugOperationTracer(TraceOptions.DEFAULT), | 1 | /*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.privacy;
import org.hyperledger.besu.crypto.SECP256K1;
import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.Account;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.Hash;
import org.hyperledger.besu.ethereum.core.MutableWorldState;
import org.hyperledger.besu.ethereum.core.PrivacyParameters;
import org.hyperledger.besu.ethereum.core.Wei;
import org.hyperledger.besu.ethereum.debug.TraceOptions;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSpec;
import org.hyperledger.besu.ethereum.transaction.CallParameter;
import org.hyperledger.besu.ethereum.vm.BlockHashLookup;
import org.hyperledger.besu.ethereum.vm.DebugOperationTracer;
import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import java.util.Optional;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
/*
* Used to process transactions for priv_call.
*
* The processing won't affect the private world state, it is used to execute read operations on the
* blockchain.
*/
public class PrivateTransactionSimulator {
// Dummy signature for transactions to not fail being processed.
private static final SECP256K1.Signature FAKE_SIGNATURE =
SECP256K1.Signature.create(SECP256K1.HALF_CURVE_ORDER, SECP256K1.HALF_CURVE_ORDER, (byte) 0);
private static final Address DEFAULT_FROM =
Address.fromHexString("0x0000000000000000000000000000000000000000");
private final Blockchain blockchain;
private final WorldStateArchive worldStateArchive;
private final ProtocolSchedule<?> protocolSchedule;
private final PrivacyParameters privacyParameters;
private final PrivateStateRootResolver privateStateRootResolver;
public PrivateTransactionSimulator(
final Blockchain blockchain,
final WorldStateArchive worldStateArchive,
final ProtocolSchedule<?> protocolSchedule,
final PrivacyParameters privacyParameters) {
this.blockchain = blockchain;
this.worldStateArchive = worldStateArchive;
this.protocolSchedule = protocolSchedule;
this.privacyParameters = privacyParameters;
this.privateStateRootResolver =
new PrivateStateRootResolver(privacyParameters.getPrivateStateStorage());
}
public Optional<PrivateTransactionProcessor.Result> process(
final String privacyGroupId, final CallParameter callParams) {
final BlockHeader header = blockchain.getChainHeadHeader();
return process(privacyGroupId, callParams, header);
}
public Optional<PrivateTransactionProcessor.Result> process(
final String privacyGroupId, final CallParameter callParams, final Hash blockHeaderHash) {
final BlockHeader header = blockchain.getBlockHeader(blockHeaderHash).orElse(null);
return process(privacyGroupId, callParams, header);
}
public Optional<PrivateTransactionProcessor.Result> process(
final String privacyGroupId, final CallParameter callParams, final long blockNumber) {
final BlockHeader header = blockchain.getBlockHeader(blockNumber).orElse(null);
return process(privacyGroupId, callParams, header);
}
private Optional<PrivateTransactionProcessor.Result> process(
final String privacyGroupIdString, final CallParameter callParams, final BlockHeader header) {
if (header == null) {
return Optional.empty();
}
final MutableWorldState publicWorldState =
worldStateArchive.getMutable(header.getStateRoot()).orElse(null);
if (publicWorldState == null) {
return Optional.empty();
}
// get the last world state root hash or create a new one
final Bytes32 privacyGroupId = Bytes32.wrap(Bytes.fromBase64String(privacyGroupIdString));
final Hash lastRootHash =
privateStateRootResolver.resolveLastStateRoot(privacyGroupId, header.getHash());
final MutableWorldState disposablePrivateState =
privacyParameters.getPrivateWorldStateArchive().getMutable(lastRootHash).get();
final PrivateTransaction transaction =
getPrivateTransaction(callParams, header, privacyGroupId, disposablePrivateState);
final ProtocolSpec<?> protocolSpec = protocolSchedule.getByBlockNumber(header.getNumber());
final PrivateTransactionProcessor privateTransactionProcessor =
protocolSpec.getPrivateTransactionProcessor();
final PrivateTransactionProcessor.Result result =
privateTransactionProcessor.processTransaction(
blockchain,
publicWorldState.updater(),
disposablePrivateState.updater(),
header,
transaction,
protocolSpec.getMiningBeneficiaryCalculator().calculateBeneficiary(header),
new DebugOperationTracer(TraceOptions.DEFAULT),
new BlockHashLookup(header, blockchain),
privacyGroupId);
return Optional.of(result);
}
private PrivateTransaction getPrivateTransaction(
final CallParameter callParams,
final BlockHeader header,
final Bytes privacyGroupId,
final MutableWorldState disposablePrivateState) {
final Address senderAddress =
callParams.getFrom() != null ? callParams.getFrom() : DEFAULT_FROM;
final Account sender = disposablePrivateState.get(senderAddress);
final long nonce = sender != null ? sender.getNonce() : 0L;
final long gasLimit =
callParams.getGasLimit() >= 0 ? callParams.getGasLimit() : header.getGasLimit();
final Wei gasPrice = callParams.getGasPrice() != null ? callParams.getGasPrice() : Wei.ZERO;
final Wei value = callParams.getValue() != null ? callParams.getValue() : Wei.ZERO;
final Bytes payload = callParams.getPayload() != null ? callParams.getPayload() : Bytes.EMPTY;
return PrivateTransaction.builder()
.privateFrom(Bytes.EMPTY)
.privacyGroupId(privacyGroupId)
.restriction(Restriction.RESTRICTED)
.nonce(nonce)
.gasPrice(gasPrice)
.gasLimit(gasLimit)
.to(callParams.getTo())
.sender(senderAddress)
.value(value)
.payload(payload)
.signature(FAKE_SIGNATURE)
.build();
}
}
| 1 | 22,048 | What about this: "// Corresponding PMT does not exist." | hyperledger-besu | java |
@@ -626,6 +626,8 @@ class OptionsManagerMixIn(object):
config_file = self.config_file
if config_file is not None:
config_file = os.path.expanduser(config_file)
+ if not os.path.exists(config_file):
+ raise IOError("The config file {:s} doesn't exist!".format(config_file))
use_config_file = config_file and os.path.exists(config_file)
if use_config_file: | 1 | # Copyright (c) 2006-2010, 2012-2014 LOGILAB S.A. (Paris, FRANCE) <[email protected]>
# Copyright (c) 2014-2016 Claudiu Popa <[email protected]>
# Copyright (c) 2015 Aru Sahni <[email protected]>
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""utilities for Pylint configuration :
* pylintrc
* pylint.d (PYLINTHOME)
"""
from __future__ import print_function
# TODO(cpopa): this module contains the logic for the
# configuration parser and for the command line parser,
# but it's really coupled to optparse's internals.
# The code was copied almost verbatim from logilab.common,
# in order to not depend on it anymore and it will definitely
# need a cleanup. It could be completely reengineered as well.
import contextlib
import collections
import copy
import io
import optparse
import os
import pickle
import re
import sys
import time
import configparser
from six.moves import range
from pylint import utils
USER_HOME = os.path.expanduser('~')
if 'PYLINTHOME' in os.environ:
PYLINT_HOME = os.environ['PYLINTHOME']
if USER_HOME == '~':
USER_HOME = os.path.dirname(PYLINT_HOME)
elif USER_HOME == '~':
PYLINT_HOME = ".pylint.d"
else:
PYLINT_HOME = os.path.join(USER_HOME, '.pylint.d')
def _get_pdata_path(base_name, recurs):
base_name = base_name.replace(os.sep, '_')
return os.path.join(PYLINT_HOME, "%s%s%s"%(base_name, recurs, '.stats'))
def load_results(base):
data_file = _get_pdata_path(base, 1)
try:
with open(data_file, _PICK_LOAD) as stream:
return pickle.load(stream)
except Exception: # pylint: disable=broad-except
return {}
if sys.version_info < (3, 0):
_PICK_DUMP, _PICK_LOAD = 'w', 'r'
else:
_PICK_DUMP, _PICK_LOAD = 'wb', 'rb'
def save_results(results, base):
if not os.path.exists(PYLINT_HOME):
try:
os.mkdir(PYLINT_HOME)
except OSError:
print('Unable to create directory %s' % PYLINT_HOME, file=sys.stderr)
data_file = _get_pdata_path(base, 1)
try:
with open(data_file, _PICK_DUMP) as stream:
pickle.dump(results, stream)
except (IOError, OSError) as ex:
print('Unable to create file %s: %s' % (data_file, ex), file=sys.stderr)
def find_pylintrc():
"""search the pylint rc file and return its path if it find it, else None
"""
# is there a pylint rc file in the current directory ?
if os.path.exists('pylintrc'):
return os.path.abspath('pylintrc')
if os.path.exists('.pylintrc'):
return os.path.abspath('.pylintrc')
if os.path.isfile('__init__.py'):
curdir = os.path.abspath(os.getcwd())
while os.path.isfile(os.path.join(curdir, '__init__.py')):
curdir = os.path.abspath(os.path.join(curdir, '..'))
if os.path.isfile(os.path.join(curdir, 'pylintrc')):
return os.path.join(curdir, 'pylintrc')
if os.path.isfile(os.path.join(curdir, '.pylintrc')):
return os.path.join(curdir, '.pylintrc')
if 'PYLINTRC' in os.environ and os.path.exists(os.environ['PYLINTRC']):
pylintrc = os.environ['PYLINTRC']
else:
user_home = os.path.expanduser('~')
if user_home == '~' or user_home == '/root':
pylintrc = ".pylintrc"
else:
pylintrc = os.path.join(user_home, '.pylintrc')
if not os.path.isfile(pylintrc):
pylintrc = os.path.join(user_home, '.config', 'pylintrc')
if not os.path.isfile(pylintrc):
if os.path.isfile('/etc/pylintrc'):
pylintrc = '/etc/pylintrc'
else:
pylintrc = None
return pylintrc
PYLINTRC = find_pylintrc()
ENV_HELP = '''
The following environment variables are used:
* PYLINTHOME
Path to the directory where the persistent for the run will be stored. If
not found, it defaults to ~/.pylint.d/ or .pylint.d (in the current working
directory).
* PYLINTRC
Path to the configuration file. See the documentation for the method used
to search for configuration file.
''' % globals()
class UnsupportedAction(Exception):
"""raised by set_option when it doesn't know what to do for an action"""
def _multiple_choice_validator(choices, name, value):
values = utils._check_csv(value)
for csv_value in values:
if csv_value not in choices:
msg = "option %s: invalid value: %r, should be in %s"
raise optparse.OptionValueError(msg % (name, csv_value, choices))
return values
def _choice_validator(choices, name, value):
if value not in choices:
msg = "option %s: invalid value: %r, should be in %s"
raise optparse.OptionValueError(msg % (name, value, choices))
return value
# pylint: disable=unused-argument
def _csv_validator(_, name, value):
return utils._check_csv(value)
# pylint: disable=unused-argument
def _regexp_validator(_, name, value):
if hasattr(value, 'pattern'):
return value
return re.compile(value)
# pylint: disable=unused-argument
def _regexp_csv_validator(_, name, value):
return [_regexp_validator(_, name, val) for val in _csv_validator(_, name, value)]
def _yn_validator(opt, _, value):
if isinstance(value, int):
return bool(value)
if value in ('y', 'yes'):
return True
if value in ('n', 'no'):
return False
msg = "option %s: invalid yn value %r, should be in (y, yes, n, no)"
raise optparse.OptionValueError(msg % (opt, value))
def _non_empty_string_validator(opt, _, value):
if not value:
msg = "indent string can't be empty."
raise optparse.OptionValueError(msg)
return utils._unquote(value)
VALIDATORS = {
'string': utils._unquote,
'int': int,
'regexp': re.compile,
'regexp_csv': _regexp_csv_validator,
'csv': _csv_validator,
'yn': _yn_validator,
'choice': lambda opt, name, value: _choice_validator(opt['choices'], name, value),
'multiple_choice': lambda opt, name, value: _multiple_choice_validator(opt['choices'],
name, value),
'non_empty_string': _non_empty_string_validator,
}
def _call_validator(opttype, optdict, option, value):
if opttype not in VALIDATORS:
raise Exception('Unsupported type "%s"' % opttype)
try:
return VALIDATORS[opttype](optdict, option, value)
except TypeError:
try:
return VALIDATORS[opttype](value)
except Exception:
raise optparse.OptionValueError('%s value (%r) should be of type %s' %
(option, value, opttype))
def _validate(value, optdict, name=''):
"""return a validated value for an option according to its type
optional argument name is only used for error message formatting
"""
try:
_type = optdict['type']
except KeyError:
# FIXME
return value
return _call_validator(_type, optdict, name, value)
def _level_options(group, outputlevel):
return [option for option in group.option_list
if (getattr(option, 'level', 0) or 0) <= outputlevel
and option.help is not optparse.SUPPRESS_HELP]
def _expand_default(self, option):
"""Patch OptionParser.expand_default with custom behaviour
This will handle defaults to avoid overriding values in the
configuration file.
"""
if self.parser is None or not self.default_tag:
return option.help
optname = option._long_opts[0][2:]
try:
provider = self.parser.options_manager._all_options[optname]
except KeyError:
value = None
else:
optdict = provider.get_option_def(optname)
optname = provider.option_attrname(optname, optdict)
value = getattr(provider.config, optname, optdict)
value = utils._format_option_value(optdict, value)
if value is optparse.NO_DEFAULT or not value:
value = self.NO_DEFAULT_VALUE
return option.help.replace(self.default_tag, str(value))
@contextlib.contextmanager
def _patch_optparse():
orig_default = optparse.HelpFormatter
try:
optparse.HelpFormatter.expand_default = _expand_default
yield
finally:
optparse.HelpFormatter.expand_default = orig_default
def _multiple_choices_validating_option(opt, name, value):
return _multiple_choice_validator(opt.choices, name, value)
class Option(optparse.Option):
TYPES = optparse.Option.TYPES + ('regexp', 'regexp_csv', 'csv', 'yn',
'multiple_choice',
'non_empty_string')
ATTRS = optparse.Option.ATTRS + ['hide', 'level']
TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER)
TYPE_CHECKER['regexp'] = _regexp_validator
TYPE_CHECKER['regexp_csv'] = _regexp_csv_validator
TYPE_CHECKER['csv'] = _csv_validator
TYPE_CHECKER['yn'] = _yn_validator
TYPE_CHECKER['multiple_choice'] = _multiple_choices_validating_option
TYPE_CHECKER['non_empty_string'] = _non_empty_string_validator
def __init__(self, *opts, **attrs):
optparse.Option.__init__(self, *opts, **attrs)
if hasattr(self, "hide") and self.hide:
self.help = optparse.SUPPRESS_HELP
def _check_choice(self):
if self.type in ("choice", "multiple_choice"):
if self.choices is None:
raise optparse.OptionError(
"must supply a list of choices for type 'choice'", self)
elif not isinstance(self.choices, (tuple, list)):
raise optparse.OptionError(
"choices must be a list of strings ('%s' supplied)"
% str(type(self.choices)).split("'")[1], self)
elif self.choices is not None:
raise optparse.OptionError(
"must not supply choices for type %r" % self.type, self)
optparse.Option.CHECK_METHODS[2] = _check_choice
def process(self, opt, value, values, parser):
# First, convert the value(s) to the right type. Howl if any
# value(s) are bogus.
value = self.convert_value(opt, value)
if self.type == 'named':
existent = getattr(values, self.dest)
if existent:
existent.update(value)
value = existent
# And then take whatever action is expected of us.
# This is a separate method to make life easier for
# subclasses to add new actions.
return self.take_action(
self.action, self.dest, opt, value, values, parser)
class OptionParser(optparse.OptionParser):
def __init__(self, option_class, *args, **kwargs):
optparse.OptionParser.__init__(self, option_class=Option, *args, **kwargs)
def format_option_help(self, formatter=None):
if formatter is None:
formatter = self.formatter
outputlevel = getattr(formatter, 'output_level', 0)
formatter.store_option_strings(self)
result = []
result.append(formatter.format_heading("Options"))
formatter.indent()
if self.option_list:
result.append(optparse.OptionContainer.format_option_help(self, formatter))
result.append("\n")
for group in self.option_groups:
if group.level <= outputlevel and (
group.description or _level_options(group, outputlevel)):
result.append(group.format_help(formatter))
result.append("\n")
formatter.dedent()
# Drop the last "\n", or the header if no options or option groups:
return "".join(result[:-1])
def _match_long_opt(self, opt):
"""Disable abbreviations."""
if opt not in self._long_opt:
raise optparse.BadOptionError(opt)
return opt
# pylint: disable=abstract-method; by design?
class _ManHelpFormatter(optparse.HelpFormatter):
def __init__(self, indent_increment=0, max_help_position=24,
width=79, short_first=0):
optparse.HelpFormatter.__init__(
self, indent_increment, max_help_position, width, short_first)
def format_heading(self, heading):
return '.SH %s\n' % heading.upper()
def format_description(self, description):
return description
def format_option(self, option):
try:
optstring = option.option_strings
except AttributeError:
optstring = self.format_option_strings(option)
if option.help:
help_text = self.expand_default(option)
help = ' '.join([l.strip() for l in help_text.splitlines()])
else:
help = ''
return '''.IP "%s"
%s
''' % (optstring, help)
def format_head(self, optparser, pkginfo, section=1):
long_desc = ""
try:
pgm = optparser._get_prog_name()
except AttributeError:
# py >= 2.4.X (dunno which X exactly, at least 2)
pgm = optparser.get_prog_name()
short_desc = self.format_short_description(pgm, pkginfo.description)
if hasattr(pkginfo, "long_desc"):
long_desc = self.format_long_description(pgm, pkginfo.long_desc)
return '%s\n%s\n%s\n%s' % (self.format_title(pgm, section),
short_desc, self.format_synopsis(pgm),
long_desc)
@staticmethod
def format_title(pgm, section):
date = '-'.join(str(num) for num in time.localtime()[:3])
return '.TH %s %s "%s" %s' % (pgm, section, date, pgm)
@staticmethod
def format_short_description(pgm, short_desc):
return '''.SH NAME
.B %s
\\- %s
''' % (pgm, short_desc.strip())
@staticmethod
def format_synopsis(pgm):
return '''.SH SYNOPSIS
.B %s
[
.I OPTIONS
] [
.I <arguments>
]
''' % pgm
@staticmethod
def format_long_description(pgm, long_desc):
long_desc = '\n'.join(line.lstrip()
for line in long_desc.splitlines())
long_desc = long_desc.replace('\n.\n', '\n\n')
if long_desc.lower().startswith(pgm):
long_desc = long_desc[len(pgm):]
return '''.SH DESCRIPTION
.B %s
%s
''' % (pgm, long_desc.strip())
@staticmethod
def format_tail(pkginfo):
tail = '''.SH SEE ALSO
/usr/share/doc/pythonX.Y-%s/
.SH BUGS
Please report bugs on the project\'s mailing list:
%s
.SH AUTHOR
%s <%s>
''' % (getattr(pkginfo, 'debian_name', pkginfo.modname),
pkginfo.mailinglist, pkginfo.author, pkginfo.author_email)
if hasattr(pkginfo, "copyright"):
tail += '''
.SH COPYRIGHT
%s
''' % pkginfo.copyright
return tail
class OptionsManagerMixIn(object):
"""Handle configuration from both a configuration file and command line options"""
def __init__(self, usage, config_file=None, version=None, quiet=0):
self.config_file = config_file
self.reset_parsers(usage, version=version)
# list of registered options providers
self.options_providers = []
# dictionary associating option name to checker
self._all_options = collections.OrderedDict()
self._short_options = {}
self._nocallback_options = {}
self._mygroups = {}
# verbosity
self.quiet = quiet
self._maxlevel = 0
def reset_parsers(self, usage='', version=None):
# configuration file parser
self.cfgfile_parser = configparser.ConfigParser(inline_comment_prefixes=('#', ';'))
# command line parser
self.cmdline_parser = OptionParser(Option, usage=usage, version=version)
self.cmdline_parser.options_manager = self
self._optik_option_attrs = set(self.cmdline_parser.option_class.ATTRS)
def register_options_provider(self, provider, own_group=True):
"""register an options provider"""
assert provider.priority <= 0, "provider's priority can't be >= 0"
for i in range(len(self.options_providers)):
if provider.priority > self.options_providers[i].priority:
self.options_providers.insert(i, provider)
break
else:
self.options_providers.append(provider)
non_group_spec_options = [option for option in provider.options
if 'group' not in option[1]]
groups = getattr(provider, 'option_groups', ())
if own_group and non_group_spec_options:
self.add_option_group(provider.name.upper(), provider.__doc__,
non_group_spec_options, provider)
else:
for opt, optdict in non_group_spec_options:
self.add_optik_option(provider, self.cmdline_parser, opt, optdict)
for gname, gdoc in groups:
gname = gname.upper()
goptions = [option for option in provider.options
if option[1].get('group', '').upper() == gname]
self.add_option_group(gname, gdoc, goptions, provider)
def add_option_group(self, group_name, _, options, provider):
# add option group to the command line parser
if group_name in self._mygroups:
group = self._mygroups[group_name]
else:
group = optparse.OptionGroup(self.cmdline_parser,
title=group_name.capitalize())
self.cmdline_parser.add_option_group(group)
group.level = provider.level
self._mygroups[group_name] = group
# add section to the config file
if group_name != "DEFAULT" and \
group_name not in self.cfgfile_parser._sections:
self.cfgfile_parser.add_section(group_name)
# add provider's specific options
for opt, optdict in options:
self.add_optik_option(provider, group, opt, optdict)
def add_optik_option(self, provider, optikcontainer, opt, optdict):
args, optdict = self.optik_option(provider, opt, optdict)
option = optikcontainer.add_option(*args, **optdict)
self._all_options[opt] = provider
self._maxlevel = max(self._maxlevel, option.level or 0)
def optik_option(self, provider, opt, optdict):
"""get our personal option definition and return a suitable form for
use with optik/optparse
"""
optdict = copy.copy(optdict)
if 'action' in optdict:
self._nocallback_options[provider] = opt
else:
optdict['action'] = 'callback'
optdict['callback'] = self.cb_set_provider_option
# default is handled here and *must not* be given to optik if you
# want the whole machinery to work
if 'default' in optdict:
if ('help' in optdict
and optdict.get('default') is not None
and optdict['action'] not in ('store_true', 'store_false')):
optdict['help'] += ' [current: %default]'
del optdict['default']
args = ['--' + str(opt)]
if 'short' in optdict:
self._short_options[optdict['short']] = opt
args.append('-' + optdict['short'])
del optdict['short']
# cleanup option definition dict before giving it to optik
for key in list(optdict.keys()):
if key not in self._optik_option_attrs:
optdict.pop(key)
return args, optdict
def cb_set_provider_option(self, option, opt, value, parser):
"""optik callback for option setting"""
if opt.startswith('--'):
# remove -- on long option
opt = opt[2:]
else:
# short option, get its long equivalent
opt = self._short_options[opt[1:]]
# trick since we can't set action='store_true' on options
if value is None:
value = 1
self.global_set_option(opt, value)
def global_set_option(self, opt, value):
"""set option on the correct option provider"""
self._all_options[opt].set_option(opt, value)
def generate_config(self, stream=None, skipsections=(), encoding=None):
"""write a configuration file according to the current configuration
into the given stream or stdout
"""
options_by_section = {}
sections = []
for provider in self.options_providers:
for section, options in provider.options_by_section():
if section is None:
section = provider.name
if section in skipsections:
continue
options = [(n, d, v) for (n, d, v) in options
if d.get('type') is not None
and not d.get('deprecated')]
if not options:
continue
if section not in sections:
sections.append(section)
alloptions = options_by_section.setdefault(section, [])
alloptions += options
stream = stream or sys.stdout
encoding = utils._get_encoding(encoding, stream)
printed = False
for section in sections:
if printed:
print('\n', file=stream)
utils.format_section(stream, section.upper(),
sorted(options_by_section[section]),
encoding)
printed = True
def generate_manpage(self, pkginfo, section=1, stream=None):
with _patch_optparse():
_generate_manpage(self.cmdline_parser, pkginfo,
section, stream=stream or sys.stdout,
level=self._maxlevel)
def load_provider_defaults(self):
"""initialize configuration using default values"""
for provider in self.options_providers:
provider.load_defaults()
def read_config_file(self, config_file=None):
"""read the configuration file but do not load it (i.e. dispatching
values to each options provider)
"""
helplevel = 1
while helplevel <= self._maxlevel:
opt = '-'.join(['long'] * helplevel) + '-help'
if opt in self._all_options:
break # already processed
# pylint: disable=unused-argument
def helpfunc(option, opt, val, p, level=helplevel):
print(self.help(level))
sys.exit(0)
helpmsg = '%s verbose help.' % ' '.join(['more'] * helplevel)
optdict = {'action': 'callback', 'callback': helpfunc,
'help': helpmsg}
provider = self.options_providers[0]
self.add_optik_option(provider, self.cmdline_parser, opt, optdict)
provider.options += ((opt, optdict),)
helplevel += 1
if config_file is None:
config_file = self.config_file
if config_file is not None:
config_file = os.path.expanduser(config_file)
use_config_file = config_file and os.path.exists(config_file)
if use_config_file:
parser = self.cfgfile_parser
# Use this encoding in order to strip the BOM marker, if any.
with io.open(config_file, 'r', encoding='utf_8_sig') as fp:
parser.read_file(fp)
# normalize sections'title
for sect, values in list(parser._sections.items()):
if not sect.isupper() and values:
parser._sections[sect.upper()] = values
if self.quiet:
return
if use_config_file:
msg = 'Using config file {0}'.format(os.path.abspath(config_file))
else:
msg = 'No config file found, using default configuration'
print(msg, file=sys.stderr)
def load_config_file(self):
"""dispatch values previously read from a configuration file to each
options provider)
"""
parser = self.cfgfile_parser
for section in parser.sections():
for option, value in parser.items(section):
try:
self.global_set_option(option, value)
except (KeyError, optparse.OptionError):
# TODO handle here undeclared options appearing in the config file
continue
def load_configuration(self, **kwargs):
"""override configuration according to given parameters"""
return self.load_configuration_from_config(kwargs)
def load_configuration_from_config(self, config):
for opt, opt_value in config.items():
opt = opt.replace('_', '-')
provider = self._all_options[opt]
provider.set_option(opt, opt_value)
def load_command_line_configuration(self, args=None):
"""Override configuration according to command line parameters
return additional arguments
"""
with _patch_optparse():
if args is None:
args = sys.argv[1:]
else:
args = list(args)
(options, args) = self.cmdline_parser.parse_args(args=args)
for provider in self._nocallback_options:
config = provider.config
for attr in config.__dict__.keys():
value = getattr(options, attr, None)
if value is None:
continue
setattr(config, attr, value)
return args
def add_help_section(self, title, description, level=0):
"""add a dummy option section for help purpose """
group = optparse.OptionGroup(self.cmdline_parser,
title=title.capitalize(),
description=description)
group.level = level
self._maxlevel = max(self._maxlevel, level)
self.cmdline_parser.add_option_group(group)
def help(self, level=0):
"""return the usage string for available options """
self.cmdline_parser.formatter.output_level = level
with _patch_optparse():
return self.cmdline_parser.format_help()
class OptionsProviderMixIn(object):
"""Mixin to provide options to an OptionsManager"""
# those attributes should be overridden
priority = -1
name = 'default'
options = ()
level = 0
def __init__(self):
self.config = optparse.Values()
self.load_defaults()
def load_defaults(self):
"""initialize the provider using default values"""
for opt, optdict in self.options:
action = optdict.get('action')
if action != 'callback':
# callback action have no default
if optdict is None:
optdict = self.get_option_def(opt)
default = optdict.get('default')
self.set_option(opt, default, action, optdict)
def option_attrname(self, opt, optdict=None):
"""get the config attribute corresponding to opt"""
if optdict is None:
optdict = self.get_option_def(opt)
return optdict.get('dest', opt.replace('-', '_'))
def option_value(self, opt):
"""get the current value for the given option"""
return getattr(self.config, self.option_attrname(opt), None)
def set_option(self, optname, value, action=None, optdict=None):
"""method called to set an option (registered in the options list)"""
if optdict is None:
optdict = self.get_option_def(optname)
if value is not None:
value = _validate(value, optdict, optname)
if action is None:
action = optdict.get('action', 'store')
if action == 'store':
setattr(self.config, self.option_attrname(optname, optdict), value)
elif action in ('store_true', 'count'):
setattr(self.config, self.option_attrname(optname, optdict), 0)
elif action == 'store_false':
setattr(self.config, self.option_attrname(optname, optdict), 1)
elif action == 'append':
optname = self.option_attrname(optname, optdict)
_list = getattr(self.config, optname, None)
if _list is None:
if isinstance(value, (list, tuple)):
_list = value
elif value is not None:
_list = []
_list.append(value)
setattr(self.config, optname, _list)
elif isinstance(_list, tuple):
setattr(self.config, optname, _list + (value,))
else:
_list.append(value)
elif action == 'callback':
optdict['callback'](None, optname, value, None)
else:
raise UnsupportedAction(action)
def get_option_def(self, opt):
"""return the dictionary defining an option given its name"""
assert self.options
for option in self.options:
if option[0] == opt:
return option[1]
raise optparse.OptionError('no such option %s in section %r'
% (opt, self.name), opt)
def options_by_section(self):
"""return an iterator on options grouped by section
(section, [list of (optname, optdict, optvalue)])
"""
sections = {}
for optname, optdict in self.options:
sections.setdefault(optdict.get('group'), []).append(
(optname, optdict, self.option_value(optname)))
if None in sections:
yield None, sections.pop(None)
for section, options in sorted(sections.items()):
yield section.upper(), options
def options_and_values(self, options=None):
if options is None:
options = self.options
for optname, optdict in options:
yield (optname, optdict, self.option_value(optname))
class ConfigurationMixIn(OptionsManagerMixIn, OptionsProviderMixIn):
"""basic mixin for simple configurations which don't need the
manager / providers model
"""
def __init__(self, *args, **kwargs):
if not args:
kwargs.setdefault('usage', '')
kwargs.setdefault('quiet', 1)
OptionsManagerMixIn.__init__(self, *args, **kwargs)
OptionsProviderMixIn.__init__(self)
if not getattr(self, 'option_groups', None):
self.option_groups = []
for _, optdict in self.options:
try:
gdef = (optdict['group'].upper(), '')
except KeyError:
continue
if gdef not in self.option_groups:
self.option_groups.append(gdef)
self.register_options_provider(self, own_group=False)
def _generate_manpage(optparser, pkginfo, section=1,
stream=sys.stdout, level=0):
formatter = _ManHelpFormatter()
formatter.output_level = level
formatter.parser = optparser
print(formatter.format_head(optparser, pkginfo, section), file=stream)
print(optparser.format_option_help(formatter), file=stream)
print(formatter.format_tail(pkginfo), file=stream)
| 1 | 9,756 | You don't need af ormat specified here. | PyCQA-pylint | py |
@@ -12,6 +12,8 @@ import (
"time"
"github.com/nats-io/go-nats"
+ "strings"
+ "sync"
)
func TestRouteConfig(t *testing.T) { | 1 | // Copyright 2013-2016 Apcera Inc. All rights reserved.
package server
import (
"fmt"
"net"
"net/url"
"reflect"
"strconv"
"testing"
"time"
"github.com/nats-io/go-nats"
)
func TestRouteConfig(t *testing.T) {
opts, err := ProcessConfigFile("./configs/cluster.conf")
if err != nil {
t.Fatalf("Received an error reading route config file: %v\n", err)
}
golden := &Options{
ConfigFile: "./configs/cluster.conf",
Host: "localhost",
Port: 4242,
Username: "derek",
Password: "bella",
AuthTimeout: 1.0,
Cluster: ClusterOpts{
Host: "127.0.0.1",
Port: 4244,
Username: "route_user",
Password: "top_secret",
AuthTimeout: 1.0,
NoAdvertise: true,
ConnectRetries: 2,
},
PidFile: "/tmp/nats_cluster_test.pid",
}
// Setup URLs
r1, _ := url.Parse("nats-route://foo:bar@localhost:4245")
r2, _ := url.Parse("nats-route://foo:bar@localhost:4246")
golden.Routes = []*url.URL{r1, r2}
if !reflect.DeepEqual(golden, opts) {
t.Fatalf("Options are incorrect.\nexpected: %+v\ngot: %+v",
golden, opts)
}
}
func TestServerRoutesWithClients(t *testing.T) {
optsA, _ := ProcessConfigFile("./configs/srv_a.conf")
optsB, _ := ProcessConfigFile("./configs/srv_b.conf")
optsA.NoSigs, optsA.NoLog = true, true
optsB.NoSigs, optsB.NoLog = true, true
srvA := RunServer(optsA)
defer srvA.Shutdown()
urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, optsA.Port)
urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, optsB.Port)
nc1, err := nats.Connect(urlA)
if err != nil {
t.Fatalf("Error creating client: %v\n", err)
}
defer nc1.Close()
ch := make(chan bool)
sub, _ := nc1.Subscribe("foo", func(m *nats.Msg) { ch <- true })
nc1.QueueSubscribe("foo", "bar", func(m *nats.Msg) {})
nc1.Publish("foo", []byte("Hello"))
// Wait for message
<-ch
sub.Unsubscribe()
srvB := RunServer(optsB)
defer srvB.Shutdown()
// Wait for route to form.
checkClusterFormed(t, srvA, srvB)
nc2, err := nats.Connect(urlB)
if err != nil {
t.Fatalf("Error creating client: %v\n", err)
}
defer nc2.Close()
nc2.Publish("foo", []byte("Hello"))
nc2.Flush()
}
func TestServerRoutesWithAuthAndBCrypt(t *testing.T) {
optsA, _ := ProcessConfigFile("./configs/srv_a_bcrypt.conf")
optsB, _ := ProcessConfigFile("./configs/srv_b_bcrypt.conf")
optsA.NoSigs, optsA.NoLog = true, true
optsB.NoSigs, optsB.NoLog = true, true
srvA := RunServer(optsA)
defer srvA.Shutdown()
srvB := RunServer(optsB)
defer srvB.Shutdown()
// Wait for route to form.
checkClusterFormed(t, srvA, srvB)
urlA := fmt.Sprintf("nats://%s:%s@%s:%d/", optsA.Username, optsA.Password, optsA.Host, optsA.Port)
urlB := fmt.Sprintf("nats://%s:%s@%s:%d/", optsB.Username, optsB.Password, optsB.Host, optsB.Port)
nc1, err := nats.Connect(urlA)
if err != nil {
t.Fatalf("Error creating client: %v\n", err)
}
defer nc1.Close()
// Test that we are connected.
ch := make(chan bool)
sub, err := nc1.Subscribe("foo", func(m *nats.Msg) { ch <- true })
if err != nil {
t.Fatalf("Error creating subscription: %v\n", err)
}
nc1.Flush()
defer sub.Unsubscribe()
nc2, err := nats.Connect(urlB)
if err != nil {
t.Fatalf("Error creating client: %v\n", err)
}
defer nc2.Close()
nc2.Publish("foo", []byte("Hello"))
nc2.Flush()
// Wait for message
select {
case <-ch:
case <-time.After(2 * time.Second):
t.Fatal("Timeout waiting for message across route")
}
}
// Helper function to check that a cluster is formed
func checkClusterFormed(t *testing.T, servers ...*Server) {
// Wait for the cluster to form
var err string
expectedNumRoutes := len(servers) - 1
maxTime := time.Now().Add(10 * time.Second)
for time.Now().Before(maxTime) {
err = ""
for _, s := range servers {
if numRoutes := s.NumRoutes(); numRoutes != expectedNumRoutes {
err = fmt.Sprintf("Expected %d routes for server %q, got %d", expectedNumRoutes, s.ID(), numRoutes)
break
}
}
if err != "" {
time.Sleep(100 * time.Millisecond)
} else {
break
}
}
if err != "" {
stackFatalf(t, "%s", err)
}
}
// Helper function to generate next opts to make sure no port conflicts etc.
func nextServerOpts(opts *Options) *Options {
nopts := *opts
nopts.Port = -1
nopts.Cluster.Port = -1
nopts.HTTPPort = -1
return &nopts
}
func TestSeedSolicitWorks(t *testing.T) {
optsSeed, _ := ProcessConfigFile("./configs/seed.conf")
optsSeed.NoSigs, optsSeed.NoLog = true, true
srvSeed := RunServer(optsSeed)
defer srvSeed.Shutdown()
optsA := nextServerOpts(optsSeed)
optsA.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsSeed.Cluster.Host,
srvSeed.ClusterAddr().Port))
srvA := RunServer(optsA)
defer srvA.Shutdown()
urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, srvA.ClusterAddr().Port)
nc1, err := nats.Connect(urlA)
if err != nil {
t.Fatalf("Error creating client: %v\n", err)
}
defer nc1.Close()
// Test that we are connected.
ch := make(chan bool)
nc1.Subscribe("foo", func(m *nats.Msg) { ch <- true })
nc1.Flush()
optsB := nextServerOpts(optsA)
optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsSeed.Cluster.Host,
srvSeed.ClusterAddr().Port))
srvB := RunServer(optsB)
defer srvB.Shutdown()
urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, srvB.ClusterAddr().Port)
nc2, err := nats.Connect(urlB)
if err != nil {
t.Fatalf("Error creating client: %v\n", err)
}
defer nc2.Close()
checkClusterFormed(t, srvSeed, srvA, srvB)
nc2.Publish("foo", []byte("Hello"))
// Wait for message
select {
case <-ch:
case <-time.After(2 * time.Second):
t.Fatal("Timeout waiting for message across route")
}
}
func TestTLSSeedSolicitWorks(t *testing.T) {
optsSeed, _ := ProcessConfigFile("./configs/seed_tls.conf")
optsSeed.NoSigs, optsSeed.NoLog = true, true
srvSeed := RunServer(optsSeed)
defer srvSeed.Shutdown()
seedRouteUrl := fmt.Sprintf("nats://%s:%d", optsSeed.Cluster.Host,
srvSeed.ClusterAddr().Port)
optsA := nextServerOpts(optsSeed)
optsA.Routes = RoutesFromStr(seedRouteUrl)
srvA := RunServer(optsA)
defer srvA.Shutdown()
urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, srvA.Addr().(*net.TCPAddr).Port)
nc1, err := nats.Connect(urlA)
if err != nil {
t.Fatalf("Error creating client: %v\n", err)
}
defer nc1.Close()
// Test that we are connected.
ch := make(chan bool)
nc1.Subscribe("foo", func(m *nats.Msg) { ch <- true })
nc1.Flush()
optsB := nextServerOpts(optsA)
optsB.Routes = RoutesFromStr(seedRouteUrl)
srvB := RunServer(optsB)
defer srvB.Shutdown()
urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, srvB.Addr().(*net.TCPAddr).Port)
nc2, err := nats.Connect(urlB)
if err != nil {
t.Fatalf("Error creating client: %v\n", err)
}
defer nc2.Close()
checkClusterFormed(t, srvSeed, srvA, srvB)
nc2.Publish("foo", []byte("Hello"))
// Wait for message
select {
case <-ch:
case <-time.After(2 * time.Second):
t.Fatal("Timeout waiting for message across route")
}
}
func TestChainedSolicitWorks(t *testing.T) {
optsSeed, _ := ProcessConfigFile("./configs/seed.conf")
optsSeed.NoSigs, optsSeed.NoLog = true, true
srvSeed := RunServer(optsSeed)
defer srvSeed.Shutdown()
seedRouteUrl := fmt.Sprintf("nats://%s:%d", optsSeed.Cluster.Host,
srvSeed.ClusterAddr().Port)
optsA := nextServerOpts(optsSeed)
optsA.Routes = RoutesFromStr(seedRouteUrl)
srvA := RunServer(optsA)
defer srvA.Shutdown()
urlSeed := fmt.Sprintf("nats://%s:%d/", optsSeed.Host, srvA.Addr().(*net.TCPAddr).Port)
nc1, err := nats.Connect(urlSeed)
if err != nil {
t.Fatalf("Error creating client: %v\n", err)
}
defer nc1.Close()
// Test that we are connected.
ch := make(chan bool)
nc1.Subscribe("foo", func(m *nats.Msg) { ch <- true })
nc1.Flush()
optsB := nextServerOpts(optsA)
// Server B connects to A
optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host,
srvA.ClusterAddr().Port))
srvB := RunServer(optsB)
defer srvB.Shutdown()
urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, srvB.Addr().(*net.TCPAddr).Port)
nc2, err := nats.Connect(urlB)
if err != nil {
t.Fatalf("Error creating client: %v\n", err)
}
defer nc2.Close()
checkClusterFormed(t, srvSeed, srvA, srvB)
nc2.Publish("foo", []byte("Hello"))
// Wait for message
select {
case <-ch:
case <-time.After(2 * time.Second):
t.Fatal("Timeout waiting for message across route")
}
}
func TestTLSChainedSolicitWorks(t *testing.T) {
optsSeed, _ := ProcessConfigFile("./configs/seed_tls.conf")
optsSeed.NoSigs, optsSeed.NoLog = true, true
srvSeed := RunServer(optsSeed)
defer srvSeed.Shutdown()
urlSeedRoute := fmt.Sprintf("nats://%s:%d", optsSeed.Cluster.Host,
srvSeed.ClusterAddr().Port)
optsA := nextServerOpts(optsSeed)
optsA.Routes = RoutesFromStr(urlSeedRoute)
srvA := RunServer(optsA)
defer srvA.Shutdown()
urlSeed := fmt.Sprintf("nats://%s:%d/", optsSeed.Host, srvSeed.Addr().(*net.TCPAddr).Port)
nc1, err := nats.Connect(urlSeed)
if err != nil {
t.Fatalf("Error creating client: %v\n", err)
}
defer nc1.Close()
// Test that we are connected.
ch := make(chan bool)
nc1.Subscribe("foo", func(m *nats.Msg) { ch <- true })
nc1.Flush()
optsB := nextServerOpts(optsA)
// Server B connects to A
optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host,
srvA.ClusterAddr().Port))
srvB := RunServer(optsB)
defer srvB.Shutdown()
urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, srvB.Addr().(*net.TCPAddr).Port)
nc2, err := nats.Connect(urlB)
if err != nil {
t.Fatalf("Error creating client: %v\n", err)
}
defer nc2.Close()
checkClusterFormed(t, srvSeed, srvA, srvB)
nc2.Publish("foo", []byte("Hello"))
// Wait for message
select {
case <-ch:
case <-time.After(2 * time.Second):
t.Fatal("Timeout waiting for message across route")
}
}
func TestRouteTLSHandshakeError(t *testing.T) {
optsSeed, _ := ProcessConfigFile("./configs/seed_tls.conf")
optsSeed.NoLog = true
srvSeed := RunServer(optsSeed)
defer srvSeed.Shutdown()
opts := DefaultOptions()
opts.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsSeed.Cluster.Host, optsSeed.Cluster.Port))
srv := RunServer(opts)
defer srv.Shutdown()
time.Sleep(500 * time.Millisecond)
maxTime := time.Now().Add(1 * time.Second)
for time.Now().Before(maxTime) {
if srv.NumRoutes() > 0 {
time.Sleep(100 * time.Millisecond)
continue
}
break
}
if srv.NumRoutes() > 0 {
t.Fatal("Route should have failed")
}
}
func TestBlockedShutdownOnRouteAcceptLoopFailure(t *testing.T) {
opts := DefaultOptions()
opts.Cluster.Host = "x.x.x.x"
opts.Cluster.Port = 7222
s := New(opts)
go s.Start()
// Wait a second
time.Sleep(time.Second)
ch := make(chan bool)
go func() {
s.Shutdown()
ch <- true
}()
timeout := time.NewTimer(5 * time.Second)
select {
case <-ch:
return
case <-timeout.C:
t.Fatal("Shutdown did not complete")
}
}
func TestRouteUseIPv6(t *testing.T) {
opts := DefaultOptions()
opts.Cluster.Host = "::"
opts.Cluster.Port = 6222
// I believe that there is no IPv6 support on Travis...
// Regardless, cannot have this test fail simply because IPv6 is disabled
// on the host.
hp := net.JoinHostPort(opts.Cluster.Host, strconv.Itoa(opts.Cluster.Port))
_, err := net.ResolveTCPAddr("tcp", hp)
if err != nil {
t.Skipf("Skipping this test since there is no IPv6 support on this host: %v", err)
}
s := RunServer(opts)
defer s.Shutdown()
routeUp := false
timeout := time.Now().Add(5 * time.Second)
for time.Now().Before(timeout) && !routeUp {
// We know that the server is local and listening to
// all IPv6 interfaces. Try connect using IPv6 loopback.
if conn, err := net.Dial("tcp", "[::1]:6222"); err != nil {
// Travis seem to have the server actually listening to 0.0.0.0,
// so try with 127.0.0.1
if conn, err := net.Dial("tcp", "127.0.0.1:6222"); err != nil {
time.Sleep(time.Second)
continue
} else {
conn.Close()
}
} else {
conn.Close()
}
routeUp = true
}
if !routeUp {
t.Fatal("Server failed to start route accept loop")
}
}
func TestClientConnectToRoutePort(t *testing.T) {
opts := DefaultOptions()
// Since client will first connect to the route listen port, set the
// cluster's Host to localhost so it works on Windows too, since on
// Windows, a client can't use 0.0.0.0 in a connect.
opts.Cluster.Host = "localhost"
opts.Cluster.NoAdvertise = true
s := RunServer(opts)
defer s.Shutdown()
url := fmt.Sprintf("nats://%s:%d", opts.Cluster.Host, s.ClusterAddr().Port)
clientURL := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
// When connecting to the ROUTE port, the client library will receive the
// CLIENT port in the INFO protocol. This URL is added to the client's pool
// and will be tried after the initial connect failure. So all those
// nats.Connect() should succeed.
// The only reason for a failure would be if there are too many FDs in time-wait
// which would delay the creation of TCP connection. So keep the total of
// attempts rather small.
total := 10
for i := 0; i < total; i++ {
nc, err := nats.Connect(url)
if err != nil {
t.Fatalf("Unexepected error on connect: %v", err)
}
defer nc.Close()
if nc.ConnectedUrl() != clientURL {
t.Fatalf("Expected client to be connected to %v, got %v", clientURL, nc.ConnectedUrl())
}
}
}
| 1 | 7,203 | Nitpick: import ordering | nats-io-nats-server | go |
@@ -38,7 +38,7 @@ namespace Nethermind.Blockchain
public ReadOnlyChain(ReadOnlyBlockTree readOnlyTree,
IBlockValidator blockValidator,
- IRewardCalculator rewardCalculator,
+ Func<ITransactionProcessor, IRewardCalculator> rewardCalculatorFactory,
ISpecProvider specProvider,
IReadOnlyDbProvider dbProvider,
IBlockDataRecoveryStep recoveryStep, | 1 | // Copyright (c) 2018 Demerzel Solutions Limited
// This file is part of the Nethermind library.
//
// The Nethermind library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Nethermind library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using Nethermind.Blockchain.Receipts;
using Nethermind.Blockchain.Rewards;
using Nethermind.Blockchain.TxPools;
using Nethermind.Blockchain.Validators;
using Nethermind.Core.Attributes;
using Nethermind.Core.Specs;
using Nethermind.Evm;
using Nethermind.Logging;
using Nethermind.Store;
namespace Nethermind.Blockchain
{
[Todo("Review how it compares with ReadOnlyChainProcessingEnv")]
public class ReadOnlyChain
{
public IBlockchainProcessor Processor { get; }
public IStateProvider ReadOnlyStateProvider { get; }
public IEnumerable<IAdditionalBlockProcessor> AdditionalBlockProcessors { get; }
public IBlockProcessor BlockProcessor { get; }
public ReadOnlyChain(ReadOnlyBlockTree readOnlyTree,
IBlockValidator blockValidator,
IRewardCalculator rewardCalculator,
ISpecProvider specProvider,
IReadOnlyDbProvider dbProvider,
IBlockDataRecoveryStep recoveryStep,
ILogManager logManager,
ITxPool customTxPool,
IReceiptStorage receiptStorage,
Func<IDb, IStateProvider, IBlockTree, ITransactionProcessor, ILogManager, IEnumerable<IAdditionalBlockProcessor>> additionalBlockProcessorsFactory)
{
ReadOnlyStateProvider = new StateProvider(dbProvider.StateDb, dbProvider.CodeDb, logManager);
StorageProvider storageProvider = new StorageProvider(dbProvider.StateDb, ReadOnlyStateProvider, logManager);
BlockhashProvider blockhashProvider = new BlockhashProvider(readOnlyTree, logManager);
VirtualMachine virtualMachine = new VirtualMachine(ReadOnlyStateProvider, storageProvider, blockhashProvider, specProvider, logManager);
ITransactionProcessor transactionProcessor = new TransactionProcessor(specProvider, ReadOnlyStateProvider, storageProvider, virtualMachine, logManager);
ITxPool txPool = customTxPool;
AdditionalBlockProcessors = additionalBlockProcessorsFactory?.Invoke(dbProvider.StateDb, ReadOnlyStateProvider, readOnlyTree, transactionProcessor, logManager);
BlockProcessor = new BlockProcessor(specProvider, blockValidator, rewardCalculator, transactionProcessor, dbProvider.StateDb, dbProvider.CodeDb, ReadOnlyStateProvider, storageProvider, txPool, receiptStorage, logManager, AdditionalBlockProcessors);
Processor = new OneTimeChainProcessor(dbProvider, new BlockchainProcessor(readOnlyTree, BlockProcessor, recoveryStep, logManager, false));
}
}
} | 1 | 23,148 | code smell here, a function that create a reward calculator from transaction processor? | NethermindEth-nethermind | .cs |
@@ -48,7 +48,7 @@ var authScopes = []string{
"https://www.googleapis.com/auth/cloud-platform",
}
-// Client is a runtimevarManager client.
+// A Client constructs runtime variables using the Runtime Configurator API.
type Client struct {
conn *grpc.ClientConn
// The gRPC API client. | 1 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package runtimeconfigurator provides a runtimevar driver implementation to read configurations from
// Cloud Runtime Configurator service and ability to detect changes and get updates.
//
// User constructs a Client that provides the gRPC connection, then use the client to construct any
// number of runtimevar.Variable objects using NewConfig method.
package runtimeconfigurator
import (
"context"
"fmt"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/google/go-cloud/runtimevar"
"github.com/google/go-cloud/runtimevar/driver"
"google.golang.org/api/option"
transport "google.golang.org/api/transport/grpc"
pb "google.golang.org/genproto/googleapis/cloud/runtimeconfig/v1beta1"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
// endpoint is the address of the GCP Runtime Configurator API.
endPoint = "runtimeconfig.googleapis.com:443"
// defaultWaitTimeout is the default value for WatchOptions.WaitTime if not set.
// Change the docstring for NewVariable if this time is modified.
defaultWaitTimeout = 10 * time.Minute
)
// List of authentication scopes required for using the Runtime Configurator API.
var authScopes = []string{
"https://www.googleapis.com/auth/cloud-platform",
}
// Client is a runtimevarManager client.
type Client struct {
conn *grpc.ClientConn
// The gRPC API client.
client pb.RuntimeConfigManagerClient
}
// NewClient constructs a Client instance from given gRPC connection.
func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
opts = append(opts, option.WithEndpoint(endPoint), option.WithScopes(authScopes...))
conn, err := transport.Dial(ctx, opts...)
if err != nil {
return nil, err
}
return &Client{
conn: conn,
client: pb.NewRuntimeConfigManagerClient(conn),
}, nil
}
// Close tears down the gRPC connection used by this Client.
func (c *Client) Close() error {
return c.conn.Close()
}
// NewVariable constructs a runtimevar.Variable object with this package as the driver
// implementation. Provide a decoder to unmarshal updated configurations into similar
// objects during the Watch call.
// If WaitTime is not set the poller will time out after 10 minutes.
func (c *Client) NewVariable(ctx context.Context, name ResourceName, decoder *runtimevar.Decoder, opts *WatchOptions) (*runtimevar.Variable, error) {
if opts == nil {
opts = &WatchOptions{}
}
waitTime := opts.WaitTime
switch {
case waitTime == 0:
waitTime = defaultWaitTimeout
case waitTime < 0:
return nil, fmt.Errorf("cannot have negative WaitTime option value: %v", waitTime)
}
return runtimevar.New(&watcher{
client: c.client,
waitTime: waitTime,
lastRPCTime: time.Now().Add(-1 * waitTime), // Remove wait on first Watch call.
name: name.String(),
decoder: decoder,
}), nil
}
// ResourceName identifies the full configuration variable path used by the service.
type ResourceName struct {
ProjectID string
Config string
Variable string
}
// String returns the full configuration variable path.
func (r ResourceName) String() string {
return fmt.Sprintf("projects/%s/configs/%s/variables/%s", r.ProjectID, r.Config, r.Variable)
}
// WatchOptions provide optional configurations to the Watcher.
type WatchOptions struct {
// WaitTime controls the frequency of making RPC and checking for updates by the Watch method.
// A Watcher keeps track of the last time it made an RPC, when Watch is called, it waits for
// configured WaitTime from the last RPC before making another RPC. The smaller the value, the
// higher the frequency of making RPCs, which also means faster rate of hitting the API quota.
//
// If this option is not set or set to 0, it uses defaultWaitTimeout value.
WaitTime time.Duration
}
// watcher implements driver.Watcher for configurations provided by the Runtime Configurator
// service.
type watcher struct {
client pb.RuntimeConfigManagerClient
waitTime time.Duration
lastRPCTime time.Time
name string
decoder *runtimevar.Decoder
bytes []byte
isDeleted bool
updateTime time.Time
}
// Close implements driver.Watcher.Close. This is a no-op for this driver.
func (w *watcher) Close() error {
return nil
}
// Watch blocks until the file changes, the Context's Done channel closes or an error occurs. It
// implements the driver.Watcher.Watch method.
func (w *watcher) Watch(ctx context.Context) (driver.Variable, error) {
zeroVar := driver.Variable{}
// Loop to check for changes or continue waiting.
for {
// Block until waitTime or context cancelled/timed out.
t := time.NewTimer(w.waitTime - time.Now().Sub(w.lastRPCTime))
select {
case <-t.C:
case <-ctx.Done():
t.Stop()
return zeroVar, ctx.Err()
}
// Use GetVariables RPC and check for deltas based on the response.
vpb, err := w.client.GetVariable(ctx, &pb.GetVariableRequest{Name: w.name})
w.lastRPCTime = time.Now()
if err == nil {
updateTime, err := parseUpdateTime(vpb)
if err != nil {
return zeroVar, err
}
// Determine if there are any changes based on the bytes. If there are, update cache and
// return nil, else continue on.
bytes := bytesFromProto(vpb)
if w.isDeleted || bytesNotEqual(w.bytes, bytes) {
w.bytes = bytes
w.updateTime = updateTime
w.isDeleted = false
val, err := w.decoder.Decode(bytes)
if err != nil {
return zeroVar, err
}
return driver.Variable{
Value: val,
UpdateTime: updateTime,
}, nil
}
} else {
if st, ok := status.FromError(err); !ok || st.Code() != codes.NotFound {
return zeroVar, err
}
// For RPC not found error, if last known state is not deleted, mark isDeleted and
// return error, else treat as no change has occurred.
if !w.isDeleted {
w.isDeleted = true
w.updateTime = time.Now().UTC()
return zeroVar, err
}
}
}
}
func bytesFromProto(vpb *pb.Variable) []byte {
// Proto may contain either bytes or text. If it contains text content, convert that to []byte.
if _, isBytes := vpb.GetContents().(*pb.Variable_Value); isBytes {
return vpb.GetValue()
}
return []byte(vpb.GetText())
}
func bytesNotEqual(a []byte, b []byte) bool {
n := len(a)
if n != len(b) {
return true
}
for i := 0; i < n; i++ {
if a[i] != b[i] {
return true
}
}
return false
}
func parseUpdateTime(vpb *pb.Variable) (time.Time, error) {
updateTime, err := ptypes.Timestamp(vpb.GetUpdateTime())
if err != nil {
return time.Time{}, fmt.Errorf(
"variable message for name=%q contains invalid timestamp: %v", vpb.Name, err)
}
return updateTime, nil
}
| 1 | 9,775 | I don't think the `A` is idomatic is it? | google-go-cloud | go |
@@ -67,4 +67,12 @@ public interface ActionsProvider {
default ExpireSnapshots expireSnapshots(Table table) {
throw new UnsupportedOperationException(this.getClass().getName() + " does not implement expireSnapshots");
}
+
+ /**
+ * Instantiates an action to remove all the files reachable from given metadata location.
+ */
+ default RemoveReachableFiles removeReachableFiles(String metadataLocation) {
+ throw new UnsupportedOperationException(this.getClass().getName() + " does not implement " +
+ RemoveReachableFiles.class.toString());
+ }
} | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iceberg.actions;
import org.apache.iceberg.Table;
/**
* An API that should be implemented by query engine integrations for providing actions.
*/
public interface ActionsProvider {
/**
* Instantiates an action to snapshot an existing table as a new Iceberg table.
*/
default SnapshotTable snapshotTable(String sourceTableIdent) {
throw new UnsupportedOperationException(this.getClass().getName() + " does not implement snapshotTable");
}
/**
* Instantiates an action to migrate an existing table to Iceberg.
*/
default MigrateTable migrateTable(String tableIdent) {
throw new UnsupportedOperationException(this.getClass().getName() + " does not implement migrateTable");
}
/**
* Instantiates an action to remove orphan files.
*/
default RemoveOrphanFiles removeOrphanFiles(Table table) {
throw new UnsupportedOperationException(this.getClass().getName() + " does not implement removeOrphanFiles");
}
/**
* Instantiates an action to rewrite manifests.
*/
default RewriteManifests rewriteManifests(Table table) {
throw new UnsupportedOperationException(this.getClass().getName() + " does not implement rewriteManifests");
}
/**
* Instantiates an action to rewrite data files.
*/
default RewriteDataFiles rewriteDataFiles(Table table) {
throw new UnsupportedOperationException(this.getClass().getName() + " does not implement rewriteDataFiles");
}
/**
* Instantiates an action to expire snapshots.
*/
default ExpireSnapshots expireSnapshots(Table table) {
throw new UnsupportedOperationException(this.getClass().getName() + " does not implement expireSnapshots");
}
}
| 1 | 35,840 | nit: the others use the method name in the api and not the class name of the api | apache-iceberg | java |
@@ -1939,6 +1939,9 @@ unsigned SwiftExpressionParser::Parse(DiagnosticManager &diagnostic_manager,
// - Some passes may create new functions, but only the functions defined in
// the lldb repl line should be serialized.
if (swift_ast_ctx->UseSerialization()) {
+ // Run all the passes before differentiation before we serialize.
+ runSILMandatoryOptPreDiffPasses(*sil_module);
+ // Serialize the module now.
auto expr_module_dir = swift_ast_ctx->GetReplExprModulesDir();
assert(expr_module_dir != nullptr);
llvm::SmallString<256> filename(expr_module_dir); | 1 | //===-- SwiftExpressionParser.cpp -------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "SwiftExpressionParser.h"
#include "SwiftASTManipulator.h"
#include "SwiftREPLMaterializer.h"
#include "SwiftSILManipulator.h"
#include "SwiftUserExpression.h"
#include "Plugins/ExpressionParser/Swift/SwiftDiagnostic.h"
#include "Plugins/ExpressionParser/Swift/SwiftExpressionVariable.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/Expression/DiagnosticManager.h"
#include "lldb/Expression/Expression.h"
#include "lldb/Expression/ExpressionSourceCode.h"
#include "lldb/Expression/IRExecutionUnit.h"
#include "lldb/Symbol/CompileUnit.h"
#include "lldb/Symbol/SymbolFile.h"
#include "lldb/Symbol/SymbolVendor.h"
#include "lldb/Symbol/Type.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/SwiftLanguageRuntime.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Stream.h"
#include "llvm-c/Analysis.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/Basic/Module.h"
#include "clang/Rewrite/Core/RewriteBuffer.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticConsumer.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Module.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Basic/PrimarySpecificPaths.h"
#include "swift/Basic/SourceManager.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Parse/LocalContext.h"
#include "swift/Parse/PersistentParserState.h"
#include "swift/SIL/SILDebuggerClient.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/Serialization/SerializationOptions.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Subsystems.h"
using namespace lldb_private;
using llvm::make_error;
using llvm::StringError;
using llvm::inconvertibleErrorCode;
SwiftExpressionParser::SwiftExpressionParser(
ExecutionContextScope *exe_scope, Expression &expr,
const EvaluateExpressionOptions &options)
: ExpressionParser(exe_scope, expr, options.GetGenerateDebugInfo()),
m_expr(expr), m_triple(), m_llvm_context(), m_module(),
m_execution_unit_sp(), m_sc(), m_exe_scope(exe_scope), m_stack_frame_wp(),
m_options(options) {
assert(expr.Language() == lldb::eLanguageTypeSwift);
// TODO This code is copied from ClangExpressionParser.cpp.
// Factor this out into common code.
lldb::TargetSP target_sp;
if (exe_scope) {
target_sp = exe_scope->CalculateTarget();
lldb::StackFrameSP stack_frame = exe_scope->CalculateStackFrame();
if (stack_frame) {
m_stack_frame_wp = stack_frame;
m_sc = stack_frame->GetSymbolContext(lldb::eSymbolContextEverything);
} else {
m_sc.target_sp = target_sp;
}
}
if (target_sp && target_sp->GetArchitecture().IsValid()) {
std::string triple = target_sp->GetArchitecture().GetTriple().str();
int dash_count = 0;
for (size_t i = 0; i < triple.size(); ++i) {
if (triple[i] == '-')
dash_count++;
if (dash_count == 3) {
triple.resize(i);
break;
}
}
m_triple = triple;
} else {
m_triple = llvm::sys::getDefaultTargetTriple();
}
if (target_sp) {
Status error;
m_swift_ast_context = llvm::make_unique<SwiftASTContextReader>(
target_sp->GetScratchSwiftASTContext(error, *exe_scope, true));
}
}
static void DescribeFileUnit(Stream &s, swift::FileUnit *file_unit) {
s.PutCString("kind = ");
switch (file_unit->getKind()) {
default: { s.PutCString("<unknown>"); }
case swift::FileUnitKind::Source: {
s.PutCString("Source, ");
if (swift::SourceFile *source_file =
llvm::dyn_cast<swift::SourceFile>(file_unit)) {
s.Printf("filename = '%s', ", source_file->getFilename().str().c_str());
s.PutCString("source file kind = ");
switch (source_file->Kind) {
case swift::SourceFileKind::Library:
s.PutCString("Library");
case swift::SourceFileKind::Main:
s.PutCString("Main");
case swift::SourceFileKind::REPL:
s.PutCString("REPL");
case swift::SourceFileKind::SIL:
s.PutCString("SIL");
}
}
} break;
case swift::FileUnitKind::Builtin: {
s.PutCString("Builtin");
} break;
case swift::FileUnitKind::SerializedAST:
case swift::FileUnitKind::ClangModule: {
if (file_unit->getKind() == swift::FileUnitKind::SerializedAST)
s.PutCString("Serialized Swift AST, ");
else
s.PutCString("Clang module, ");
swift::LoadedFile *loaded_file = llvm::cast<swift::LoadedFile>(file_unit);
s.Printf("filename = '%s'", loaded_file->getFilename().str().c_str());
} break;
};
}
// Gets the full module name from the module passed in.
static void GetNameFromModule(swift::ModuleDecl *module, std::string &result) {
result.clear();
if (module) {
const char *name = module->getName().get();
if (!name)
return;
result.append(name);
const clang::Module *clang_module = module->findUnderlyingClangModule();
// At present, there doesn't seem to be any way to get the full module path
// from the Swift side.
if (!clang_module)
return;
for (const clang::Module *cur_module = clang_module->Parent; cur_module;
cur_module = cur_module->Parent) {
if (!cur_module->Name.empty()) {
result.insert(0, 1, '.');
result.insert(0, cur_module->Name);
}
}
}
}
/// Largely lifted from swift::performAutoImport, but serves our own nefarious
/// purposes.
static bool PerformAutoImport(SwiftASTContext &swift_ast_context,
SymbolContext &sc, ExecutionContextScope &exe_scope,
lldb::StackFrameWP &stack_frame_wp,
swift::SourceFile &source_file, bool user_imports,
Status &error) {
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
const std::vector<ConstString> *cu_modules = nullptr;
CompileUnit *compile_unit = sc.comp_unit;
if (compile_unit && compile_unit->GetLanguage() == lldb::eLanguageTypeSwift)
cu_modules = &compile_unit->GetImportedModules();
llvm::SmallVector<swift::ModuleDecl::ImportedModule, 2> imported_modules;
llvm::SmallVector<swift::SourceFile::ImportedModuleDesc, 2>
additional_imports;
source_file.getImportedModules(imported_modules,
swift::ModuleDecl::ImportFilter::All);
std::set<ConstString> loaded_modules;
auto load_one_module = [&](const ConstString &module_name) {
error.Clear();
if (loaded_modules.count(module_name))
return true;
if (log)
log->Printf("[PerformAutoImport] Importing module %s",
module_name.AsCString());
loaded_modules.insert(module_name);
swift::ModuleDecl *swift_module = nullptr;
lldb::StackFrameSP this_frame_sp(stack_frame_wp.lock());
if (module_name == ConstString(swift_ast_context.GetClangImporter()
->getImportedHeaderModule()
->getName()
.str()))
swift_module =
swift_ast_context.GetClangImporter()->getImportedHeaderModule();
else if (this_frame_sp) {
lldb::ProcessSP process_sp(this_frame_sp->CalculateProcess());
if (process_sp)
swift_module = swift_ast_context.FindAndLoadModule(
module_name, *process_sp.get(), error);
} else
swift_module = swift_ast_context.GetModule(module_name, error);
if (!swift_module || !error.Success() ||
swift_ast_context.HasFatalErrors()) {
if (log)
log->Printf("[PerformAutoImport] Couldn't import module %s: %s",
module_name.AsCString(), error.AsCString());
if (!swift_module || swift_ast_context.HasFatalErrors()) {
return false;
}
}
if (log) {
log->Printf("Importing %s with source files:", module_name.AsCString());
for (swift::FileUnit *file_unit : swift_module->getFiles()) {
StreamString ss;
DescribeFileUnit(ss, file_unit);
log->Printf(" %s", ss.GetData());
}
}
additional_imports.push_back(swift::SourceFile::ImportedModuleDesc(
std::make_pair(swift::ModuleDecl::AccessPathTy(), swift_module),
swift::SourceFile::ImportOptions()));
imported_modules.push_back(
std::make_pair(swift::ModuleDecl::AccessPathTy(), swift_module));
return true;
};
if (!user_imports) {
if (!load_one_module(ConstString("Swift")))
return false;
if (cu_modules) {
for (const ConstString &module_name : *cu_modules) {
if (!load_one_module(module_name))
return false;
}
}
} else {
llvm::SmallVector<swift::ModuleDecl::ImportedModule, 2> parsed_imports;
source_file.getImportedModules(parsed_imports,
swift::ModuleDecl::ImportFilter::All);
auto *persistent_expression_state =
sc.target_sp->GetSwiftPersistentExpressionState(exe_scope);
for (auto module_pair : parsed_imports) {
swift::ModuleDecl *module = module_pair.second;
if (module) {
std::string module_name;
GetNameFromModule(module, module_name);
if (!module_name.empty()) {
ConstString module_const_str(module_name);
if (log)
log->Printf("[PerformAutoImport] Performing auto import on found "
"module: %s.\n",
module_name.c_str());
if (!load_one_module(module_const_str))
return false;
// How do we tell we are in REPL or playground mode?
persistent_expression_state->AddHandLoadedModule(module_const_str);
}
}
}
// Finally get the hand-loaded modules from the
// SwiftPersistentExpressionState and load them into this context:
if (!persistent_expression_state->RunOverHandLoadedModules(load_one_module))
return false;
}
source_file.addImports(additional_imports);
return true;
}
class VariableMetadataPersistent
: public SwiftASTManipulatorBase::VariableMetadata {
public:
VariableMetadataPersistent(lldb::ExpressionVariableSP &persistent_variable_sp)
: m_persistent_variable_sp(persistent_variable_sp) {}
static constexpr unsigned Type() { return 'Pers'; }
virtual unsigned GetType() { return Type(); }
lldb::ExpressionVariableSP m_persistent_variable_sp;
};
class VariableMetadataVariable
: public SwiftASTManipulatorBase::VariableMetadata {
public:
VariableMetadataVariable(lldb::VariableSP &variable_sp)
: m_variable_sp(variable_sp) {}
static constexpr unsigned Type() { return 'Vari'; }
virtual unsigned GetType() { return Type(); }
lldb::VariableSP m_variable_sp;
};
static CompilerType ImportType(SwiftASTContext &target_context,
CompilerType source_type) {
SwiftASTContext *swift_ast_ctx =
llvm::dyn_cast_or_null<SwiftASTContext>(source_type.GetTypeSystem());
if (swift_ast_ctx == nullptr)
return CompilerType();
if (swift_ast_ctx == &target_context)
return source_type;
Status error, mangled_error;
CompilerType target_type;
// First try to get the type by using the mangled name,
// That will save the mangling step ImportType would have to do:
ConstString type_name = source_type.GetTypeName();
ConstString mangled_counterpart;
bool found_counterpart = type_name.GetMangledCounterpart(mangled_counterpart);
if (found_counterpart)
target_type = target_context.GetTypeFromMangledTypename(
mangled_counterpart.GetCString(), mangled_error);
if (!target_type.IsValid())
target_type = target_context.ImportType(source_type, error);
return target_type;
}
namespace {
class LLDBNameLookup : public swift::SILDebuggerClient {
public:
LLDBNameLookup(swift::SourceFile &source_file,
SwiftExpressionParser::SILVariableMap &variable_map,
SymbolContext &sc, ExecutionContextScope &exe_scope)
: SILDebuggerClient(source_file.getASTContext()),
m_log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)),
m_source_file(source_file), m_variable_map(variable_map), m_sc(sc) {
source_file.getParentModule()->setDebugClient(this);
if (!m_sc.target_sp)
return;
m_persistent_vars =
m_sc.target_sp->GetSwiftPersistentExpressionState(exe_scope);
}
virtual ~LLDBNameLookup() {}
virtual swift::SILValue emitLValueForVariable(swift::VarDecl *var,
swift::SILBuilder &builder) {
SwiftSILManipulator manipulator(builder);
swift::Identifier variable_name = var->getName();
ConstString variable_const_string(variable_name.get());
SwiftExpressionParser::SILVariableMap::iterator vi =
m_variable_map.find(variable_const_string.AsCString());
if (vi == m_variable_map.end())
return swift::SILValue();
return manipulator.emitLValueForVariable(var, vi->second);
}
SwiftPersistentExpressionState::SwiftDeclMap &GetStagedDecls() {
return m_staged_decls;
}
protected:
Log *m_log;
swift::SourceFile &m_source_file;
SwiftExpressionParser::SILVariableMap &m_variable_map;
SymbolContext m_sc;
SwiftPersistentExpressionState *m_persistent_vars = nullptr;
// Subclasses stage globalized decls in this map. They get copied over to the
// SwiftPersistentVariable store if the parse succeeds.
SwiftPersistentExpressionState::SwiftDeclMap m_staged_decls;
};
/// A name lookup class for debugger expr mode.
class LLDBExprNameLookup : public LLDBNameLookup {
public:
LLDBExprNameLookup(swift::SourceFile &source_file,
SwiftExpressionParser::SILVariableMap &variable_map,
SymbolContext &sc, ExecutionContextScope &exe_scope)
: LLDBNameLookup(source_file, variable_map, sc, exe_scope) {}
virtual ~LLDBExprNameLookup() {}
virtual bool shouldGlobalize(swift::Identifier Name, swift::DeclKind Kind) {
// Extensions have to be globalized, there's no way to mark them as local
// to the function, since their
// name is the name of the thing being extended...
if (Kind == swift::DeclKind::Extension)
return true;
// Operators need to be parsed at the global scope regardless of name.
if (Kind == swift::DeclKind::Func && Name.isOperator())
return true;
const char *name_cstr = Name.get();
if (name_cstr && name_cstr[0] == '$') {
if (m_log)
m_log->Printf("[LLDBExprNameLookup::shouldGlobalize] Returning true to "
"globalizing %s",
name_cstr);
return true;
}
return false;
}
virtual void didGlobalize(swift::Decl *decl) {
swift::ValueDecl *value_decl = swift::dyn_cast<swift::ValueDecl>(decl);
if (value_decl) {
// It seems weird to be asking this again, but some DeclKinds must be
// moved to
// the source-file level to be legal. But we don't want to register them
// with
// lldb unless they are of the kind lldb explicitly wants to globalize.
if (shouldGlobalize(value_decl->getBaseName().getIdentifier(),
value_decl->getKind()))
m_staged_decls.AddDecl(value_decl, false, ConstString());
}
}
virtual bool lookupOverrides(swift::DeclBaseName Name, swift::DeclContext *DC,
swift::SourceLoc Loc, bool IsTypeLookup,
ResultVector &RV) {
static unsigned counter = 0;
unsigned count = counter++;
if (m_log) {
m_log->Printf("[LLDBExprNameLookup::lookupOverrides(%u)] Searching for %s",
count, Name.getIdentifier().get());
}
return false;
}
virtual bool lookupAdditions(swift::DeclBaseName Name, swift::DeclContext *DC,
swift::SourceLoc Loc, bool IsTypeLookup,
ResultVector &RV) {
static unsigned counter = 0;
unsigned count = counter++;
StringRef NameStr = Name.getIdentifier().str();
if (m_log) {
m_log->Printf("[LLDBExprNameLookup::lookupAdditions (%u)] Searching for %s",
count, Name.getIdentifier().str().str().c_str());
}
ConstString name_const_str(NameStr);
std::vector<swift::ValueDecl *> results;
// First look up the matching decls we've made in this compile. Later,
// when we look for persistent decls, these staged decls take precedence.
m_staged_decls.FindMatchingDecls(name_const_str, {}, results);
// Next look up persistent decls matching this name. Then, if we aren't
// looking at a debugger variable, filter out persistent results of the same
// kind as one found by the ordinary lookup mechanism in the parser. The
// problem we are addressing here is the case where the user has entered the
// REPL while in an ordinary debugging session to play around. While there,
// e.g., they define a class that happens to have the same name as one in
// the program, then in some other context "expr" will call the class
// they've defined, not the one in the program itself would use. Plain
// "expr" should behave as much like code in the program would, so we want
// to favor entities of the same DeclKind & name from the program over ones
// defined in the REPL. For function decls we check the interface type and
// full name so we don't remove overloads that don't exist in the current
// scope.
//
// Note also, we only do this for the persistent decls. Anything in the
// "staged" list has been defined in this expr setting and so is more local
// than local.
if (m_persistent_vars) {
bool is_debugger_variable = !NameStr.empty() && NameStr.front() == '$';
size_t num_external_results = RV.size();
if (!is_debugger_variable && num_external_results > 0) {
std::vector<swift::ValueDecl *> persistent_results;
m_persistent_vars->GetSwiftPersistentDecls(name_const_str, {},
persistent_results);
size_t num_persistent_results = persistent_results.size();
for (size_t idx = 0; idx < num_persistent_results; idx++) {
swift::ValueDecl *value_decl = persistent_results[idx];
if (!value_decl)
continue;
swift::DeclName value_decl_name = value_decl->getFullName();
swift::DeclKind value_decl_kind = value_decl->getKind();
swift::CanType value_interface_type =
value_decl->getInterfaceType()->getCanonicalType();
bool is_function =
swift::isa<swift::AbstractFunctionDecl>(value_decl);
bool skip_it = false;
for (size_t rv_idx = 0; rv_idx < num_external_results; rv_idx++) {
if (swift::ValueDecl *rv_decl = RV[rv_idx].getValueDecl()) {
if (value_decl_kind == rv_decl->getKind()) {
if (is_function) {
swift::DeclName rv_full_name = rv_decl->getFullName();
if (rv_full_name.matchesRef(value_decl_name)) {
// If the full names match, make sure the interface types
// match:
if (rv_decl->getInterfaceType()->getCanonicalType() ==
value_interface_type)
skip_it = true;
}
} else {
skip_it = true;
}
if (skip_it)
break;
}
}
}
if (!skip_it)
results.push_back(value_decl);
}
} else {
m_persistent_vars->GetSwiftPersistentDecls(name_const_str, results,
results);
}
}
for (size_t idx = 0; idx < results.size(); idx++) {
swift::ValueDecl *value_decl = results[idx];
assert(&DC->getASTContext() ==
&value_decl->getASTContext()); // no import required
RV.push_back(swift::LookupResultEntry(value_decl));
}
return results.size() > 0;
}
virtual swift::Identifier getPreferredPrivateDiscriminator() {
if (m_sc.comp_unit) {
if (lldb_private::Module *module = m_sc.module_sp.get()) {
if (lldb_private::SymbolVendor *symbol_vendor =
module->GetSymbolVendor()) {
std::string private_discriminator_string;
if (symbol_vendor->GetCompileOption("-private-discriminator",
private_discriminator_string,
m_sc.comp_unit)) {
return m_source_file.getASTContext().getIdentifier(
private_discriminator_string);
}
}
}
}
return swift::Identifier();
}
};
/// A name lookup class for REPL and Playground mode.
class LLDBREPLNameLookup : public LLDBNameLookup {
public:
LLDBREPLNameLookup(swift::SourceFile &source_file,
SwiftExpressionParser::SILVariableMap &variable_map,
SymbolContext &sc, ExecutionContextScope &exe_scope)
: LLDBNameLookup(source_file, variable_map, sc, exe_scope) {}
virtual ~LLDBREPLNameLookup() {}
virtual bool shouldGlobalize(swift::Identifier Name, swift::DeclKind kind) {
return false;
}
virtual void didGlobalize (swift::Decl *Decl) {}
virtual bool lookupOverrides(swift::DeclBaseName Name, swift::DeclContext *DC,
swift::SourceLoc Loc, bool IsTypeLookup,
ResultVector &RV) {
return false;
}
virtual bool lookupAdditions(swift::DeclBaseName Name, swift::DeclContext *DC,
swift::SourceLoc Loc, bool IsTypeLookup,
ResultVector &RV) {
static unsigned counter = 0;
unsigned count = counter++;
StringRef NameStr = Name.getIdentifier().str();
ConstString name_const_str(NameStr);
if (m_log) {
m_log->Printf("[LLDBREPLNameLookup::lookupAdditions (%u)] Searching for %s",
count, Name.getIdentifier().str().str().c_str());
}
// Find decls that come from the current compilation.
std::vector<swift::ValueDecl *> current_compilation_results;
for (auto result : RV) {
auto result_decl = result.getValueDecl();
auto result_decl_context = result_decl->getDeclContext();
if (result_decl_context->isChildContextOf(DC) || result_decl_context == DC)
current_compilation_results.push_back(result_decl);
}
// Find persistent decls, excluding decls that are equivalent to decls from
// the current compilation. This makes the decls from the current
// compilation take precedence.
std::vector<swift::ValueDecl *> persistent_decl_results;
m_persistent_vars->GetSwiftPersistentDecls(name_const_str,
current_compilation_results,
persistent_decl_results);
// Append the persistent decls that we found to the result vector.
for (auto result : persistent_decl_results) {
assert(&DC->getASTContext() ==
&result->getASTContext()); // no import required
RV.push_back(swift::LookupResultEntry(result));
}
return !persistent_decl_results.empty();
}
virtual swift::Identifier getPreferredPrivateDiscriminator() {
return swift::Identifier();
}
};
}; // END Anonymous namespace
static void
AddRequiredAliases(Block *block, lldb::StackFrameSP &stack_frame_sp,
SwiftASTContext &swift_ast_context,
SwiftASTManipulator &manipulator,
const Expression::SwiftGenericInfo &generic_info) {
// First, emit the typealias for "$__lldb_context"
if (!block)
return;
Function *function = block->CalculateSymbolContextFunction();
if (!function)
return;
constexpr bool can_create = true;
Block &function_block(function->GetBlock(can_create));
lldb::VariableListSP variable_list_sp(
function_block.GetBlockVariableList(true));
if (!variable_list_sp)
return;
lldb::VariableSP self_var_sp(
variable_list_sp->FindVariable(ConstString("self")));
if (!self_var_sp)
return;
CompilerType self_type;
if (stack_frame_sp) {
lldb::ValueObjectSP valobj_sp =
stack_frame_sp->GetValueObjectForFrameVariable(self_var_sp,
lldb::eNoDynamicValues);
if (valobj_sp)
self_type = valobj_sp->GetCompilerType();
}
if (!self_type.IsValid()) {
if (Type *type = self_var_sp->GetType()) {
self_type = type->GetForwardCompilerType();
}
}
if (!self_type.IsValid() ||
!llvm::isa<SwiftASTContext>(self_type.GetTypeSystem()))
return;
// Import before getting the unbound version, because the unbound version
// may not be in the mangled name map
CompilerType imported_self_type = ImportType(swift_ast_context, self_type);
if (!imported_self_type.IsValid())
return;
// This might be a referenced type, in which case we really want to extend
// the referent:
imported_self_type =
llvm::cast<SwiftASTContext>(imported_self_type.GetTypeSystem())
->GetReferentType(imported_self_type);
// If we are extending a generic class it's going to be a metatype, and we
// have to grab the instance type:
imported_self_type =
llvm::cast<SwiftASTContext>(imported_self_type.GetTypeSystem())
->GetInstanceType(imported_self_type.GetOpaqueQualType());
Flags imported_self_type_flags(imported_self_type.GetTypeInfo());
// If 'self' is the Self archetype, resolve it to the actual metatype it is
if (SwiftASTContext::IsSelfArchetypeType(imported_self_type)) {
SwiftLanguageRuntime *swift_runtime =
stack_frame_sp->GetThread()->GetProcess()->GetSwiftLanguageRuntime();
// Assume self is always the first type parameter.
if (CompilerType concrete_self_type = swift_runtime->GetConcreteType(
stack_frame_sp.get(), ConstString(u8"\u03C4_0_0"))) {
if (SwiftASTContext *concrete_self_type_ast_ctx =
llvm::dyn_cast_or_null<SwiftASTContext>(
concrete_self_type.GetTypeSystem())) {
imported_self_type =
concrete_self_type_ast_ctx->CreateMetatypeType(concrete_self_type);
imported_self_type_flags.Reset(imported_self_type.GetTypeInfo());
imported_self_type = ImportType(swift_ast_context, imported_self_type);
if (imported_self_type_flags.AllSet(lldb::eTypeIsSwift |
lldb::eTypeIsMetatype)) {
imported_self_type = imported_self_type.GetInstanceType();
}
}
}
}
// Get the instance type:
if (imported_self_type_flags.AllSet(lldb::eTypeIsSwift |
lldb::eTypeIsMetatype)) {
imported_self_type = imported_self_type.GetInstanceType();
imported_self_type_flags.Reset(imported_self_type.GetTypeInfo());
}
swift::Type object_type =
swift::Type((swift::TypeBase *)(imported_self_type.GetOpaqueQualType()))
->getWithoutSpecifierType();
if (object_type.getPointer() &&
(object_type.getPointer() != imported_self_type.GetOpaqueQualType()))
imported_self_type = CompilerType(imported_self_type.GetTypeSystem(),
object_type.getPointer());
// If the type of 'self' is a bound generic type, get the unbound version
bool is_generic = imported_self_type_flags.AllSet(lldb::eTypeIsSwift |
lldb::eTypeIsGeneric);
bool is_bound =
imported_self_type_flags.AllSet(lldb::eTypeIsSwift | lldb::eTypeIsBound);
if (is_generic) {
if (is_bound)
imported_self_type = imported_self_type.GetUnboundType();
}
// if 'self' is a weak storage type, it must be an optional. Look through
// it and unpack the argument of "optional".
if (swift::WeakStorageType *weak_storage_type =
((swift::TypeBase *)imported_self_type.GetOpaqueQualType())
->getAs<swift::WeakStorageType>()) {
swift::Type referent_type = weak_storage_type->getReferentType();
swift::BoundGenericEnumType *optional_type =
referent_type->getAs<swift::BoundGenericEnumType>();
if (!optional_type)
return;
swift::Type first_arg_type = optional_type->getGenericArgs()[0];
swift::ClassType *self_class_type =
first_arg_type->getAs<swift::ClassType>();
if (!self_class_type)
return;
imported_self_type =
CompilerType(imported_self_type.GetTypeSystem(), self_class_type);
}
imported_self_type_flags.Reset(imported_self_type.GetTypeInfo());
if (imported_self_type_flags.AllClear(lldb::eTypeIsGenericTypeParam)) {
swift::ValueDecl *type_alias_decl = nullptr;
type_alias_decl = manipulator.MakeGlobalTypealias(
swift_ast_context.GetASTContext()->getIdentifier("$__lldb_context"),
imported_self_type);
if (!type_alias_decl) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (log)
log->Printf("SEP:AddRequiredAliases: Failed to make the "
"$__lldb_context typealias.");
}
} else {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (log)
log->Printf("SEP:AddRequiredAliases: Failed to resolve the self "
"archetype - could not make the $__lldb_context "
"typealias.");
}
}
static void CountLocals(
SymbolContext &sc, lldb::StackFrameSP &stack_frame_sp,
SwiftASTContext &ast_context,
llvm::SmallVectorImpl<SwiftASTManipulator::VariableInfo> &local_variables) {
std::set<ConstString> counted_names; // avoids shadowing
if (!sc.block && !sc.function)
return;
Block *block = sc.block;
Block *top_block = block->GetContainingInlinedBlock();
if (!top_block)
top_block = &sc.function->GetBlock(true);
static ConstString s_self_name("self");
SwiftLanguageRuntime *language_runtime = nullptr;
ExecutionContextScope *scope = nullptr;
if (stack_frame_sp) {
language_runtime =
stack_frame_sp->GetThread()->GetProcess()->GetSwiftLanguageRuntime();
scope = stack_frame_sp.get();
}
// The module scoped variables are stored at the CompUnit level, so after we
// go through the current context,
// then we have to take one more pass through the variables in the CompUnit.
bool handling_globals = false;
while (true) {
VariableList variables;
if (!handling_globals) {
constexpr bool can_create = true;
constexpr bool get_parent_variables = false;
constexpr bool stop_if_block_is_inlined_function = true;
block->AppendVariables(can_create, get_parent_variables,
stop_if_block_is_inlined_function,
[](Variable *) { return true; }, &variables);
} else {
if (sc.comp_unit) {
lldb::VariableListSP globals_sp = sc.comp_unit->GetVariableList(true);
if (globals_sp)
variables.AddVariables(globals_sp.get());
}
}
for (size_t vi = 0, ve = variables.GetSize(); vi != ve; ++vi) {
lldb::VariableSP variable_sp(variables.GetVariableAtIndex(vi));
const ConstString &name(variable_sp->GetUnqualifiedName());
const char *name_cstring = variable_sp->GetUnqualifiedName().GetCString();
if (name.IsEmpty())
continue;
if (counted_names.count(name))
continue;
CompilerType var_type;
if (stack_frame_sp) {
lldb::ValueObjectSP valobj_sp =
stack_frame_sp->GetValueObjectForFrameVariable(
variable_sp, lldb::eNoDynamicValues);
if (!valobj_sp || valobj_sp->GetError().Fail()) {
// Ignore the variable if we couldn't find its corresponding value
// object.
// TODO if the expression tries to use an ignored variable, produce a
// sensible error.
continue;
} else {
var_type = valobj_sp->GetCompilerType();
}
if (var_type.IsValid() && !SwiftASTContext::IsFullyRealized(var_type)) {
lldb::ValueObjectSP dynamic_valobj_sp =
valobj_sp->GetDynamicValue(lldb::eDynamicDontRunTarget);
if (!dynamic_valobj_sp || dynamic_valobj_sp->GetError().Fail()) {
continue;
}
}
}
if (!var_type.IsValid()) {
Type *var_lldb_type = variable_sp->GetType();
if (var_lldb_type)
var_type = var_lldb_type->GetFullCompilerType();
}
if (!var_type.IsValid())
continue;
if (!llvm::isa<SwiftASTContext>(var_type.GetTypeSystem()))
continue;
Status error;
CompilerType target_type = ast_context.ImportType(var_type, error);
// If the import failed, give up
if (!target_type.IsValid())
continue;
// Make sure to resolve all archetypes in the variable type.
if (stack_frame_sp) {
if (language_runtime)
target_type = language_runtime->DoArchetypeBindingForType(
*stack_frame_sp, target_type);
if (auto *ts = target_type.GetTypeSystem())
target_type =
ts->MapIntoContext(stack_frame_sp, target_type.GetOpaqueQualType());
}
// If we couldn't fully realize the type, then we aren't going to get very
// far making a local out of it,
// so discard it here.
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TYPES |
LIBLLDB_LOG_EXPRESSIONS));
if (!SwiftASTContext::IsFullyRealized(target_type)) {
if (log) {
log->Printf("Discarding local %s because we couldn't fully realize "
"it, our best attempt was: %s.",
name_cstring,
target_type.GetTypeName().AsCString("<unknown>"));
}
continue;
}
SwiftASTManipulatorBase::VariableMetadataSP metadata_sp(
new VariableMetadataVariable(variable_sp));
const char *overridden_name = name_cstring;
if (name == s_self_name) {
overridden_name = ConstString("$__lldb_injected_self").AsCString();
if (log) {
swift::TypeBase *swift_type =
(swift::TypeBase *)target_type.GetOpaqueQualType();
if (swift_type) {
std::string s;
llvm::raw_string_ostream ss(s);
swift_type->dump(ss);
ss.flush();
log->Printf("Adding injected self: type (%p) context(%p) is: %s",
swift_type, ast_context.GetASTContext(), s.c_str());
}
}
}
SwiftASTManipulator::VariableInfo variable_info(
target_type,
ast_context.GetASTContext()->getIdentifier(overridden_name),
metadata_sp,
swift::VarDecl::Specifier::Var);
local_variables.push_back(variable_info);
counted_names.insert(name);
}
if (handling_globals) {
// Okay, now we're done...
break;
} else if (block == top_block) {
// Now add the containing module block, that's what holds the module
// globals:
handling_globals = true;
} else
block = block->GetParent();
}
}
static void ResolveSpecialNames(
SymbolContext &sc, ExecutionContextScope &exe_scope,
SwiftASTContext &ast_context,
llvm::SmallVectorImpl<swift::Identifier> &special_names,
llvm::SmallVectorImpl<SwiftASTManipulator::VariableInfo> &local_variables) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (!sc.target_sp)
return;
auto *persistent_state =
sc.target_sp->GetSwiftPersistentExpressionState(exe_scope);
std::set<ConstString> resolved_names;
for (swift::Identifier &name : special_names) {
ConstString name_cs = ConstString(name.str());
if (resolved_names.count(name_cs))
continue;
resolved_names.insert(name_cs);
if (log)
log->Printf("Resolving special name %s", name_cs.AsCString());
lldb::ExpressionVariableSP expr_var_sp =
persistent_state->GetVariable(name_cs);
if (!expr_var_sp)
continue;
CompilerType var_type = expr_var_sp->GetCompilerType();
if (!var_type.IsValid())
continue;
if (!llvm::isa<SwiftASTContext>(var_type.GetTypeSystem()))
continue;
CompilerType target_type;
Status error;
target_type = ast_context.ImportType(var_type, error);
if (!target_type)
continue;
SwiftASTManipulatorBase::VariableMetadataSP metadata_sp(
new VariableMetadataPersistent(expr_var_sp));
auto specifier = llvm::cast<SwiftExpressionVariable>(expr_var_sp.get())
->GetIsModifiable()
? swift::VarDecl::Specifier::Var
: swift::VarDecl::Specifier::Let;
SwiftASTManipulator::VariableInfo variable_info(
target_type, ast_context.GetASTContext()->getIdentifier(name.str()),
metadata_sp, specifier);
local_variables.push_back(variable_info);
}
}
//----------------------------------------------------------------------
// Diagnostics are part of the ShintASTContext and we must enable and
// disable colorization manually in the ShintASTContext. We need to
// ensure that if we modify the setting that we restore it to what it
// was. This class helps us to do that without having to intrument all
// returns from a function, like in SwiftExpressionParser::Parse(...).
//----------------------------------------------------------------------
class SetColorize {
public:
SetColorize(SwiftASTContext *swift_ast, bool colorize)
: m_swift_ast(swift_ast),
m_saved_colorize(swift_ast->SetColorizeDiagnostics(colorize)) {}
~SetColorize() { m_swift_ast->SetColorizeDiagnostics(m_saved_colorize); }
protected:
SwiftASTContext *m_swift_ast;
const bool m_saved_colorize;
};
/// Initialize the SwiftASTContext and return the wrapped
/// swift::ASTContext when successful.
static swift::ASTContext *SetupASTContext(
SwiftASTContext *swift_ast_context, DiagnosticManager &diagnostic_manager,
std::function<bool()> disable_objc_runtime, bool repl, bool playground) {
if (!swift_ast_context) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"No AST context to parse into. Please parse with a target.\n");
return nullptr;
}
// Lazily get the clang importer if we can to make sure it exists in case we
// need it.
if (!swift_ast_context->GetClangImporter()) {
std::string swift_error = "Fatal Swift ";
swift_error +=
swift_ast_context->GetFatalErrors().AsCString("error: unknown error.");
diagnostic_manager.PutString(eDiagnosticSeverityError, swift_error);
diagnostic_manager.PutString(
eDiagnosticSeverityRemark,
"Swift expressions require OS X 10.10 / iOS 8 SDKs or later.\n");
return nullptr;
}
if (swift_ast_context->HasFatalErrors()) {
diagnostic_manager.PutString(eDiagnosticSeverityError,
"The AST context is in a fatal error state.");
return nullptr;
}
swift::ASTContext *ast_context = swift_ast_context->GetASTContext();
if (!ast_context) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"Couldn't initialize the AST context. Please check your settings.");
return nullptr;
}
if (swift_ast_context->HasFatalErrors()) {
diagnostic_manager.PutString(eDiagnosticSeverityError,
"The AST context is in a fatal error state.");
return nullptr;
}
// TODO find a way to get contraint-solver output sent to a stream so we can
// log it
// swift_ast_context->GetLanguageOptions().DebugConstraintSolver = true;
swift_ast_context->ClearDiagnostics();
// Make a class that will set/restore the colorize setting in the
// SwiftASTContext for us
// SetColorize colorize(swift_ast_context,
// stream.GetFlags().Test(Stream::eANSIColor));
swift_ast_context->GetLanguageOptions().DebuggerSupport = true;
swift_ast_context->GetLanguageOptions().EnableDollarIdentifiers =
true; // No longer part of debugger support, set it separately.
swift_ast_context->GetLanguageOptions().EnableAccessControl =
(repl || playground);
swift_ast_context->GetLanguageOptions().EnableTargetOSChecking = false;
if (disable_objc_runtime())
swift_ast_context->GetLanguageOptions().EnableObjCInterop = false;
swift_ast_context->GetLanguageOptions().Playground = repl || playground;
swift_ast_context->GetIRGenOptions().Playground = repl || playground;
// For the expression parser and REPL we want to relax the
// requirement that you put "try" in front of every expression that
// might throw.
if (repl || !playground)
swift_ast_context->GetLanguageOptions().EnableThrowWithoutTry = true;
// SWIFT_ENABLE_TENSORFLOW
// FIXME: When partitioning joins the mandatory pass pipeline, we should be able to
// switch this back to NoOptimization.
swift_ast_context->GetIRGenOptions().OptMode =
swift::OptimizationMode::ForSpeed;
// Normally we'd like to verify, but unfortunately the verifier's
// error mode is abort().
swift_ast_context->GetIRGenOptions().Verify = false;
return ast_context;
}
/// Returns the buffer_id for the expression's source code.
static std::pair<unsigned, std::string>
CreateMainFile(SwiftASTContext &swift_ast_context, StringRef filename,
StringRef text, const EvaluateExpressionOptions &options) {
const bool generate_debug_info = options.GetGenerateDebugInfo();
swift_ast_context.SetGenerateDebugInfo(generate_debug_info
? swift::IRGenDebugInfoLevel::Normal
: swift::IRGenDebugInfoLevel::None);
swift::IRGenOptions &ir_gen_options = swift_ast_context.GetIRGenOptions();
if (generate_debug_info) {
std::string temp_source_path;
if (ExpressionSourceCode::SaveExpressionTextToTempFile(text, options,
temp_source_path)) {
auto error_or_buffer_ap =
llvm::MemoryBuffer::getFile(temp_source_path.c_str());
if (error_or_buffer_ap.getError() == std::error_condition()) {
unsigned buffer_id =
swift_ast_context.GetSourceManager().addNewSourceBuffer(
std::move(error_or_buffer_ap.get()));
llvm::SmallString<256> source_dir(temp_source_path);
llvm::sys::path::remove_filename(source_dir);
ir_gen_options.DebugCompilationDir = source_dir.str();
return {buffer_id, temp_source_path};
}
}
}
std::unique_ptr<llvm::MemoryBuffer> expr_buffer(
llvm::MemoryBuffer::getMemBufferCopy(text, filename));
unsigned buffer_id = swift_ast_context.GetSourceManager().addNewSourceBuffer(
std::move(expr_buffer));
return {buffer_id, filename};
}
/// Attempt to materialize one variable.
static llvm::Optional<SwiftExpressionParser::SILVariableInfo>
MaterializeVariable(SwiftASTManipulatorBase::VariableInfo &variable,
SwiftUserExpression &user_expression,
Materializer &materializer,
SwiftASTManipulator &manipulator,
lldb::StackFrameWP &stack_frame_wp,
DiagnosticManager &diagnostic_manager, Log *log,
bool repl) {
uint64_t offset = 0;
bool needs_init = false;
bool is_result =
variable.MetadataIs<SwiftASTManipulatorBase::VariableMetadataResult>();
bool is_error =
variable.MetadataIs<SwiftASTManipulatorBase::VariableMetadataError>();
if (is_result || is_error) {
needs_init = true;
Status error;
if (repl) {
if (swift::TypeBase *swift_type =
(swift::TypeBase *)variable.GetType().GetOpaqueQualType()) {
if (!swift_type->getCanonicalType()->isVoid()) {
auto &repl_mat = *llvm::cast<SwiftREPLMaterializer>(&materializer);
if (is_result)
offset = repl_mat.AddREPLResultVariable(
variable.GetType(), variable.GetDecl(),
&user_expression.GetResultDelegate(), error);
else
offset = repl_mat.AddREPLResultVariable(
variable.GetType(), variable.GetDecl(),
&user_expression.GetErrorDelegate(), error);
}
}
} else {
CompilerType actual_type(variable.GetType());
auto *orig_swift_type = (swift::TypeBase *)actual_type.GetOpaqueQualType();
auto *swift_type = orig_swift_type->mapTypeOutOfContext().getPointer();
actual_type.SetCompilerType(actual_type.GetTypeSystem(), swift_type);
lldb::StackFrameSP stack_frame_sp = stack_frame_wp.lock();
if (swift_type->hasTypeParameter()) {
if (stack_frame_sp && stack_frame_sp->GetThread() &&
stack_frame_sp->GetThread()->GetProcess()) {
SwiftLanguageRuntime *swift_runtime = stack_frame_sp->GetThread()
->GetProcess()
->GetSwiftLanguageRuntime();
if (swift_runtime) {
StreamString type_name;
if (SwiftLanguageRuntime::GetAbstractTypeName(type_name, swift_type))
actual_type = swift_runtime->GetConcreteType(
stack_frame_sp.get(), ConstString(type_name.GetString()));
if (actual_type.IsValid())
variable.SetType(actual_type);
else
actual_type = variable.GetType();
}
}
}
if (stack_frame_sp) {
auto *ctx = llvm::cast<SwiftASTContext>(actual_type.GetTypeSystem());
actual_type = ctx->MapIntoContext(stack_frame_sp,
actual_type.GetOpaqueQualType());
}
swift::Type actual_swift_type =
(swift::TypeBase *)actual_type.GetOpaqueQualType();
if (actual_swift_type->hasTypeParameter())
actual_swift_type = orig_swift_type;
swift::Type fixed_type = manipulator.FixupResultType(
actual_swift_type, user_expression.GetLanguageFlags());
if (!fixed_type.isNull()) {
actual_type =
CompilerType(actual_type.GetTypeSystem(), fixed_type.getPointer());
variable.SetType(actual_type);
}
if (is_result)
offset = materializer.AddResultVariable(
actual_type, false, true, &user_expression.GetResultDelegate(),
error);
else
offset = materializer.AddResultVariable(
actual_type, false, true, &user_expression.GetErrorDelegate(),
error);
}
if (!error.Success()) {
diagnostic_manager.Printf(
eDiagnosticSeverityError, "couldn't add %s variable to struct: %s.\n",
is_result ? "result" : "error", error.AsCString());
return llvm::None;
}
if (log)
log->Printf("Added %s variable to struct at offset %llu",
is_result ? "result" : "error", (unsigned long long)offset);
} else if (variable.MetadataIs<VariableMetadataVariable>()) {
Status error;
VariableMetadataVariable *variable_metadata =
static_cast<VariableMetadataVariable *>(variable.m_metadata.get());
// FIXME: It would be nice if we could do something like
// variable_metadata->m_variable_sp->SetType(variable.GetType())
// here.
offset = materializer.AddVariable(variable_metadata->m_variable_sp, error);
if (!error.Success()) {
diagnostic_manager.Printf(eDiagnosticSeverityError,
"couldn't add variable to struct: %s.\n",
error.AsCString());
return llvm::None;
}
if (log)
log->Printf("Added variable %s to struct at offset %llu",
variable_metadata->m_variable_sp->GetName().AsCString(),
(unsigned long long)offset);
} else if (variable.MetadataIs<VariableMetadataPersistent>()) {
VariableMetadataPersistent *variable_metadata =
static_cast<VariableMetadataPersistent *>(variable.m_metadata.get());
needs_init = llvm::cast<SwiftExpressionVariable>(
variable_metadata->m_persistent_variable_sp.get())
->m_swift_flags &
SwiftExpressionVariable::EVSNeedsInit;
Status error;
// When trying to materialize variables in the REPL, check whether
// this is possibly a zero-sized type and call the correct function which
// correctly handles zero-sized types. Unfortunately we currently have
// this check scattered in several places in the codebase, we should at
// some point centralize it.
if (repl && SwiftASTContext::IsPossibleZeroSizeType(variable.GetType())) {
auto &repl_mat = *llvm::cast<SwiftREPLMaterializer>(&materializer);
offset = repl_mat.AddREPLResultVariable(
variable.GetType(), variable.GetDecl(),
&user_expression.GetPersistentVariableDelegate(), error);
} else {
offset = materializer.AddPersistentVariable(
variable_metadata->m_persistent_variable_sp,
&user_expression.GetPersistentVariableDelegate(), error);
}
if (!error.Success()) {
diagnostic_manager.Printf(eDiagnosticSeverityError,
"couldn't add variable to struct: %s.\n",
error.AsCString());
return llvm::None;
}
if (log)
log->Printf(
"Added persistent variable %s with flags 0x%llx to "
"struct at offset %llu",
variable_metadata->m_persistent_variable_sp->GetName().AsCString(),
(unsigned long long)
variable_metadata->m_persistent_variable_sp->m_flags,
(unsigned long long)offset);
}
return SwiftExpressionParser::SILVariableInfo(variable.GetType(), offset,
needs_init);
}
namespace {
/// This error indicates that the error has already been diagnosed.
struct PropagatedError : public llvm::ErrorInfo<PropagatedError> {
static char ID;
void log(llvm::raw_ostream &OS) const override { OS << "Propagated"; }
std::error_code convertToErrorCode() const override {
return inconvertibleErrorCode();
}
};
/// This indicates an error in the SwiftASTContext.
struct SwiftASTContextError : public llvm::ErrorInfo<SwiftASTContextError> {
static char ID;
void log(llvm::raw_ostream &OS) const override { OS << "SwiftASTContext"; }
std::error_code convertToErrorCode() const override {
return inconvertibleErrorCode();
}
};
/// This indicates an error in the SwiftASTContext.
struct ModuleImportError : public llvm::ErrorInfo<ModuleImportError> {
static char ID;
std::string Message;
ModuleImportError(llvm::Twine Message) : Message(Message.str()) {}
void log(llvm::raw_ostream &OS) const override { OS << "ModuleImport"; }
std::error_code convertToErrorCode() const override {
return inconvertibleErrorCode();
}
};
char PropagatedError::ID = 0;
char SwiftASTContextError::ID = 0;
char ModuleImportError::ID = 0;
/// This holds the result of ParseAndImport.
struct ParsedExpression {
std::unique_ptr<SwiftASTManipulator> code_manipulator;
swift::ASTContext &ast_context;
swift::ModuleDecl &module;
LLDBNameLookup &external_lookup;
swift::SourceFile &source_file;
std::string main_filename;
unsigned buffer_id;
};
} // namespace
/// Attempt to parse an expression and import all the Swift modules
/// the expression and its context depend on.
static llvm::Expected<ParsedExpression>
ParseAndImport(SwiftASTContext *swift_ast_context, Expression &expr,
SwiftExpressionParser::SILVariableMap &variable_map,
unsigned &buffer_id, DiagnosticManager &diagnostic_manager,
SwiftExpressionParser &swift_expr_parser,
lldb::StackFrameWP &stack_frame_wp, SymbolContext &sc,
ExecutionContextScope &exe_scope,
const EvaluateExpressionOptions &options, bool repl,
bool playground) {
auto should_disable_objc_runtime = [&]() {
lldb::StackFrameSP this_frame_sp(stack_frame_wp.lock());
if (!this_frame_sp)
return false;
lldb::ProcessSP process_sp(this_frame_sp->CalculateProcess());
if (!process_sp)
return false;
return !process_sp->GetObjCLanguageRuntime();
};
swift::ASTContext *ast_context =
SetupASTContext(swift_ast_context, diagnostic_manager,
should_disable_objc_runtime, repl, playground);
if (!ast_context)
return make_error<SwiftASTContextError>();
// If we are using the playground, hand import the necessary modules.
// FIXME: We won't have to do this once the playground adds import statements
// for the things it needs itself.
if (playground) {
auto *persistent_state =
sc.target_sp->GetSwiftPersistentExpressionState(exe_scope);
persistent_state->AddHandLoadedModule(ConstString("Swift"));
}
std::string main_filename;
std::tie(buffer_id, main_filename) = CreateMainFile(
*swift_ast_context, repl ? "<REPL>" : "<EXPR>", expr.Text(), options);
char expr_name_buf[32];
snprintf(expr_name_buf, sizeof(expr_name_buf), "__lldb_expr_%u",
options.GetExpressionNumber());
auto module_id = ast_context->getIdentifier(expr_name_buf);
auto &module = *swift::ModuleDecl::create(module_id, *ast_context);
const auto implicit_import_kind =
swift::SourceFile::ImplicitModuleImportKind::Stdlib;
auto &invocation = swift_ast_context->GetCompilerInvocation();
invocation.getFrontendOptions().ModuleName = expr_name_buf;
invocation.getIRGenOptions().ModuleName = expr_name_buf;
swift::SourceFileKind source_file_kind = swift::SourceFileKind::Library;
if (playground || repl) {
source_file_kind = swift::SourceFileKind::Main;
}
swift::SourceFile *source_file = new (*ast_context) swift::SourceFile(
module, source_file_kind, buffer_id, implicit_import_kind,
/*Keep tokens*/ false);
module.addFile(*source_file);
bool done = false;
LLDBNameLookup *external_lookup;
if (options.GetPlaygroundTransformEnabled() || options.GetREPLEnabled()) {
external_lookup = new LLDBREPLNameLookup(*source_file, variable_map, sc,
exe_scope);
} else {
external_lookup = new LLDBExprNameLookup(*source_file, variable_map, sc,
exe_scope);
}
// FIXME: This call is here just so that the we keep the
// DebuggerClients alive as long as the Module we are not inserting
// them in.
swift_ast_context->AddDebuggerClient(external_lookup);
swift::PersistentParserState persistent_state(*ast_context);
while (!done) {
swift::parseIntoSourceFile(*source_file, buffer_id, &done, nullptr,
&persistent_state);
if (swift_ast_context->HasErrors())
return make_error<SwiftASTContextError>();
}
if (!done)
return make_error<llvm::StringError>(
"Parse did not consume the whole expression.",
inconvertibleErrorCode());
std::unique_ptr<SwiftASTManipulator> code_manipulator;
if (repl || !playground) {
code_manipulator =
llvm::make_unique<SwiftASTManipulator>(*source_file, repl);
if (!playground) {
code_manipulator->RewriteResult();
}
}
Status auto_import_error;
if (!PerformAutoImport(*swift_ast_context, sc, exe_scope, stack_frame_wp,
*source_file, false, auto_import_error))
return make_error<ModuleImportError>(llvm::Twine("in auto-import:\n") +
auto_import_error.AsCString());
// Swift Modules that rely on shared libraries (not frameworks)
// don't record the link information in the swiftmodule file, so we
// can't really make them work without outside information.
// However, in the REPL you can added -L & -l options to the initial
// compiler startup, and we should dlopen anything that's been
// stuffed on there and hope it will be useful later on.
if (repl) {
lldb::StackFrameSP this_frame_sp(stack_frame_wp.lock());
if (this_frame_sp) {
lldb::ProcessSP process_sp(this_frame_sp->CalculateProcess());
if (process_sp) {
Status error;
swift_ast_context->LoadExtraDylibs(*process_sp.get(), error);
}
}
}
if (!playground && !repl) {
lldb::StackFrameSP stack_frame_sp = stack_frame_wp.lock();
bool local_context_is_swift = true;
if (sc.block) {
Function *function = sc.block->CalculateSymbolContextFunction();
if (function && function->GetLanguage() != lldb::eLanguageTypeSwift)
local_context_is_swift = false;
}
llvm::SmallVector<SwiftASTManipulator::VariableInfo, 5> local_variables;
if (local_context_is_swift) {
AddRequiredAliases(sc.block, stack_frame_sp, *swift_ast_context,
*code_manipulator, expr.GetSwiftGenericInfo());
// Register all local variables so that lookups to them resolve.
CountLocals(sc, stack_frame_sp, *swift_ast_context, local_variables);
}
// Register all magic variables.
llvm::SmallVector<swift::Identifier, 2> special_names;
llvm::StringRef persistent_var_prefix;
if (!repl)
persistent_var_prefix = "$";
code_manipulator->FindSpecialNames(special_names, persistent_var_prefix);
ResolveSpecialNames(sc, exe_scope, *swift_ast_context, special_names,
local_variables);
code_manipulator->AddExternalVariables(local_variables);
stack_frame_sp.reset();
}
swift::performNameBinding(*source_file);
if (swift_ast_context->HasErrors())
return make_error<SwiftASTContextError>();
// Do the auto-importing after Name Binding, that's when the Imports for the
// source file are figured out.
{
std::lock_guard<std::recursive_mutex> global_context_locker(
IRExecutionUnit::GetLLVMGlobalContextMutex());
Status auto_import_error;
if (!PerformAutoImport(*swift_ast_context, sc, exe_scope, stack_frame_wp,
*source_file, true, auto_import_error)) {
return make_error<ModuleImportError>(llvm::Twine("in auto-import:\n") +
auto_import_error.AsCString());
}
}
// After the swift code manipulator performed AST transformations, verify
// that the AST we have in our hands is valid. This is a nop for release
// builds, but helps catching bug when assertions are turned on.
swift::verify(*source_file);
ParsedExpression result = {std::move(code_manipulator),
*ast_context,
module,
*external_lookup,
*source_file,
std::move(main_filename)};
return std::move(result);
}
unsigned SwiftExpressionParser::Parse(DiagnosticManager &diagnostic_manager,
uint32_t first_line, uint32_t last_line,
uint32_t line_offset) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
SwiftExpressionParser::SILVariableMap variable_map;
auto *swift_ast_ctx = m_swift_ast_context->get();
// Helper function to diagnose errors in m_swift_ast_context.
unsigned buffer_id = UINT32_MAX;
auto DiagnoseSwiftASTContextError = [&]() {
assert(swift_ast_ctx->HasErrors() && "error expected");
swift_ast_ctx->PrintDiagnostics(diagnostic_manager, buffer_id,
first_line, last_line, line_offset);
};
// In the case of playgrounds, we turn all rewriting functionality off.
const bool repl = m_options.GetREPLEnabled();
const bool playground = m_options.GetPlaygroundTransformEnabled();
if (!m_exe_scope)
return false;
// Parse the expression an import all nececssary swift modules.
auto parsed_expr =
ParseAndImport(m_swift_ast_context->get(), m_expr, variable_map,
buffer_id, diagnostic_manager, *this, m_stack_frame_wp,
m_sc, *m_exe_scope, m_options, repl, playground);
if (!parsed_expr) {
bool retry = false;
handleAllErrors(parsed_expr.takeError(),
[&](const ModuleImportError &MIE) {
if (swift_ast_ctx->GetClangImporter())
// Already on backup power.
diagnostic_manager.PutString(eDiagnosticSeverityError,
MIE.Message);
else
// Discard the shared scratch context and retry.
retry = true;
},
[&](const SwiftASTContextError &SACE) {
if (swift_ast_ctx->GetClangImporter())
DiagnoseSwiftASTContextError();
else
// Discard the shared scratch context and retry.
retry = true;
},
[&](const StringError &SE) {
diagnostic_manager.PutString(eDiagnosticSeverityError,
SE.getMessage());
},
[](const PropagatedError &P) {});
// Unrecoverable error?
if (!retry)
return 1;
// Signal that we want to retry the expression exactly once with
// a fresh SwiftASTContext initialized with the flags from the
// current lldb::Module / Swift dylib to avoid header search
// mismatches.
m_sc.target_sp->SetUseScratchTypesystemPerModule(true);
return 2;
}
// Not persistent because we're building source files one at a time.
swift::TopLevelContext top_level_context;
swift::OptionSet<swift::TypeCheckingFlags> type_checking_options;
swift::performTypeChecking(parsed_expr->source_file, top_level_context,
type_checking_options);
if (swift_ast_ctx->HasErrors()) {
DiagnoseSwiftASTContextError();
return 1;
}
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
parsed_expr->source_file.dump(ss);
ss.flush();
log->Printf("Source file after type checking:");
log->PutCString(s.c_str());
}
if (repl) {
parsed_expr->code_manipulator->MakeDeclarationsPublic();
}
Status error;
if (!playground) {
parsed_expr->code_manipulator->FixupResultAfterTypeChecking(error);
if (!error.Success()) {
diagnostic_manager.PutString(eDiagnosticSeverityError, error.AsCString());
return 1;
}
} else {
swift::performPlaygroundTransform(parsed_expr->source_file, true);
swift::typeCheckExternalDefinitions(parsed_expr->source_file);
}
// I think we now have to do the name binding and type checking again, but
// there should be only the result
// variable to bind up at this point.
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
parsed_expr->source_file.dump(ss);
ss.flush();
log->Printf("Source file after FixupResult:");
log->PutCString(s.c_str());
}
// Allow variables to be re-used from previous REPL statements.
if (m_sc.target_sp && (repl || !playground)) {
Status error;
SwiftASTContext *scratch_ast_context = m_swift_ast_context->get();
if (scratch_ast_context) {
auto *persistent_state =
m_sc.target_sp->GetSwiftPersistentExpressionState(*m_exe_scope);
llvm::SmallVector<size_t, 1> declaration_indexes;
parsed_expr->code_manipulator->FindVariableDeclarations(
declaration_indexes, repl);
for (size_t declaration_index : declaration_indexes) {
SwiftASTManipulator::VariableInfo &variable_info =
parsed_expr->code_manipulator->GetVariableInfo()[declaration_index];
CompilerType imported_type =
ImportType(*scratch_ast_context, variable_info.GetType());
if (imported_type) {
lldb::ExpressionVariableSP persistent_variable =
persistent_state->AddNewlyConstructedVariable(
new SwiftExpressionVariable(
m_sc.target_sp.get(),
ConstString(variable_info.GetName().str()), imported_type,
m_sc.target_sp->GetArchitecture().GetByteOrder(),
m_sc.target_sp->GetArchitecture().GetAddressByteSize()));
if (repl) {
persistent_variable->m_flags |= ExpressionVariable::EVKeepInTarget;
persistent_variable->m_flags |=
ExpressionVariable::EVIsProgramReference;
} else {
persistent_variable->m_flags |=
ExpressionVariable::EVNeedsAllocation;
persistent_variable->m_flags |= ExpressionVariable::EVKeepInTarget;
llvm::cast<SwiftExpressionVariable>(persistent_variable.get())
->m_swift_flags |= SwiftExpressionVariable::EVSNeedsInit;
}
swift::VarDecl *decl = variable_info.GetDecl();
if (decl) {
if (decl->isLet()) {
llvm::cast<SwiftExpressionVariable>(persistent_variable.get())
->SetIsModifiable(false);
}
if (!decl->hasStorage()) {
llvm::cast<SwiftExpressionVariable>(persistent_variable.get())
->SetIsComputed(true);
}
}
variable_info.m_metadata.reset(
new VariableMetadataPersistent(persistent_variable));
persistent_state->RegisterSwiftPersistentDecl(decl);
}
}
if (repl) {
llvm::SmallVector<swift::ValueDecl *, 1> non_variables;
parsed_expr->code_manipulator->FindNonVariableDeclarations(
non_variables);
for (swift::ValueDecl *decl : non_variables) {
persistent_state->RegisterSwiftPersistentDecl(decl);
}
}
}
}
if (!playground && !repl) {
parsed_expr->code_manipulator->FixCaptures();
// This currently crashes with Assertion failed: (BufferID != -1),
// function findBufferContainingLoc, file
// llvm/tools/swift/include/swift/Basic/SourceManager.h, line 92.
// if (log)
// {
// std::string s;
// llvm::raw_string_ostream ss(s);
// parsed_expr->source_file.dump(ss);
// ss.flush();
//
// log->Printf("Source file after capture fixing:");
// log->PutCString(s.c_str());
// }
if (log) {
log->Printf("Variables:");
for (const SwiftASTManipulatorBase::VariableInfo &variable :
parsed_expr->code_manipulator->GetVariableInfo()) {
StreamString ss;
variable.Print(ss);
log->Printf(" %s", ss.GetData());
}
}
}
if (repl || !playground)
if (auto *materializer = m_expr.GetMaterializer())
for (auto &variable : parsed_expr->code_manipulator->GetVariableInfo()) {
auto &swift_expr = *static_cast<SwiftUserExpression *>(&m_expr);
auto var_info = MaterializeVariable(
variable, swift_expr, *materializer, *parsed_expr->code_manipulator,
m_stack_frame_wp, diagnostic_manager, log, repl);
if (!var_info)
return 1;
const char *name = ConstString(variable.GetName().get()).GetCString();
variable_map[name] = *var_info;
}
// SWIFT_ENABLE_TENSORFLOW
// Set optimization mode to -O for REPL/Playgrounds.
auto &options = swift_ast_ctx->GetSILOptions();
options.OptMode = swift::OptimizationMode::ForSpeed;
std::unique_ptr<swift::SILModule> sil_module(swift::performSILGeneration(
parsed_expr->source_file, options));
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
const bool verbose = false;
sil_module->print(ss, verbose, &parsed_expr->module);
ss.flush();
log->Printf("SIL module before linking:");
log->PutCString(s.c_str());
}
if (swift_ast_ctx->HasErrors()) {
DiagnoseSwiftASTContextError();
return 1;
}
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
const bool verbose = false;
sil_module->print(ss, verbose, &parsed_expr->module);
ss.flush();
log->Printf("Generated SIL module:");
log->PutCString(s.c_str());
}
// SWIFT_ENABLE_TENSORFLOW
// Serialize the file if modules directory is set.
// Note that the serialization should be done immediately after
// SILGen and before any other passes run. This is important
// because of the following reasons:
// - passes like differentation need to see the code before optimizations.
// - Some passes may create new functions, but only the functions defined in
// the lldb repl line should be serialized.
if (swift_ast_ctx->UseSerialization()) {
auto expr_module_dir = swift_ast_ctx->GetReplExprModulesDir();
assert(expr_module_dir != nullptr);
llvm::SmallString<256> filename(expr_module_dir);
std::string module_name;
GetNameFromModule(&parsed_expr->module, module_name);
llvm::sys::path::append(filename, module_name);
llvm::sys::path::replace_extension(filename, ".swiftmodule");
// TODO: Check language is swift
swift::SerializationOptions serializationOpts;
serializationOpts.OutputPath = filename.c_str();
serializationOpts.SerializeAllSIL = true;
serializationOpts.IsSIB = true;
if (log) {
log->Printf("Serializing module %s to %s\n", module_name.c_str(),
serializationOpts.OutputPath);
}
swift::serialize(sil_module->getSwiftModule(), serializationOpts,
sil_module.get());
}
runSILDiagnosticPasses(*sil_module);
// SWIFT_ENABLE_TENSORFLOW
sil_module->setSerializeSILAction([] {});
if (!swift_ast_ctx->UseSerialization()) {
// FIXME: When partitioning joins the mandatory pass pipeline, we should be able to
// stop running the optimization passes and drop the explicit call of the partitioning
// pass.
runSILOptPreparePasses(*sil_module);
runSILOptimizationPasses(*sil_module);
}
// FIXME: These passes should be moved to the mandatory pass pipeline that
// runs at -O0. We need a proper deabstraction pass to do that though.
runSILTFPartitionPass(*sil_module);
// SWIFT_ENABLE_TENSORFLOW
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
const bool verbose = false;
sil_module->print(ss, verbose, &parsed_expr->module);
ss.flush();
log->Printf("SIL module after diagnostic passes:");
log->PutCString(s.c_str());
}
if (swift_ast_ctx->HasErrors()) {
DiagnoseSwiftASTContextError();
return 1;
}
{
std::lock_guard<std::recursive_mutex> global_context_locker(
IRExecutionUnit::GetLLVMGlobalContextMutex());
m_module = swift::performIRGeneration(
swift_ast_ctx->GetIRGenOptions(), &parsed_expr->module,
std::move(sil_module), "lldb_module",
swift::PrimarySpecificPaths("", parsed_expr->main_filename),
SwiftASTContext::GetGlobalLLVMContext(), llvm::ArrayRef<std::string>());
}
if (swift_ast_ctx->HasErrors()) {
DiagnoseSwiftASTContextError();
return 1;
}
if (!m_module) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"Couldn't IRGen expression, no additional error");
return 1;
}
if (log) {
std::string s;
llvm::raw_string_ostream ss(s);
m_module->print(ss, NULL);
ss.flush();
log->Printf("Generated IR module:");
log->PutCString(s.c_str());
}
{
std::lock_guard<std::recursive_mutex> global_context_locker(
IRExecutionUnit::GetLLVMGlobalContextMutex());
LLVMVerifyModule((LLVMOpaqueModule *)m_module.get(), LLVMReturnStatusAction,
nullptr);
}
if (swift_ast_ctx->HasErrors())
return 1;
// The Parse succeeded! Now put this module into the context's
// list of loaded modules, and copy the Decls that were globalized
// as part of the parse from the staging area in the external
// lookup object into the SwiftPersistentExpressionState.
// SWIFT_ENABLE_TENSORFLOW
swift::ModuleDecl *module = nullptr;
if (!swift_ast_ctx->UseSerialization()) {
// Just reuse the module if no serialization is requested.
module = &parsed_expr->module;
} else {
// Reload the serialized module so that we can look
// into SIL functions in subsequent cells if needed (e.g., differentiation).
if (log) {
log->Printf("Reloading the serialized module.\n");
}
lldb::StackFrameSP this_frame_sp(m_stack_frame_wp.lock());
if (this_frame_sp) {
lldb::ProcessSP process_sp(this_frame_sp->CalculateProcess());
Status error;
std::string module_name = parsed_expr->module.getName().str();
if (process_sp && !module_name.empty()) {
ConstString module_const_str(module_name);
module = swift_ast_ctx->FindAndLoadModule(module_const_str,
*process_sp.get(), error);
}
}
if (!module || swift_ast_ctx->HasErrors()) {
diagnostic_manager.PutString(eDiagnosticSeverityError,
"Couldn't reload the serialized module file.");
return 1;
}
// Update persistent non-variable decls to the ones in the serialized module.
// Otherwise, we will have deserialization errors.
auto *persistent_state =
m_sc.target_sp->GetSwiftPersistentExpressionState(*m_exe_scope);
llvm::SmallVector<swift::Decl*, 8> decls;
module->getTopLevelDecls(decls);
for (swift::Decl *decl : decls) {
if (swift::ValueDecl *value_decl = llvm::dyn_cast<swift::ValueDecl>(decl)) {
if (!llvm::isa<swift::VarDecl>(value_decl) && value_decl->hasName()) {
persistent_state->RegisterSwiftPersistentDecl(value_decl);
}
}
}
}
parsed_expr->ast_context.LoadedModules.insert({module->getName(), module});
swift_ast_ctx->CacheModule(module);
if (m_sc.target_sp) {
auto *persistent_state =
m_sc.target_sp->GetSwiftPersistentExpressionState(*m_exe_scope);
persistent_state->CopyInSwiftPersistentDecls(
parsed_expr->external_lookup.GetStagedDecls());
}
return 0;
}
static bool FindFunctionInModule(ConstString &mangled_name,
llvm::Module *module, const char *orig_name,
bool exact) {
swift::Demangle::Context demangle_ctx;
for (llvm::Module::iterator fi = module->getFunctionList().begin(),
fe = module->getFunctionList().end();
fi != fe; ++fi) {
if (exact) {
if (!fi->getName().str().compare(orig_name)) {
mangled_name.SetCString(fi->getName().str().c_str());
return true;
}
} else {
if (fi->getName().str().find(orig_name) != std::string::npos) {
mangled_name.SetCString(fi->getName().str().c_str());
return true;
}
// The new demangling is cannier about compression, so the name may
// not be in the mangled name plain. Let's demangle it and see if we
// can find it in the demangled nodes.
demangle_ctx.clear();
swift::Demangle::NodePointer node_ptr =
demangle_ctx.demangleSymbolAsNode(fi->getName());
if (node_ptr) {
if (node_ptr->getKind() != swift::Demangle::Node::Kind::Global)
continue;
if (node_ptr->getNumChildren() != 1)
continue;
node_ptr = node_ptr->getFirstChild();
if (node_ptr->getKind() != swift::Demangle::Node::Kind::Function)
continue;
size_t num_children = node_ptr->getNumChildren();
for (size_t i = 0; i < num_children; i++) {
swift::Demangle::NodePointer child_ptr = node_ptr->getChild(i);
if (child_ptr->getKind() == swift::Demangle::Node::Kind::Identifier) {
if (!child_ptr->hasText())
continue;
if (child_ptr->getText().contains(orig_name)) {
mangled_name.SetCString(fi->getName().str().c_str());
return true;
}
}
}
}
}
}
return false;
}
Status SwiftExpressionParser::PrepareForExecution(
lldb::addr_t &func_addr, lldb::addr_t &func_end,
lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
bool &can_interpret, ExecutionPolicy execution_policy) {
Status err;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (!m_module) {
err.SetErrorString("Can't prepare a NULL module for execution");
return err;
}
const char *orig_name = nullptr;
bool exact = false;
if (m_options.GetPlaygroundTransformEnabled() || m_options.GetREPLEnabled()) {
orig_name = "main";
exact = true;
} else {
orig_name = "$__lldb_expr";
}
ConstString function_name;
if (!FindFunctionInModule(function_name, m_module.get(), orig_name, exact)) {
err.SetErrorToGenericError();
err.SetErrorStringWithFormat("Couldn't find %s() in the module", orig_name);
return err;
} else {
if (log)
log->Printf("Found function %s for %s", function_name.AsCString(),
"$__lldb_expr");
}
// Retrieve an appropriate symbol context.
SymbolContext sc;
if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
} else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
sc.target_sp = target_sp;
}
std::vector<std::string> features;
std::unique_ptr<llvm::LLVMContext> llvm_context_up;
m_execution_unit_sp.reset(
new IRExecutionUnit(llvm_context_up,
m_module, // handed off here
function_name, exe_ctx.GetTargetSP(), sc, features));
// TODO figure out some way to work ClangExpressionDeclMap into this or do the
// equivalent
// for Swift
m_execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
execution_unit_sp = m_execution_unit_sp;
m_execution_unit_sp.reset();
return err;
}
bool SwiftExpressionParser::RewriteExpression(
DiagnosticManager &diagnostic_manager) {
// There isn't a Swift equivalent to clang::Rewriter, so we'll just use
// that...
auto *swift_ast_ctx = m_swift_ast_context->get();
if (!swift_ast_ctx)
return false;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
swift::SourceManager &source_manager =
swift_ast_ctx->GetSourceManager();
const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
size_t num_diags = diagnostics.size();
if (num_diags == 0)
return false;
clang::RewriteBuffer rewrite_buf;
llvm::StringRef text_ref(m_expr.Text());
rewrite_buf.Initialize(text_ref);
for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
const SwiftDiagnostic *diagnostic = llvm::dyn_cast<SwiftDiagnostic>(diag);
if (!(diagnostic && diagnostic->HasFixIts()))
continue;
const SwiftDiagnostic::FixItList &fixits = diagnostic->FixIts();
std::vector<swift::CharSourceRange> source_ranges;
for (const swift::DiagnosticInfo::FixIt &fixit : fixits) {
const swift::CharSourceRange &range = fixit.getRange();
swift::SourceLoc start_loc = range.getStart();
if (!start_loc.isValid()) {
// getLocOffsetInBuffer will assert if you pass it an invalid location,
// so we have to check that first.
if (log)
log->Printf(
"SwiftExpressionParser::RewriteExpression: ignoring fixit since "
"it contains an invalid source location: %s.",
range.str().str().c_str());
return false;
}
// ReplaceText can't handle replacing the same source range more than
// once, so we have to check that
// before we proceed:
if (std::find(source_ranges.begin(), source_ranges.end(), range) !=
source_ranges.end()) {
if (log)
log->Printf(
"SwiftExpressionParser::RewriteExpression: ignoring fix-it since "
"source range appears twice: %s.\n",
range.str().str().c_str());
return false;
} else
source_ranges.push_back(range);
// ReplaceText will either assert or crash if the start_loc isn't inside
// the buffer it is said to
// reside in. That shouldn't happen, but it doesn't hurt to check before
// we call ReplaceText.
auto *Buffer = source_manager.getLLVMSourceMgr().getMemoryBuffer(
diagnostic->GetBufferID());
if (!(start_loc.getOpaquePointerValue() >= Buffer->getBuffer().begin() &&
start_loc.getOpaquePointerValue() <= Buffer->getBuffer().end())) {
if (log)
log->Printf(
"SwiftExpressionParser::RewriteExpression: ignoring fixit since "
"it contains a source location not in the specified buffer: %s.",
range.str().str().c_str());
}
unsigned offset = source_manager.getLocOffsetInBuffer(
range.getStart(), diagnostic->GetBufferID());
rewrite_buf.ReplaceText(offset, range.getByteLength(), fixit.getText());
}
}
std::string fixed_expression;
llvm::raw_string_ostream out_stream(fixed_expression);
rewrite_buf.write(out_stream);
out_stream.flush();
diagnostic_manager.SetFixedExpression(fixed_expression);
return true;
}
| 1 | 18,162 | Does it work to run all the sil diagnostic passes before we serialize? That would be more consistent with what the normal compiler does in `FrontendTool.cpp : performCompileStepsPostSILGen()` | apple-swift-lldb | cpp |
@@ -4,6 +4,7 @@ Given '"$teacher_name" is teaching the section from "$section_start" to "$sectio
section = Section.find_by_starts_on_and_ends_on!(start_date, end_date)
teacher = Teacher.find_by_name!(teacher_name)
create(:section_teacher, section: section, teacher: teacher)
+ p section.teachers
end
Given 'I create the following section for "$course_name":' do |course_name, section_data| | 1 | Given '"$teacher_name" is teaching the section from "$section_start" to "$section_end"' do |teacher_name, section_start, section_end|
start_date = Date.parse(section_start)
end_date = Date.parse(section_end)
section = Section.find_by_starts_on_and_ends_on!(start_date, end_date)
teacher = Teacher.find_by_name!(teacher_name)
create(:section_teacher, section: section, teacher: teacher)
end
Given 'I create the following section for "$course_name":' do |course_name, section_data|
steps %{
Given a teacher exists with a name of "Albert Einstein"
When I go to the admin page
And I follow "New Section" within the course "#{course_name}"
When I select the start date of "June 14, 2010"
}
step "I fill in the following:", section_data
steps %{
And I select the teacher "Albert Einstein"
And I fill in the Boston address
And I press "Save Section"
Then I see the successful section creation notice
}
end
Given /^I am signed up as student of "([^"]*)" on ([0-9-]+)$/ do |course_name, date|
course = create(:course, name: course_name)
section = create(:section, course: course, starts_on: date)
@registration = create(:paid_registration, section: section)
end
When /^it is a week before ([0-9-]+)$/ do |date|
Timecop.freeze(DateTime.parse(date) - 1.week)
end
| 1 | 6,405 | You left in a puts. | thoughtbot-upcase | rb |
@@ -59,6 +59,11 @@ public abstract class CachingCollector extends FilterCollector {
@Override
public final float score() { return score; }
+ @Override
+ public float smoothingScore(int docId) throws IOException {
+ return 0;
+ }
+
@Override
public int docID() {
return doc; | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.search;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.util.ArrayUtil;
/**
* Caches all docs, and optionally also scores, coming from
* a search, and is then able to replay them to another
* collector. You specify the max RAM this class may use.
* Once the collection is done, call {@link #isCached}. If
* this returns true, you can use {@link #replay(Collector)}
* against a new collector. If it returns false, this means
* too much RAM was required and you must instead re-run the
* original search.
*
* <p><b>NOTE</b>: this class consumes 4 (or 8 bytes, if
* scoring is cached) per collected document. If the result
* set is large this can easily be a very substantial amount
* of RAM!
*
* <p>See the Lucene <code>modules/grouping</code> module for more
* details including a full code example.</p>
*
* @lucene.experimental
*/
public abstract class CachingCollector extends FilterCollector {
private static final int INITIAL_ARRAY_SIZE = 128;
private static final class CachedScorable extends Scorable {
// NOTE: these members are package-private b/c that way accessing them from
// the outer class does not incur access check by the JVM. The same
// situation would be if they were defined in the outer class as private
// members.
int doc;
float score;
@Override
public final float score() { return score; }
@Override
public int docID() {
return doc;
}
}
private static class NoScoreCachingCollector extends CachingCollector {
List<LeafReaderContext> contexts;
List<int[]> docs;
int maxDocsToCache;
NoScoreCachingLeafCollector lastCollector;
NoScoreCachingCollector(Collector in, int maxDocsToCache) {
super(in);
this.maxDocsToCache = maxDocsToCache;
contexts = new ArrayList<>();
docs = new ArrayList<>();
}
protected NoScoreCachingLeafCollector wrap(LeafCollector in, int maxDocsToCache) {
return new NoScoreCachingLeafCollector(in, maxDocsToCache);
}
// note: do *not* override needScore to say false. Just because we aren't caching the score doesn't mean the
// wrapped collector doesn't need it to do its job.
public LeafCollector getLeafCollector(LeafReaderContext context) throws IOException {
postCollection();
final LeafCollector in = this.in.getLeafCollector(context);
if (contexts != null) {
contexts.add(context);
}
if (maxDocsToCache >= 0) {
return lastCollector = wrap(in, maxDocsToCache);
} else {
return in;
}
}
protected void invalidate() {
maxDocsToCache = -1;
contexts = null;
this.docs = null;
}
protected void postCollect(NoScoreCachingLeafCollector collector) {
final int[] docs = collector.cachedDocs();
maxDocsToCache -= docs.length;
this.docs.add(docs);
}
private void postCollection() {
if (lastCollector != null) {
if (!lastCollector.hasCache()) {
invalidate();
} else {
postCollect(lastCollector);
}
lastCollector = null;
}
}
protected void collect(LeafCollector collector, int i) throws IOException {
final int[] docs = this.docs.get(i);
for (int doc : docs) {
collector.collect(doc);
}
}
public void replay(Collector other) throws IOException {
postCollection();
if (!isCached()) {
throw new IllegalStateException("cannot replay: cache was cleared because too much RAM was required");
}
assert docs.size() == contexts.size();
for (int i = 0; i < contexts.size(); ++i) {
final LeafReaderContext context = contexts.get(i);
final LeafCollector collector = other.getLeafCollector(context);
collect(collector, i);
}
}
}
private static class ScoreCachingCollector extends NoScoreCachingCollector {
List<float[]> scores;
ScoreCachingCollector(Collector in, int maxDocsToCache) {
super(in, maxDocsToCache);
scores = new ArrayList<>();
}
protected NoScoreCachingLeafCollector wrap(LeafCollector in, int maxDocsToCache) {
return new ScoreCachingLeafCollector(in, maxDocsToCache);
}
@Override
protected void postCollect(NoScoreCachingLeafCollector collector) {
final ScoreCachingLeafCollector coll = (ScoreCachingLeafCollector) collector;
super.postCollect(coll);
scores.add(coll.cachedScores());
}
/** Ensure the scores are collected so they can be replayed, even if the wrapped collector doesn't need them. */
@Override
public ScoreMode scoreMode() {
return ScoreMode.COMPLETE;
}
@Override
protected void collect(LeafCollector collector, int i) throws IOException {
final int[] docs = this.docs.get(i);
final float[] scores = this.scores.get(i);
assert docs.length == scores.length;
final CachedScorable scorer = new CachedScorable();
collector.setScorer(scorer);
for (int j = 0; j < docs.length; ++j) {
scorer.doc = docs[j];
scorer.score = scores[j];
collector.collect(scorer.doc);
}
}
}
private class NoScoreCachingLeafCollector extends FilterLeafCollector {
final int maxDocsToCache;
int[] docs;
int docCount;
NoScoreCachingLeafCollector(LeafCollector in, int maxDocsToCache) {
super(in);
this.maxDocsToCache = maxDocsToCache;
docs = new int[Math.min(maxDocsToCache, INITIAL_ARRAY_SIZE)];
docCount = 0;
}
protected void grow(int newLen) {
docs = ArrayUtil.growExact(docs, newLen);
}
protected void invalidate() {
docs = null;
docCount = -1;
cached = false;
}
protected void buffer(int doc) throws IOException {
docs[docCount] = doc;
}
@Override
public void collect(int doc) throws IOException {
if (docs != null) {
if (docCount >= docs.length) {
if (docCount >= maxDocsToCache) {
invalidate();
} else {
final int newLen = Math.min(ArrayUtil.oversize(docCount + 1, Integer.BYTES), maxDocsToCache);
grow(newLen);
}
}
if (docs != null) {
buffer(doc);
++docCount;
}
}
super.collect(doc);
}
boolean hasCache() {
return docs != null;
}
int[] cachedDocs() {
return docs == null ? null : ArrayUtil.copyOfSubArray(docs, 0, docCount);
}
}
private class ScoreCachingLeafCollector extends NoScoreCachingLeafCollector {
Scorable scorer;
float[] scores;
ScoreCachingLeafCollector(LeafCollector in, int maxDocsToCache) {
super(in, maxDocsToCache);
scores = new float[docs.length];
}
@Override
public void setScorer(Scorable scorer) throws IOException {
this.scorer = scorer;
super.setScorer(scorer);
}
@Override
protected void grow(int newLen) {
super.grow(newLen);
scores = ArrayUtil.growExact(scores, newLen);
}
@Override
protected void invalidate() {
super.invalidate();
scores = null;
}
@Override
protected void buffer(int doc) throws IOException {
super.buffer(doc);
scores[docCount] = scorer.score();
}
float[] cachedScores() {
return docs == null ? null : ArrayUtil.copyOfSubArray(scores, 0, docCount);
}
}
/**
* Creates a {@link CachingCollector} which does not wrap another collector.
* The cached documents and scores can later be {@link #replay(Collector)
* replayed}.
*/
public static CachingCollector create(boolean cacheScores, double maxRAMMB) {
Collector other = new SimpleCollector() {
@Override
public void collect(int doc) {}
@Override
public ScoreMode scoreMode() {
return ScoreMode.COMPLETE;
}
};
return create(other, cacheScores, maxRAMMB);
}
/**
* Create a new {@link CachingCollector} that wraps the given collector and
* caches documents and scores up to the specified RAM threshold.
*
* @param other
* the Collector to wrap and delegate calls to.
* @param cacheScores
* whether to cache scores in addition to document IDs. Note that
* this increases the RAM consumed per doc
* @param maxRAMMB
* the maximum RAM in MB to consume for caching the documents and
* scores. If the collector exceeds the threshold, no documents and
* scores are cached.
*/
public static CachingCollector create(Collector other, boolean cacheScores, double maxRAMMB) {
int bytesPerDoc = Integer.BYTES;
if (cacheScores) {
bytesPerDoc += Float.BYTES;
}
final int maxDocsToCache = (int) ((maxRAMMB * 1024 * 1024) / bytesPerDoc);
return create(other, cacheScores, maxDocsToCache);
}
/**
* Create a new {@link CachingCollector} that wraps the given collector and
* caches documents and scores up to the specified max docs threshold.
*
* @param other
* the Collector to wrap and delegate calls to.
* @param cacheScores
* whether to cache scores in addition to document IDs. Note that
* this increases the RAM consumed per doc
* @param maxDocsToCache
* the maximum number of documents for caching the documents and
* possible the scores. If the collector exceeds the threshold,
* no documents and scores are cached.
*/
public static CachingCollector create(Collector other, boolean cacheScores, int maxDocsToCache) {
return cacheScores ? new ScoreCachingCollector(other, maxDocsToCache) : new NoScoreCachingCollector(other, maxDocsToCache);
}
private boolean cached;
private CachingCollector(Collector in) {
super(in);
cached = true;
}
/**
* Return true is this collector is able to replay collection.
*/
public final boolean isCached() {
return cached;
}
/**
* Replays the cached doc IDs (and scores) to the given Collector. If this
* instance does not cache scores, then Scorer is not set on
* {@code other.setScorer} as well as scores are not replayed.
*
* @throws IllegalStateException
* if this collector is not cached (i.e., if the RAM limits were too
* low for the number of documents + scores to cache).
* @throws IllegalArgumentException
* if the given Collect's does not support out-of-order collection,
* while the collector passed to the ctor does.
*/
public abstract void replay(Collector other) throws IOException;
}
| 1 | 38,613 | Hmm, should we also cache the `smoothingScore` for this hit? Or, if we will keep it at returning `0`, couldn't we remove this impl and inherit the default from `Scorable`? | apache-lucene-solr | java |
@@ -51,7 +51,7 @@ module.exports = function (grunt, options) {
baseTasks['release'] = ['clean', 'ngtemplates', 'build', 'copy:less_dist', 'cut-release', 'gh-pages:ui-grid-site', 'update-bower-json', 'gh-pages:bower', 'npm-publish'];
}
else {
- baseTasks['release'] = ['clean', 'ngtemplates', 'build', 'copy:less_dist', 'cut-release', 'gh-pages:ui-grid-site'];
+ baseTasks['release'] = ['clean', 'ngtemplates', 'build', 'copy:less_dist', 'cut-release'];
}
return baseTasks; | 1 |
module.exports = function (grunt, options) {
var baseTasks = {
'install': ['shell:bower-install', 'shell:protractor-install', 'shell:hooks-install'],
// register before and after test tasks so we don't have to change cli
// options on the CI server
'before-test': ['clean', 'newer:jshint', 'newer:jscs', 'ngtemplates', 'less', 'copy:font_dist'], // Have to run less so CSS files are present
'after-test': ['build'],
'default': ['before-test', 'test:single', 'after-test'],
// Build with no testing
'build': ['ngtemplates', 'concat', 'uglify', 'less', 'ngdocs', 'copy:font_dist', 'copy:site', 'copy:less_customizer',],
// Auto-test tasks for development
'autotest:unit': ['karmangular:start'],
'autotest:e2e': ['shell:protractor-start'],
// Testing tasks
'test': ['before-test', 'test:single'],
'test:ci': ['before-test', 'serialsauce'],
'test:docs': ['connect:testserver', 'protractor:docs'],
'test:e2e': ['connect:testserver', 'protractor:singlerun'],
'test:ci-e2e': ['clean', 'build', 'connect:testserver', 'protractor:ci']
};
baseTasks['dev'] = ['before-test', 'after-test', 'connect', 'autotest:unit', 'autotest:e2e', 'watch'];
if (grunt.option('e2e') === false || grunt.option('fast')) {
grunt.log.writeln("Skipping e2e testing...");
baseTasks['dev'].splice(baseTasks['dev'].indexOf('autotest:e2e'), 1);
}
if (grunt.option('unit') === false) {
grunt.log.writeln("Skipping unit testing...");
baseTasks['dev'].splice(baseTasks['dev'].indexOf('autotest:unit'), 1);
}
if (process.env.TRAVIS){
baseTasks['test:single'] = ['karma:travis'];
}
else {
baseTasks['test:single'] = ['karmangular'];
}
var util = require('../lib/grunt/utils.js');
var semver = require('semver');
var currentTag = semver.clean( util.getCurrentTag() );
if (currentTag) {
baseTasks['release'] = ['clean', 'ngtemplates', 'build', 'copy:less_dist', 'cut-release', 'gh-pages:ui-grid-site', 'update-bower-json', 'gh-pages:bower', 'npm-publish'];
}
else {
baseTasks['release'] = ['clean', 'ngtemplates', 'build', 'copy:less_dist', 'cut-release', 'gh-pages:ui-grid-site'];
}
return baseTasks;
};
| 1 | 11,764 | I removed that from here because I am hoping that will stop the random unwanted updates to the website with unstable versions. | angular-ui-ui-grid | js |
@@ -11,7 +11,9 @@ import (
// State is the status of a process.
type State rune
-const ( // Only values for Linux 3.14 and later are listed here
+// Process state values.
+// Only values for Linux 3.14 and later are listed here.
+const (
Dead State = 'X'
DiskSleep State = 'D'
Running State = 'R' | 1 | package system
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
// State is the status of a process.
type State rune
const ( // Only values for Linux 3.14 and later are listed here
Dead State = 'X'
DiskSleep State = 'D'
Running State = 'R'
Sleeping State = 'S'
Stopped State = 'T'
TracingStop State = 't'
Zombie State = 'Z'
Parked State = 'P'
Idle State = 'I'
)
// String forms of the state from proc(5)'s documentation for
// /proc/[pid]/status' "State" field.
func (s State) String() string {
switch s {
case Dead:
return "dead"
case DiskSleep:
return "disk sleep"
case Running:
return "running"
case Sleeping:
return "sleeping"
case Stopped:
return "stopped"
case TracingStop:
return "tracing stop"
case Zombie:
return "zombie"
case Parked:
return "parked"
case Idle:
return "idle" // kernel thread
default:
return fmt.Sprintf("unknown (%c)", s)
}
}
// Stat_t represents the information from /proc/[pid]/stat, as
// described in proc(5) with names based on the /proc/[pid]/status
// fields.
type Stat_t struct {
// Name is the command run by the process.
Name string
// State is the state of the process.
State State
// StartTime is the number of clock ticks after system boot (since
// Linux 2.6).
StartTime uint64
}
// Stat returns a Stat_t instance for the specified process.
func Stat(pid int) (stat Stat_t, err error) {
bytes, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat"))
if err != nil {
return stat, err
}
return parseStat(string(bytes))
}
func parseStat(data string) (stat Stat_t, err error) {
// Example:
// 89653 (gunicorn: maste) S 89630 89653 89653 0 -1 4194560 29689 28896 0 3 146 32 76 19 20 0 1 0 2971844 52965376 3920 18446744073709551615 1 1 0 0 0 0 0 16781312 137447943 0 0 0 17 1 0 0 0 0 0 0 0 0 0 0 0 0 0
// The fields are space-separated, see full description in proc(5).
//
// We are only interested in:
// * field 2: process name. It is the only field enclosed into
// parenthesis, as it can contain spaces (and parenthesis) inside.
// * field 3: process state, a single character (%c)
// * field 22: process start time, a long unsigned integer (%llu).
// 1. Look for the first '(' and the last ')' first, what's in between is Name.
// We expect at least 20 fields and a space after the last one.
const minAfterName = 20*2 + 1 // the min field is '0 '.
first := strings.IndexByte(data, '(')
if first < 0 || first+minAfterName >= len(data) {
return stat, fmt.Errorf("invalid stat data (no comm or too short): %q", data)
}
last := strings.LastIndexByte(data, ')')
if last <= first || last+minAfterName >= len(data) {
return stat, fmt.Errorf("invalid stat data (no comm or too short): %q", data)
}
stat.Name = data[first+1 : last]
// 2. Remove fields 1 and 2 and a space after. State is right after.
data = data[last+2:]
stat.State = State(data[0])
// 3. StartTime is field 22, data is at field 3 now, so we need to skip 19 spaces.
skipSpaces := 22 - 3
for first = 0; skipSpaces > 0 && first < len(data); first++ {
if data[first] == ' ' {
skipSpaces--
}
}
// Now first points to StartTime; look for space right after.
i := strings.IndexByte(data[first:], ' ')
if i < 0 {
return stat, fmt.Errorf("invalid stat data (too short): %q", data)
}
stat.StartTime, err = strconv.ParseUint(data[first:first+i], 10, 64)
if err != nil {
return stat, fmt.Errorf("invalid stat data (bad start time): %w", err)
}
return stat, nil
}
| 1 | 23,686 | Nit: missing period. | opencontainers-runc | go |
@@ -1,10 +1,13 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX - License - Identifier: Apache - 2.0
+# Purpose
+# This code example demonstrates how deny uploads of unencrypted objects to an Amazon Simple Storage Solution (Amazon S3) bucket.
+
+# snippet-start:[s3.ruby.s3_add_bucket_ssekms_encryption_policy]
+
require 'aws-sdk-s3'
-# Denies uploads of unencrypted objects to an Amazon S3 bucket.
-#
# Prerequisites:
#
# - The Amazon S3 bucket to deny uploading unencrypted objects. | 1 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX - License - Identifier: Apache - 2.0
require 'aws-sdk-s3'
# Denies uploads of unencrypted objects to an Amazon S3 bucket.
#
# Prerequisites:
#
# - The Amazon S3 bucket to deny uploading unencrypted objects.
#
# @param s3_client [Aws::S3::Client] An initialized Amazon S3 client.
# @param bucket_name [String] The bucket's name.
# @return [Boolean] true if a policy was added to the bucket to
# deny uploading unencrypted objects; otherwise, false.
# @example
# if deny_uploads_without_encryption?(
# Aws::S3::Client.new(region: 'us-east-1'),
# 'doc-example-bucket'
# )
# puts 'Policy added.'
# else
# puts 'Policy not added.'
# end
def deny_uploads_without_encryption?(s3_client, bucket_name)
policy = {
'Version': '2012-10-17',
'Id': 'PutObjPolicy',
'Statement': [
{
'Sid': 'DenyUnEncryptedObjectUploads',
'Effect': 'Deny',
'Principal': '*',
'Action': 's3:PutObject',
'Resource': 'arn:aws:s3:::' + bucket_name + '/*',
'Condition': {
'StringNotEquals': {
's3:x-amz-server-side-encryption': [
'AES256',
'aws:kms'
]
}
}
},
{
'Sid': 'DenyUnEncryptedObjectUploads',
'Effect': 'Deny',
'Principal': '*',
'Action': 's3:PutObject',
'Resource': 'arn:aws:s3:::' + bucket_name + '/*',
'Condition': {
'Null': {
's3:x-amz-server-side-encryption': 'true'
}
}
}
]
}.to_json
s3_client.put_bucket_policy(
bucket: bucket_name,
policy: policy
)
return true
rescue StandardError => e
puts "Error adding policy: #{e.message}"
return false
end
# Full example call:
def run_me
if deny_uploads_without_encryption?(
Aws::S3::Client.new(region: 'us-east-1'),
'doc-example-bucket'
)
puts 'Policy added.'
else
puts 'Policy not added.'
end
end
run_me if $PROGRAM_NAME == __FILE__
| 1 | 20,531 | how **to** deny Simple Storage **Service** | awsdocs-aws-doc-sdk-examples | rb |
@@ -5,7 +5,7 @@ setResolver(resolver);
/* jshint ignore:start */
mocha.setup({
- timeout: 15000,
+ timeout: 25000,
slow: 500
});
/* jshint ignore:end */ | 1 | import resolver from './helpers/resolver';
import {setResolver} from 'ember-mocha';
setResolver(resolver);
/* jshint ignore:start */
mocha.setup({
timeout: 15000,
slow: 500
});
/* jshint ignore:end */
| 1 | 7,914 | Were you having trouble with timeouts in general acceptance tests or only the editor test? It's possible to set timeouts on a per-test basis by using `this.timeout(25000)` within the `it()` function. I'd like to drop the global timeout in the future if possible rather than increase it - in some circumstances a failing test can have a knock-on effect which makes all later tests timeout so Travis can get hung up for a long time if no one notices and cancels the build. | TryGhost-Admin | js |
@@ -246,6 +246,11 @@ def _setSystemConfig(fromPath):
if curSourceDir==fromPath:
curDestDir=toPath
else:
+ if os.path.relpath(curSourceDir,fromPath) == "addons":
+ import addonHandler
+ subDirs[:] = [addon.name for addon in addonHandler.getRunningAddons()]
+ else:
+ subDirs[:] = subDirs
curDestDir=os.path.join(toPath,os.path.relpath(curSourceDir,fromPath))
if not os.path.isdir(curDestDir):
os.makedirs(curDestDir) | 1 | # -*- coding: UTF-8 -*-
#config/__init__.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2018 NV Access Limited, Aleksey Sadovoy, Peter Vágner, Rui Batista, Zahari Yurukov, Joseph Lee, Babbage B.V.
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
"""Manages NVDA configuration.
"""
import globalVars
import _winreg
import ctypes
import ctypes.wintypes
import os
import sys
from cStringIO import StringIO
import itertools
import contextlib
from copy import deepcopy
from collections import OrderedDict
from configobj import ConfigObj, ConfigObjError
from validate import Validator
from logHandler import log, levelNames
from logging import DEBUG
import shlobj
import baseObject
import easeOfAccess
from fileUtils import FaultTolerantFile
import winKernel
import extensionPoints
import profileUpgrader
from .configSpec import confspec
#: True if NVDA is running as a Windows Store Desktop Bridge application
isAppX=False
#: The active configuration, C{None} if it has not yet been loaded.
#: @type: ConfigObj
conf = None
#: Notifies when the configuration profile is switched.
#: This allows components to apply changes required by the new configuration.
#: For example, braille switches braille displays if necessary.
#: Handlers are called with no arguments.
configProfileSwitched = extensionPoints.Action()
def initialize():
global conf
conf = ConfigManager()
def saveOnExit():
"""Save the configuration if configured to save on exit.
This should only be called if NVDA is about to exit.
Errors are ignored.
"""
if conf["general"]["saveConfigurationOnExit"]:
try:
conf.save()
except:
pass
def isInstalledCopy():
"""Checks to see if this running copy of NVDA is installed on the system"""
try:
k=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\NVDA")
instDir=_winreg.QueryValueEx(k,"UninstallDirectory")[0]
except WindowsError:
return False
_winreg.CloseKey(k)
try:
return os.stat(instDir)==os.stat(os.getcwdu())
except WindowsError:
return False
#: #6864: The name of the subkey stored under NVDA_REGKEY where the value is stored
#: which will make an installed NVDA load the user configuration either from the local or from the roaming application data profile.
#: The registry value is unset by default.
#: When setting it manually, a DWORD value is prefered.
#: A value of 0 will evaluate to loading the configuration from the roaming application data (default).
#: A value of 1 means loading the configuration from the local application data folder.
#: @type: unicode
CONFIG_IN_LOCAL_APPDATA_SUBKEY=u"configInLocalAppData"
def getInstalledUserConfigPath():
try:
k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, NVDA_REGKEY)
configInLocalAppData = bool(_winreg.QueryValueEx(k, CONFIG_IN_LOCAL_APPDATA_SUBKEY)[0])
except WindowsError:
configInLocalAppData=False
configParent=shlobj.SHGetFolderPath(0, shlobj.CSIDL_LOCAL_APPDATA if configInLocalAppData else shlobj.CSIDL_APPDATA)
try:
return os.path.join(configParent, "nvda")
except WindowsError:
return None
def getUserDefaultConfigPath(useInstalledPathIfExists=False):
"""Get the default path for the user configuration directory.
This is the default path and doesn't reflect overriding from the command line,
which includes temporary copies.
Most callers will want the C{globalVars.appArgs.configPath variable} instead.
"""
installedUserConfigPath=getInstalledUserConfigPath()
if installedUserConfigPath and (isInstalledCopy() or isAppX or (useInstalledPathIfExists and os.path.isdir(installedUserConfigPath))):
if isAppX:
# NVDA is running as a Windows Store application.
# Although Windows will redirect %APPDATA% to a user directory specific to the Windows Store application,
# It also makes existing %APPDATA% files available here.
# We cannot share NVDA user config directories with other copies of NVDA as their config may be using add-ons
# Therefore add a suffix to the directory to make it specific to Windows Store application versions.
installedUserConfigPath+='_appx'
return installedUserConfigPath
return u'.\\userConfig\\'
def getSystemConfigPath():
if isInstalledCopy():
try:
return os.path.join(shlobj.SHGetFolderPath(0, shlobj.CSIDL_COMMON_APPDATA), "nvda")
except WindowsError:
pass
return None
def initConfigPath(configPath=None):
"""
Creates the current configuration path if it doesn't exist. Also makes sure that various sub directories also exist.
@param configPath: an optional path which should be used instead (only useful when being called from outside of NVDA)
@type configPath: basestring
"""
if not configPath:
configPath=globalVars.appArgs.configPath
if not os.path.isdir(configPath):
os.makedirs(configPath)
subdirs=["speechDicts","profiles"]
if not isAppX:
subdirs.extend(["addons", "appModules","brailleDisplayDrivers","synthDrivers","globalPlugins"])
for subdir in subdirs:
subdir=os.path.join(configPath,subdir)
if not os.path.isdir(subdir):
os.makedirs(subdir)
RUN_REGKEY = ur"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
def getStartAfterLogon():
if (easeOfAccess.isSupported and easeOfAccess.canConfigTerminateOnDesktopSwitch
and easeOfAccess.willAutoStart(_winreg.HKEY_CURRENT_USER)):
return True
try:
k = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, RUN_REGKEY)
val = _winreg.QueryValueEx(k, u"nvda")[0]
return os.stat(val) == os.stat(sys.argv[0])
except (WindowsError, OSError):
return False
def setStartAfterLogon(enable):
if getStartAfterLogon() == enable:
return
if easeOfAccess.isSupported and easeOfAccess.canConfigTerminateOnDesktopSwitch:
easeOfAccess.setAutoStart(_winreg.HKEY_CURRENT_USER, enable)
if enable:
return
# We're disabling, so ensure the run key is cleared,
# as it might have been set by an old version.
run = False
else:
run = enable
k = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, RUN_REGKEY, 0, _winreg.KEY_WRITE)
if run:
_winreg.SetValueEx(k, u"nvda", None, _winreg.REG_SZ, sys.argv[0])
else:
try:
_winreg.DeleteValue(k, u"nvda")
except WindowsError:
pass
def canStartOnSecureScreens():
# No more need to check for the NVDA service nor presence of Ease of Access, as only Windows 7 SP1 and higher is supported.
# This function will be transformed into a flag in a future release.
return isInstalledCopy()
def execElevated(path, params=None, wait=False,handleAlreadyElevated=False):
import subprocess
import shellapi
import winUser
if params is not None:
params = subprocess.list2cmdline(params)
sei = shellapi.SHELLEXECUTEINFO(lpFile=os.path.abspath(path), lpParameters=params, nShow=winUser.SW_HIDE)
#IsUserAnAdmin is apparently deprecated so may not work above Windows 8
if not handleAlreadyElevated or not ctypes.windll.shell32.IsUserAnAdmin():
sei.lpVerb=u"runas"
if wait:
sei.fMask = shellapi.SEE_MASK_NOCLOSEPROCESS
shellapi.ShellExecuteEx(sei)
if wait:
try:
h=ctypes.wintypes.HANDLE(sei.hProcess)
msg=ctypes.wintypes.MSG()
while ctypes.windll.user32.MsgWaitForMultipleObjects(1,ctypes.byref(h),False,-1,255)==1:
while ctypes.windll.user32.PeekMessageW(ctypes.byref(msg),None,0,0,1):
ctypes.windll.user32.TranslateMessage(ctypes.byref(msg))
ctypes.windll.user32.DispatchMessageW(ctypes.byref(msg))
return winKernel.GetExitCodeProcess(sei.hProcess)
finally:
winKernel.closeHandle(sei.hProcess)
SLAVE_FILENAME = u"nvda_slave.exe"
#: The name of the registry key stored under HKEY_LOCAL_MACHINE where system wide NVDA settings are stored.
#: Note that NVDA is a 32-bit application, so on X64 systems, this will evaluate to "SOFTWARE\WOW6432Node\nvda"
NVDA_REGKEY = ur"SOFTWARE\NVDA"
def getStartOnLogonScreen():
if easeOfAccess.isSupported and easeOfAccess.willAutoStart(_winreg.HKEY_LOCAL_MACHINE):
return True
try:
k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, NVDA_REGKEY)
return bool(_winreg.QueryValueEx(k, u"startOnLogonScreen")[0])
except WindowsError:
return False
def _setStartOnLogonScreen(enable):
if easeOfAccess.isSupported:
# The installer will have migrated service config to EoA if appropriate,
# so we only need to deal with EoA here.
easeOfAccess.setAutoStart(_winreg.HKEY_LOCAL_MACHINE, enable)
else:
k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, NVDA_REGKEY, 0, _winreg.KEY_WRITE)
_winreg.SetValueEx(k, u"startOnLogonScreen", None, _winreg.REG_DWORD, int(enable))
def setSystemConfigToCurrentConfig():
fromPath=os.path.abspath(globalVars.appArgs.configPath)
if ctypes.windll.shell32.IsUserAnAdmin():
_setSystemConfig(fromPath)
else:
res=execElevated(SLAVE_FILENAME, (u"setNvdaSystemConfig", fromPath), wait=True)
if res==2:
raise installer.RetriableFailure
elif res!=0:
raise RuntimeError("Slave failure")
def _setSystemConfig(fromPath):
import installer
toPath=os.path.join(sys.prefix.decode('mbcs'),'systemConfig')
if os.path.isdir(toPath):
installer.tryRemoveFile(toPath)
for curSourceDir,subDirs,files in os.walk(fromPath):
if curSourceDir==fromPath:
curDestDir=toPath
else:
curDestDir=os.path.join(toPath,os.path.relpath(curSourceDir,fromPath))
if not os.path.isdir(curDestDir):
os.makedirs(curDestDir)
for f in files:
# Do not copy executables to the system configuration, as this may cause security risks.
# This will also exclude pending updates.
if f.endswith(".exe"):
log.debug("Ignored file %s while copying current user configuration to system configuration"%f)
continue
sourceFilePath=os.path.join(curSourceDir,f)
destFilePath=os.path.join(curDestDir,f)
installer.tryCopyFile(sourceFilePath,destFilePath)
def setStartOnLogonScreen(enable):
if getStartOnLogonScreen() == enable:
return
try:
# Try setting it directly.
_setStartOnLogonScreen(enable)
except WindowsError:
# We probably don't have admin privs, so we need to elevate to do this using the slave.
if execElevated(SLAVE_FILENAME, (u"config_setStartOnLogonScreen", u"%d" % enable), wait=True) != 0:
raise RuntimeError("Slave failed to set startOnLogonScreen")
def getConfigDirs(subpath=None):
"""Retrieve all directories that should be used when searching for configuration.
IF C{subpath} is provided, it will be added to each directory returned.
@param subpath: The path to be added to each directory, C{None} for none.
@type subpath: str
@return: The configuration directories in the order in which they should be searched.
@rtype: list of str
"""
return [os.path.join(dir, subpath) if subpath else dir
for dir in (globalVars.appArgs.configPath,)
]
def addConfigDirsToPythonPackagePath(module, subdir=None):
"""Add the configuration directories to the module search path (__path__) of a Python package.
C{subdir} is added to each configuration directory. It defaults to the name of the Python package.
@param module: The root module of the package.
@type module: module
@param subdir: The subdirectory to be used, C{None} for the name of C{module}.
@type subdir: str
"""
if isAppX or globalVars.appArgs.disableAddons:
return
if not subdir:
subdir = module.__name__
# Python 2.x doesn't properly handle unicode import paths, so convert them.
dirs = [dir.encode("mbcs") for dir in getConfigDirs(subdir)]
dirs.extend(module.__path__ )
module.__path__ = dirs
# FIXME: this should not be coupled to the config module....
import addonHandler
for addon in addonHandler.getRunningAddons():
addon.addToPackagePath(module)
class ConfigManager(object):
"""Manages and provides access to configuration.
In addition to the base configuration, there can be multiple active configuration profiles.
Settings in more recently activated profiles take precedence,
with the base configuration being consulted last.
This allows a profile to override settings in profiles activated earlier and the base configuration.
A profile need only include a subset of the available settings.
Changed settings are written to the most recently activated profile.
"""
#: Sections that only apply to the base configuration;
#: i.e. they cannot be overridden in profiles.
BASE_ONLY_SECTIONS = {"general", "update", "upgrade"}
def __init__(self):
self.spec = confspec
#: All loaded profiles by name.
self._profileCache = {}
#: The active profiles.
self.profiles = []
#: Whether profile triggers are enabled (read-only).
#: @type: bool
self.profileTriggersEnabled = True
self.validator = Validator()
self.rootSection = None
self._shouldHandleProfileSwitch = True
self._pendingHandleProfileSwitch = False
self._suspendedTriggers = None
# Never save the config if running securely or if running from the launcher.
# When running from the launcher we don't save settings because the user may decide not to
# install this version, and these settings may not be compatible with the already
# installed version. See #7688
self._shouldWriteProfile = not (globalVars.appArgs.secure or globalVars.appArgs.launcher)
self._initBaseConf()
#: Maps triggers to profiles.
self.triggersToProfiles = None
self._loadProfileTriggers()
#: The names of all profiles that have been modified since they were last saved.
self._dirtyProfiles = set()
def _handleProfileSwitch(self):
if not self._shouldHandleProfileSwitch:
self._pendingHandleProfileSwitch = True
return
init = self.rootSection is None
# Reset the cache.
self.rootSection = AggregatedSection(self, (), self.spec, self.profiles)
if init:
# We're still initialising, so don't notify anyone about this change.
return
configProfileSwitched.notify()
def _initBaseConf(self, factoryDefaults=False):
fn = os.path.join(globalVars.appArgs.configPath, "nvda.ini")
if factoryDefaults:
profile = self._loadConfig(None)
profile.filename = fn
else:
try:
profile = self._loadConfig(fn) # a blank config returned if fn does not exist
self.baseConfigError = False
except:
log.error("Error loading base configuration", exc_info=True)
self.baseConfigError = True
return self._initBaseConf(factoryDefaults=True)
for key in self.BASE_ONLY_SECTIONS:
# These sections are returned directly from the base config, so validate them here.
try:
sect = profile[key]
except KeyError:
profile[key] = {}
# ConfigObj mutates this into a configobj.Section.
sect = profile[key]
sect.configspec = self.spec[key]
profile.validate(self.validator, section=sect)
self._profileCache[None] = profile
self.profiles.append(profile)
self._handleProfileSwitch()
def _loadConfig(self, fn, fileError=False):
log.info(u"Loading config: {0}".format(fn))
profile = ConfigObj(fn, indent_type="\t", encoding="UTF-8", file_error=fileError)
# Python converts \r\n to \n when reading files in Windows, so ConfigObj can't determine the true line ending.
profile.newlines = "\r\n"
profileCopy = deepcopy(profile)
try:
writeProfileFunc = self._writeProfileToFile if self._shouldWriteProfile else None
profileUpgrader.upgrade(profile, self.validator, writeProfileFunc)
except Exception as e:
# Log at level info to ensure that the profile is logged.
log.info(u"Config before schema update:\n%s" % profileCopy, exc_info=False)
raise e
# since profile settings are not yet imported we have to "peek" to see
# if debug level logging is enabled.
try:
logLevelName = profile["general"]["loggingLevel"]
except KeyError as e:
logLevelName = None
if log.isEnabledFor(log.DEBUG) or (logLevelName and DEBUG >= levelNames.get(logLevelName)):
# Log at level info to ensure that the profile is logged.
log.info(u"Config loaded (after upgrade, and in the state it will be used by NVDA):\n{0}".format(profile))
return profile
def __getitem__(self, key):
if key in self.BASE_ONLY_SECTIONS:
# Return these directly from the base configuration.
return self.profiles[0][key]
return self.rootSection[key]
def __contains__(self, key):
return key in self.rootSection
def get(self, key, default=None):
return self.rootSection.get(key, default)
def __setitem__(self, key, val):
self.rootSection[key] = val
def listProfiles(self):
for name in os.listdir(os.path.join(globalVars.appArgs.configPath, "profiles")):
name, ext = os.path.splitext(name)
if ext == ".ini":
yield name
def _getProfileFn(self, name):
return os.path.join(globalVars.appArgs.configPath, "profiles", name + ".ini")
def _getProfile(self, name, load=True):
try:
return self._profileCache[name]
except KeyError:
if not load:
raise KeyError(name)
# Load the profile.
fn = self._getProfileFn(name)
profile = self._loadConfig(fn, fileError = True) # file must exist.
profile.name = name
profile.manual = False
profile.triggered = False
self._profileCache[name] = profile
return profile
def getProfile(self, name):
"""Get a profile given its name.
This is useful for checking whether a profile has been manually activated or triggered.
@param name: The name of the profile.
@type name: basestring
@return: The profile object.
@raise KeyError: If the profile is not loaded.
"""
return self._getProfile(name, load=False)
def manualActivateProfile(self, name):
"""Manually activate a profile.
Only one profile can be manually active at a time.
If another profile was manually activated, deactivate it first.
If C{name} is C{None}, a profile will not be activated.
@param name: The name of the profile or C{None} for no profile.
@type name: basestring
"""
if len(self.profiles) > 1:
profile = self.profiles[-1]
if profile.manual:
del self.profiles[-1]
profile.manual = False
if name:
profile = self._getProfile(name)
profile.manual = True
self.profiles.append(profile)
self._handleProfileSwitch()
def _markWriteProfileDirty(self):
if len(self.profiles) == 1:
# There's nothing other than the base config, which is always saved anyway.
return
self._dirtyProfiles.add(self.profiles[-1].name)
def _writeProfileToFile(self, filename, profile):
with FaultTolerantFile(filename) as f:
profile.write(f)
def save(self):
"""Save all modified profiles and the base configuration to disk.
"""
if not self._shouldWriteProfile:
log.info("Not writing profile, either --secure or --launcher args present")
return
try:
self._writeProfileToFile(self.profiles[0].filename, self.profiles[0])
log.info("Base configuration saved")
for name in self._dirtyProfiles:
self._writeProfileToFile(self._profileCache[name].filename, self._profileCache[name])
log.info("Saved configuration profile %s" % name)
self._dirtyProfiles.clear()
except Exception as e:
log.warning("Error saving configuration; probably read only file system")
log.debugWarning("", exc_info=True)
raise e
def reset(self, factoryDefaults=False):
"""Reset the configuration to saved settings or factory defaults.
@param factoryDefaults: C{True} to reset to factory defaults, C{False} to reset to saved configuration.
@type factoryDefaults: bool
"""
self.profiles = []
self._profileCache.clear()
# Signal that we're initialising.
self.rootSection = None
self._initBaseConf(factoryDefaults=factoryDefaults)
def createProfile(self, name):
"""Create a profile.
@param name: The name of the profile ot create.
@type name: basestring
@raise ValueError: If a profile with this name already exists.
"""
if globalVars.appArgs.secure:
return
fn = self._getProfileFn(name)
if os.path.isfile(fn):
raise ValueError("A profile with the same name already exists: %s" % name)
# Just create an empty file to make sure we can.
file(fn, "w")
def deleteProfile(self, name):
"""Delete a profile.
@param name: The name of the profile to delete.
@type name: basestring
@raise LookupError: If the profile doesn't exist.
"""
if globalVars.appArgs.secure:
return
fn = self._getProfileFn(name)
if not os.path.isfile(fn):
raise LookupError("No such profile: %s" % name)
os.remove(fn)
try:
del self._profileCache[name]
except KeyError:
pass
# Remove any triggers associated with this profile.
allTriggers = self.triggersToProfiles
# You can't delete from a dict while iterating through it.
delTrigs = [trigSpec for trigSpec, trigProfile in allTriggers.iteritems()
if trigProfile == name]
if delTrigs:
for trigSpec in delTrigs:
del allTriggers[trigSpec]
self.saveProfileTriggers()
# Check if this profile was active.
delProfile = None
for index in xrange(len(self.profiles) - 1, -1, -1):
profile = self.profiles[index]
if profile.name == name:
# Deactivate it.
del self.profiles[index]
delProfile = profile
if not delProfile:
return
self._handleProfileSwitch()
if self._suspendedTriggers:
# Remove any suspended triggers referring to this profile.
for trigger in self._suspendedTriggers.keys():
if trigger._profile == delProfile:
del self._suspendedTriggers[trigger]
def renameProfile(self, oldName, newName):
"""Rename a profile.
@param oldName: The current name of the profile.
@type oldName: basestring
@param newName: The new name for the profile.
@type newName: basestring
@raise LookupError: If the profile doesn't exist.
@raise ValueError: If a profile with the new name already exists.
"""
if globalVars.appArgs.secure:
return
if newName == oldName:
return
oldFn = self._getProfileFn(oldName)
newFn = self._getProfileFn(newName)
if not os.path.isfile(oldFn):
raise LookupError("No such profile: %s" % oldName)
# Windows file names are case insensitive,
# so only test for file existence if the names don't match case insensitively.
if oldName.lower() != newName.lower() and os.path.isfile(newFn):
raise ValueError("A profile with the same name already exists: %s" % newName)
os.rename(oldFn, newFn)
# Update any associated triggers.
allTriggers = self.triggersToProfiles
saveTrigs = False
for trigSpec, trigProfile in allTriggers.iteritems():
if trigProfile == oldName:
allTriggers[trigSpec] = newName
saveTrigs = True
if saveTrigs:
self.saveProfileTriggers()
try:
profile = self._profileCache.pop(oldName)
except KeyError:
# The profile hasn't been loaded, so there's nothing more to do.
return
profile.name = newName
self._profileCache[newName] = profile
try:
self._dirtyProfiles.remove(oldName)
except KeyError:
# The profile wasn't dirty.
return
self._dirtyProfiles.add(newName)
def _triggerProfileEnter(self, trigger):
"""Called by L{ProfileTrigger.enter}}}.
"""
if not self.profileTriggersEnabled:
return
if self._suspendedTriggers is not None:
self._suspendedTriggers[trigger] = "enter"
return
try:
profile = trigger._profile = self._getProfile(trigger.profileName)
except:
trigger._profile = None
raise
profile.triggered = True
if len(self.profiles) > 1 and self.profiles[-1].manual:
# There's a manually activated profile.
# Manually activated profiles must be at the top of the stack, so insert this one below.
self.profiles.insert(-1, profile)
else:
self.profiles.append(profile)
self._handleProfileSwitch()
def _triggerProfileExit(self, trigger):
"""Called by L{ProfileTrigger.exit}}}.
"""
if not self.profileTriggersEnabled:
return
if self._suspendedTriggers is not None:
if trigger in self._suspendedTriggers:
# This trigger was entered and is now being exited.
# These cancel each other out.
del self._suspendedTriggers[trigger]
else:
self._suspendedTriggers[trigger] = "exit"
return
profile = trigger._profile
if profile is None:
return
profile.triggered = False
try:
self.profiles.remove(profile)
except ValueError:
# This is probably due to the user resetting the configuration.
log.debugWarning("Profile not active when exiting trigger")
return
self._handleProfileSwitch()
@contextlib.contextmanager
def atomicProfileSwitch(self):
"""Indicate that multiple profile switches should be treated as one.
This is useful when multiple triggers may be exited/entered at once;
e.g. when switching applications.
While multiple switches aren't harmful, they might take longer;
e.g. unnecessarily switching speech synthesizers or braille displays.
This is a context manager to be used with the C{with} statement.
"""
self._shouldHandleProfileSwitch = False
try:
yield
finally:
self._shouldHandleProfileSwitch = True
if self._pendingHandleProfileSwitch:
self._handleProfileSwitch()
self._pendingHandleProfileSwitch = False
def suspendProfileTriggers(self):
"""Suspend handling of profile triggers.
Any triggers that currently apply will continue to apply.
Subsequent enters or exits will not apply until triggers are resumed.
@see: L{resumeTriggers}
"""
if self._suspendedTriggers is not None:
return
self._suspendedTriggers = OrderedDict()
def resumeProfileTriggers(self):
"""Resume handling of profile triggers after previous suspension.
Any trigger enters or exits that occurred while triggers were suspended will be applied.
Trigger handling will then return to normal.
@see: L{suspendTriggers}
"""
if self._suspendedTriggers is None:
return
triggers = self._suspendedTriggers
self._suspendedTriggers = None
with self.atomicProfileSwitch():
for trigger, action in triggers.iteritems():
trigger.enter() if action == "enter" else trigger.exit()
def disableProfileTriggers(self):
"""Temporarily disable all profile triggers.
Any triggered profiles will be deactivated and subsequent triggers will not apply.
Call L{enableTriggers} to re-enable triggers.
"""
if not self.profileTriggersEnabled:
return
self.profileTriggersEnabled = False
for profile in self.profiles[1:]:
profile.triggered = False
if len(self.profiles) > 1 and self.profiles[-1].manual:
del self.profiles[1:-1]
else:
del self.profiles[1:]
self._suspendedTriggers = None
self._handleProfileSwitch()
def enableProfileTriggers(self):
"""Re-enable profile triggers after they were previously disabled.
"""
self.profileTriggersEnabled = True
def _loadProfileTriggers(self):
fn = os.path.join(globalVars.appArgs.configPath, "profileTriggers.ini")
try:
cobj = ConfigObj(fn, indent_type="\t", encoding="UTF-8")
except:
log.error("Error loading profile triggers", exc_info=True)
cobj = ConfigObj(None, indent_type="\t", encoding="UTF-8")
cobj.filename = fn
# Python converts \r\n to \n when reading files in Windows, so ConfigObj can't determine the true line ending.
cobj.newlines = "\r\n"
try:
self.triggersToProfiles = cobj["triggersToProfiles"]
except KeyError:
cobj["triggersToProfiles"] = {}
# ConfigObj will have mutated this into a configobj.Section.
self.triggersToProfiles = cobj["triggersToProfiles"]
def saveProfileTriggers(self):
"""Save profile trigger information to disk.
This should be called whenever L{profilesToTriggers} is modified.
"""
if globalVars.appArgs.secure:
# Never save if running securely.
return
self.triggersToProfiles.parent.write()
log.info("Profile triggers saved")
def getConfigValidationParameter(self, keyPath, validationParameter):
"""Get a config validation parameter
This can be used to get the min, max, default, or other values for a config key.
@param keyPath: a sequence of the identifiers leading to the config key. EG ("braille", "messageTimeout")
@param validationParameter: the parameter to return the value for. EG "max"
@type validationParameter: string
"""
if not keyPath or len(keyPath) < 1:
raise ValueError("Key path not provided")
spec = conf.spec
for nextKey in keyPath:
spec = spec[nextKey]
return conf.validator._parse_with_caching(spec)[2][validationParameter]
class AggregatedSection(object):
"""A view of a section of configuration which aggregates settings from all active profiles.
"""
def __init__(self, manager, path, spec, profiles):
self.manager = manager
self.path = path
self._spec = spec
#: The relevant section in all of the profiles.
self.profiles = profiles
self._cache = {}
def __getitem__(self, key, checkValidity=True):
# Try the cache first.
try:
val = self._cache[key]
except KeyError:
pass
else:
if val is KeyError:
# We know there's no such setting.
raise KeyError(key)
return val
spec = self._spec.get(key)
foundSection = False
if isinstance(spec, dict):
foundSection = True
# Walk through the profiles looking for the key.
# If it's a section, collect that section from all profiles.
subProfiles = []
for profile in reversed(self.profiles):
try:
val = profile[key]
except (KeyError, TypeError):
# Indicate that this key doesn't exist in this profile.
subProfiles.append(None)
continue
if isinstance(val, dict):
foundSection = True
subProfiles.append(val)
else:
# This is a setting.
if not checkValidity:
spec = None
return self._cacheLeaf(key, spec, val)
subProfiles.reverse()
if not foundSection and spec:
# This might have a default.
try:
val = self.manager.validator.get_default_value(spec)
except KeyError:
pass
else:
self._cache[key] = val
return val
if not foundSection:
# The key doesn't exist, so cache this fact.
self._cache[key] = KeyError
raise KeyError(key)
if spec is None:
# Create this section in the config spec.
self._spec[key] = {}
# ConfigObj might have mutated this into a configobj.Section.
spec = self._spec[key]
sect = self._cache[key] = AggregatedSection(self.manager, self.path + (key,), spec, subProfiles)
return sect
def __contains__(self, key):
try:
self[key]
return True
except KeyError:
return False
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def isSet(self, key):
"""Check whether a given key has been explicitly set.
This is sometimes useful because it can return C{False} even if there is a default for the key.
@return: C{True} if the key has been explicitly set, C{False} if not.
@rtype: bool
"""
for profile in self.profiles:
if not profile:
continue
if key in profile:
return True
return False
def _cacheLeaf(self, key, spec, val):
if spec:
# Validate and convert the value.
val = self.manager.validator.check(spec, val)
self._cache[key] = val
return val
def iteritems(self):
keys = set()
# Start with the cached items.
for key, val in self._cache.iteritems():
keys.add(key)
if val is not KeyError:
yield key, val
# Walk through the profiles and spec looking for items not yet cached.
for profile in itertools.chain(reversed(self.profiles), (self._spec,)):
if not profile:
continue
for key in profile:
if key in keys:
continue
keys.add(key)
# Use __getitem__ so caching, AggregatedSections, etc. are handled.
try:
yield key, self[key]
except KeyError:
# This could happen if the item is in the spec but there's no default.
pass
def copy(self):
return dict(self.iteritems())
def __setitem__(self, key, val):
spec = self._spec.get(key) if self.spec else None
if isinstance(spec, dict) and not isinstance(val, dict):
raise ValueError("Value must be a section")
if isinstance(spec, dict) or isinstance(val, dict):
# The value is a section.
# Update the profile.
updateSect = self._getUpdateSection()
updateSect[key] = val
self.manager._markWriteProfileDirty()
# ConfigObj will have mutated this into a configobj.Section.
val = updateSect[key]
cache = self._cache.get(key)
if cache and cache is not KeyError:
# An AggregatedSection has already been cached, so update it.
cache = self._cache[key]
cache.profiles[-1] = val
cache._cache.clear()
elif cache is KeyError:
# This key now exists, so remove the cached non-existence.
del self._cache[key]
# If an AggregatedSection isn't already cached,
# An appropriate AggregatedSection will be created the next time this section is fetched.
return
if spec:
# Validate and convert the value.
val = self.manager.validator.check(spec, val)
try:
# when setting the value we dont care if the existing value
# is not valid.
curVal = self.__getitem__(key, checkValidity=False)
except KeyError:
pass
else:
if val == curVal:
# The value isn't different, so there's nothing to do.
return
# Set this value in the most recently activated profile.
self._getUpdateSection()[key] = val
self.manager._markWriteProfileDirty()
self._cache[key] = val
def _getUpdateSection(self):
profile = self.profiles[-1]
if profile is not None:
# This section already exists in the profile.
return profile
section = self.manager.rootSection
profile = section.profiles[-1]
for part in self.path:
parentProfile = profile
section = section[part]
profile = section.profiles[-1]
if profile is None:
# This section doesn't exist in the profile yet.
# Create it and update the AggregatedSection.
parentProfile[part] = {}
# ConfigObj might have mutated this into a configobj.Section.
profile = section.profiles[-1] = parentProfile[part]
return profile
@property
def spec(self):
return self._spec
@spec.setter
def spec(self, val):
# This section is being replaced.
# Clear it and replace the content so it remains linked to the main spec.
self._spec.clear()
self._spec.update(val)
class ProfileTrigger(object):
"""A trigger for automatic activation/deactivation of a configuration profile.
The user can associate a profile with a trigger.
When the trigger applies, the associated profile is activated.
When the trigger no longer applies, the profile is deactivated.
L{spec} is a string used to search for this trigger and must be implemented.
To signal that this trigger applies, call L{enter}.
To signal that it no longer applies, call L{exit}.
Alternatively, you can use this object as a context manager via the with statement;
i.e. this trigger will apply only inside the with block.
"""
@baseObject.Getter
def spec(self):
"""The trigger specification.
This is a string used to search for this trigger in the user's configuration.
@rtype: basestring
"""
raise NotImplementedError
def enter(self):
"""Signal that this trigger applies.
The associated profile (if any) will be activated.
"""
try:
self.profileName = conf.triggersToProfiles[self.spec]
except KeyError:
self.profileName = None
return
try:
conf._triggerProfileEnter(self)
except:
log.error("Error entering trigger %s, profile %s"
% (self.spec, self.profileName), exc_info=True)
__enter__ = enter
def exit(self):
"""Signal that this trigger no longer applies.
The associated profile (if any) will be deactivated.
"""
if not self.profileName:
return
try:
conf._triggerProfileExit(self)
except:
log.error("Error exiting trigger %s, profile %s"
% (self.spec, self.profileName), exc_info=True)
def __exit__(self, excType, excVal, traceback):
self.exit()
TokenUIAccess = 26
def hasUiAccess():
token = ctypes.wintypes.HANDLE()
ctypes.windll.advapi32.OpenProcessToken(ctypes.windll.kernel32.GetCurrentProcess(),
winKernel.MAXIMUM_ALLOWED, ctypes.byref(token))
try:
val = ctypes.wintypes.DWORD()
ctypes.windll.advapi32.GetTokenInformation(token, TokenUIAccess,
ctypes.byref(val), ctypes.sizeof(ctypes.wintypes.DWORD),
ctypes.byref(ctypes.wintypes.DWORD()))
return bool(val.value)
finally:
ctypes.windll.kernel32.CloseHandle(token)
| 1 | 22,491 | I don't think this is necessary. | nvaccess-nvda | py |
@@ -1025,15 +1025,13 @@ func (vd *volAPI) snapEnumerate(w http.ResponseWriter, r *http.Request) {
return
}
- snaps := make([]*api.Volume, len(resp.GetVolumeSnapshotIds()))
- for i, s := range resp.GetVolumeSnapshotIds() {
+ snaps := make([]*api.Volume, 0)
+ for _, s := range resp.GetVolumeSnapshotIds() {
vol, err := volumes.Inspect(ctx, &api.SdkVolumeInspectRequest{VolumeId: s})
if err != nil {
- e := fmt.Errorf("Failed to inspect volumeID: %s", err.Error())
- vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
- return
+ continue
}
- snaps[i] = vol.GetVolume()
+ snaps = append(snaps, vol.GetVolume())
}
json.NewEncoder(w).Encode(snaps)
} | 1 | package server
import (
"context"
"encoding/json"
"fmt"
"math"
"net/http"
"strconv"
"strings"
"sync"
"github.com/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/libopenstorage/openstorage/api"
"github.com/libopenstorage/openstorage/api/errors"
sdk "github.com/libopenstorage/openstorage/api/server/sdk"
clustermanager "github.com/libopenstorage/openstorage/cluster/manager"
"github.com/libopenstorage/openstorage/pkg/auth/secrets"
"github.com/libopenstorage/openstorage/pkg/grpcserver"
"github.com/libopenstorage/openstorage/volume"
volumedrivers "github.com/libopenstorage/openstorage/volume/drivers"
osecrets "github.com/libopenstorage/secrets"
"github.com/urfave/negroni"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const schedDriverPostFix = "-sched"
type volAPI struct {
restBase
sdkUds string
conn *grpc.ClientConn
dummyMux *runtime.ServeMux
mu sync.Mutex
}
func responseStatus(err error) string {
if err == nil {
return ""
}
return err.Error()
}
func newVolumeAPI(name, sdkUds string) restServer {
return &volAPI{
restBase: restBase{version: volume.APIVersion, name: name},
sdkUds: sdkUds,
dummyMux: runtime.NewServeMux(),
}
}
func (vd *volAPI) String() string {
return vd.name
}
func (vd *volAPI) getConn() (*grpc.ClientConn, error) {
vd.mu.Lock()
defer vd.mu.Unlock()
if vd.conn == nil {
var err error
vd.conn, err = grpcserver.Connect(
vd.sdkUds,
[]grpc.DialOption{grpc.WithInsecure()})
if err != nil {
return nil, fmt.Errorf("Failed to connect to gRPC handler: %v", err)
}
}
return vd.conn, nil
}
func (vd *volAPI) annotateContext(r *http.Request) (context.Context, error) {
// This creates a context and populates the authentication token
// using the same function as the SDK REST Gateway
ctx, err := runtime.AnnotateContext(context.Background(), vd.dummyMux, r)
if err != nil {
return ctx, err
}
// If a header exists in the request fetch the requested driver name if provided
// and pass it in the grpc context as a metadata key value
userAgent := r.Header.Get("User-Agent")
if len(userAgent) > 0 {
// Check if the request is coming from a container orchestrator
clientName := strings.Split(userAgent, "/")
if len(clientName) > 0 {
return grpcserver.AddMetadataToContext(ctx, sdk.ContextDriverKey, clientName[0]), nil
}
}
return ctx, nil
}
func (vd *volAPI) getVolDriver(r *http.Request) (volume.VolumeDriver, error) {
// Check if the driver has registered by it's user agent name
userAgent := r.Header.Get("User-Agent")
if len(userAgent) > 0 {
clientName := strings.Split(userAgent, "/")
if len(clientName) > 0 {
d, err := volumedrivers.Get(clientName[0])
if err == nil {
return d, nil
}
}
}
// Check if the driver has registered a scheduler-based driver
d, err := volumedrivers.Get(vd.name + schedDriverPostFix)
if err == nil {
return d, nil
}
// default
return volumedrivers.Get(vd.name)
}
func (vd *volAPI) parseID(r *http.Request) (string, error) {
if id, err := vd.parseParam(r, "id"); err == nil {
return id, nil
}
return "", fmt.Errorf("could not parse snap ID")
}
func (vd *volAPI) parseParam(r *http.Request, param string) (string, error) {
vars := mux.Vars(r)
if id, ok := vars[param]; ok {
return id, nil
}
return "", fmt.Errorf("could not parse %s", param)
}
func (vd *volAPI) nodeIPtoIds(nodes []string) ([]string, error) {
nodeIds := make([]string, 0)
// Get cluster instance
c, err := clustermanager.Inst()
if err != nil {
return nodeIds, err
}
if c == nil {
return nodeIds, fmt.Errorf("failed to get cluster instance.")
}
for _, idIp := range nodes {
if idIp != "" {
id, err := c.GetNodeIdFromIp(idIp)
if err != nil {
return nodeIds, err
}
nodeIds = append(nodeIds, id)
}
}
return nodeIds, err
}
// Convert any replica set node values which are IPs to the corresponding Node ID.
// Update the replica set node list.
func (vd *volAPI) updateReplicaSpecNodeIPstoIds(rspecRef *api.ReplicaSet) error {
if rspecRef != nil && len(rspecRef.Nodes) > 0 {
nodeIds, err := vd.nodeIPtoIds(rspecRef.Nodes)
if err != nil {
return err
}
if len(nodeIds) > 0 {
rspecRef.Nodes = nodeIds
}
}
return nil
}
// Creates a single volume with given spec.
func (vd *volAPI) create(w http.ResponseWriter, r *http.Request) {
var dcRes api.VolumeCreateResponse
var dcReq api.VolumeCreateRequest
method := "create"
if err := json.NewDecoder(r.Body).Decode(&dcReq); err != nil {
fmt.Println("returning error here")
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
// Get context with auth token
ctx, err := vd.annotateContext(r)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
// Get gRPC connection
conn, err := vd.getConn()
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusInternalServerError)
return
}
spec := dcReq.GetSpec()
if spec.VolumeLabels == nil {
spec.VolumeLabels = make(map[string]string)
}
for k, v := range dcReq.Locator.GetVolumeLabels() {
spec.VolumeLabels[k] = v
}
volumes := api.NewOpenStorageVolumeClient(conn)
id, err := volumes.Create(ctx, &api.SdkVolumeCreateRequest{
Name: dcReq.Locator.GetName(),
Labels: dcReq.Locator.GetVolumeLabels(),
Spec: dcReq.GetSpec(),
})
dcRes.VolumeResponse = &api.VolumeResponse{Error: responseStatus(err)}
if err == nil {
dcRes.Id = id.GetVolumeId()
}
json.NewEncoder(w).Encode(&dcRes)
}
func processErrorForVolSetResponse(action *api.VolumeStateAction, err error, resp *api.VolumeSetResponse) {
if err == nil || resp == nil {
return
}
if action != nil && (action.Mount == api.VolumeActionParam_VOLUME_ACTION_PARAM_OFF ||
action.Attach == api.VolumeActionParam_VOLUME_ACTION_PARAM_OFF) {
switch err.(type) {
case *errors.ErrNotFound:
resp.VolumeResponse = &api.VolumeResponse{}
resp.Volume = &api.Volume{}
default:
resp.VolumeResponse = &api.VolumeResponse{
Error: err.Error(),
}
}
} else if err != nil {
resp.VolumeResponse = &api.VolumeResponse{
Error: err.Error(),
}
}
}
// swagger:operation PUT /osd-volumes/{id} volume setVolume
//
// Updates a single volume with given spec.
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id to get volume with
// required: true
// type: integer
// - name: spec
// in: body
// description: spec to set volume with
// required: true
// schema:
// "$ref": "#/definitions/VolumeSetRequest"
// responses:
// '200':
// description: volume set response
// schema:
// "$ref": "#/definitions/VolumeSetResponse"
// default:
// description: unexpected error
// schema:
// "$ref": "#/definitions/VolumeSetResponse"
func (vd *volAPI) volumeSet(w http.ResponseWriter, r *http.Request) {
var (
volumeID string
err error
req api.VolumeSetRequest
resp api.VolumeSetResponse
)
method := "volumeSet"
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
if volumeID, err = vd.parseID(r); err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
// Get context with auth token
ctx, err := vd.annotateContext(r)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
// Get gRPC connection
conn, err := vd.getConn()
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusInternalServerError)
return
}
setActions := ""
if req.Action != nil {
setActions = fmt.Sprintf("Mount=%v Attach=%v", req.Action.Mount, req.Action.Attach)
}
vd.logRequest(method, string(volumeID)).Infoln(setActions)
volumes := api.NewOpenStorageVolumeClient(conn)
vol, err := volumes.Inspect(ctx, &api.SdkVolumeInspectRequest{
VolumeId: volumeID,
})
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
detachOptions := &api.SdkVolumeDetachOptions{}
attachOptions := &api.SdkVolumeAttachOptions{}
if req.Locator != nil || req.Spec != nil {
updateReq := &api.SdkVolumeUpdateRequest{VolumeId: volumeID}
if req.Locator != nil && len(req.Locator.VolumeLabels) > 0 {
updateReq.Labels = req.Locator.VolumeLabels
}
if req.Spec != nil {
if err = vd.updateReplicaSpecNodeIPstoIds(req.Spec.ReplicaSet); err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
updateReq.Spec = getVolumeUpdateSpec(req.Spec, vol.GetVolume())
}
// Only set spec if spec and locator are not nil.
if _, err := volumes.Update(ctx, updateReq); err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
}
if req.Options["SECRET_NAME"] != "" {
attachOptions.SecretName = req.Options["SECRET_NAME"]
}
if req.Options["SECRET_KEY"] != "" {
attachOptions.SecretKey = req.Options["SECRET_KEY"]
}
if req.Options["SECRET_CONTEXT"] != "" {
attachOptions.SecretContext = req.Options["SECRET_CONTEXT"]
}
if req.Options["FORCE_DETACH"] == "true" {
detachOptions.Force = true
}
if req.Options["UNMOUNT_BEFORE_DETACH"] == "true" {
detachOptions.UnmountBeforeDetach = true
}
mountAttachClient := api.NewOpenStorageMountAttachClient(conn)
for err == nil && req.Action != nil {
if req.Action.Attach != api.VolumeActionParam_VOLUME_ACTION_PARAM_NONE {
if req.Action.Attach == api.VolumeActionParam_VOLUME_ACTION_PARAM_ON {
_, err = mountAttachClient.Attach(ctx, &api.SdkVolumeAttachRequest{
VolumeId: volumeID,
Options: attachOptions,
DriverOptions: req.GetOptions(),
})
} else {
_, err = mountAttachClient.Detach(ctx, &api.SdkVolumeDetachRequest{
VolumeId: volumeID,
Options: detachOptions,
DriverOptions: req.GetOptions(),
})
}
if err != nil {
break
}
}
unmountOptions := &api.SdkVolumeUnmountOptions{}
if req.Options["DELETE_AFTER_UNMOUNT"] == "true" {
unmountOptions.DeleteMountPath = true
}
if req.Options["WAIT_BEFORE_DELETE"] == "true" {
unmountOptions.NoDelayBeforeDeletingMountPath = false
} else {
unmountOptions.NoDelayBeforeDeletingMountPath = true
}
if req.Action.Mount != api.VolumeActionParam_VOLUME_ACTION_PARAM_NONE {
if req.Action.Mount == api.VolumeActionParam_VOLUME_ACTION_PARAM_ON {
if req.Action.MountPath == "" {
err = fmt.Errorf("Invalid mount path")
break
}
_, err = mountAttachClient.Mount(ctx, &api.SdkVolumeMountRequest{
VolumeId: volumeID,
MountPath: req.Action.MountPath,
DriverOptions: req.GetOptions(),
})
} else {
_, err = mountAttachClient.Unmount(ctx, &api.SdkVolumeUnmountRequest{
VolumeId: volumeID,
MountPath: req.Action.MountPath,
Options: unmountOptions,
DriverOptions: req.GetOptions(),
})
}
if err != nil {
break
}
}
break
}
resVol, err2 := volumes.Inspect(ctx, &api.SdkVolumeInspectRequest{
VolumeId: volumeID,
})
if err2 != nil {
resp.Volume = &api.Volume{}
} else {
resp.Volume = resVol.GetVolume()
}
resp.VolumeResponse = &api.VolumeResponse{
Error: responseStatus(err),
}
json.NewEncoder(w).Encode(resp)
}
func getVolumeUpdateSpec(spec *api.VolumeSpec, vol *api.Volume) *api.VolumeSpecUpdate {
newSpec := &api.VolumeSpecUpdate{}
if spec == nil {
return newSpec
}
newSpec.ReplicaSet = spec.ReplicaSet
if spec.Shared != vol.Spec.Shared {
newSpec.SharedOpt = &api.VolumeSpecUpdate_Shared{
Shared: spec.Shared,
}
}
if spec.Sharedv4 != vol.Spec.Sharedv4 {
newSpec.Sharedv4Opt = &api.VolumeSpecUpdate_Sharedv4{
Sharedv4: spec.Sharedv4,
}
}
if spec.Passphrase != vol.Spec.Passphrase {
newSpec.PassphraseOpt = &api.VolumeSpecUpdate_Passphrase{
Passphrase: spec.Passphrase,
}
}
if spec.Cos != vol.Spec.Cos && spec.Cos != 0 {
newSpec.CosOpt = &api.VolumeSpecUpdate_Cos{
Cos: spec.Cos,
}
}
if spec.Journal != vol.Spec.Journal {
newSpec.JournalOpt = &api.VolumeSpecUpdate_Journal{
Journal: spec.Journal,
}
}
if spec.Nodiscard != vol.Spec.Nodiscard {
newSpec.NodiscardOpt = &api.VolumeSpecUpdate_Nodiscard{
Nodiscard: spec.Nodiscard,
}
}
newSpec.IoStrategy = spec.IoStrategy
if spec.Sticky != vol.Spec.Sticky {
newSpec.StickyOpt = &api.VolumeSpecUpdate_Sticky{
Sticky: spec.Sticky,
}
}
if spec.Scale != vol.Spec.Scale {
newSpec.ScaleOpt = &api.VolumeSpecUpdate_Scale{
Scale: spec.Scale,
}
}
if spec.Size != vol.Spec.Size {
newSpec.SizeOpt = &api.VolumeSpecUpdate_Size{
Size: spec.Size,
}
}
if spec.IoProfile != vol.Spec.IoProfile {
newSpec.IoProfileOpt = &api.VolumeSpecUpdate_IoProfile{
IoProfile: spec.IoProfile,
}
}
if spec.Dedupe != vol.Spec.Dedupe {
newSpec.DedupeOpt = &api.VolumeSpecUpdate_Dedupe{
Dedupe: spec.Dedupe,
}
}
if spec.Sticky != vol.Spec.Sticky {
newSpec.StickyOpt = &api.VolumeSpecUpdate_Sticky{
Sticky: spec.Sticky,
}
}
if spec.Group != vol.Spec.Group && spec.Group != nil {
newSpec.GroupOpt = &api.VolumeSpecUpdate_Group{
Group: spec.Group,
}
}
if spec.QueueDepth != vol.Spec.QueueDepth {
newSpec.QueueDepthOpt = &api.VolumeSpecUpdate_QueueDepth{
QueueDepth: spec.QueueDepth,
}
}
if spec.SnapshotSchedule != vol.Spec.SnapshotSchedule {
newSpec.SnapshotScheduleOpt = &api.VolumeSpecUpdate_SnapshotSchedule{
SnapshotSchedule: spec.SnapshotSchedule,
}
}
if spec.SnapshotInterval != vol.Spec.SnapshotInterval && spec.SnapshotInterval != math.MaxUint32 {
newSpec.SnapshotIntervalOpt = &api.VolumeSpecUpdate_SnapshotInterval{
SnapshotInterval: spec.SnapshotInterval,
}
}
if spec.HaLevel != vol.Spec.HaLevel && spec.HaLevel != 0 {
newSpec.HaLevelOpt = &api.VolumeSpecUpdate_HaLevel{
HaLevel: spec.HaLevel,
}
}
return newSpec
}
// swagger:operation GET /osd-volumes/{id} volume inspectVolume
//
// Inspect volume with specified id.
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id to get volume with
// required: true
// type: integer
// responses:
// '200':
// description: volume get response
// schema:
// "$ref": "#/definitions/Volume"
func (vd *volAPI) inspect(w http.ResponseWriter, r *http.Request) {
var err error
var volumeID string
method := "inspect"
if volumeID, err = vd.parseID(r); err != nil {
e := fmt.Errorf("Failed to parse parse volumeID: %s", err.Error())
vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
return
}
// Get context with auth token
ctx, err := vd.annotateContext(r)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
// Get gRPC connection
conn, err := vd.getConn()
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusInternalServerError)
return
}
volumes := api.NewOpenStorageVolumeClient(conn)
dk, err := volumes.Inspect(ctx, &api.SdkVolumeInspectRequest{VolumeId: volumeID})
dkVolumes := []*api.Volume{}
if err != nil {
// SDK returns a NotFound error for an invalid volume
// Previously the REST server returned an empty array if a volume was not found
if s, ok := status.FromError(err); ok && s.Code() != codes.NotFound {
vd.sendError(vd.name, method, w, err.Error(), http.StatusNotFound)
return
}
} else {
dkVolumes = append(dkVolumes, dk.GetVolume())
}
json.NewEncoder(w).Encode(dkVolumes)
}
// swagger:operation DELETE /osd-volumes/{id} volume deleteVolume
//
// Delete volume with specified id.
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id to get volume with
// required: true
// type: integer
// responses:
// '200':
// description: volume set response
// schema:
// "$ref": "#/definitions/VolumeResponse"
// default:
// description: unexpected error
// schema:
// "$ref": "#/definitions/VolumeResponse"
func (vd *volAPI) delete(w http.ResponseWriter, r *http.Request) {
var volumeID string
var err error
method := "delete"
if volumeID, err = vd.parseID(r); err != nil {
e := fmt.Errorf("Failed to parse parse volumeID: %s", err.Error())
vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
return
}
vd.logRequest(method, volumeID).Infoln("")
volumeResponse := &api.VolumeResponse{}
// Get context with auth token
ctx, err := vd.annotateContext(r)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
// Get gRPC connection
conn, err := vd.getConn()
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusInternalServerError)
return
}
volumes := api.NewOpenStorageVolumeClient(conn)
_, err = volumes.Delete(ctx, &api.SdkVolumeDeleteRequest{VolumeId: volumeID})
if err != nil {
volumeResponse.Error = err.Error()
}
json.NewEncoder(w).Encode(volumeResponse)
}
// swagger:operation GET /osd-volumes volume enumerateVolumes
//
// Enumerate all volumes
//
// ---
// consumes:
// - multipart/form-data
// produces:
// - application/json
// parameters:
// - name: Name
// in: query
// description: User specified volume name (Case Sensitive)
// required: false
// type: string
// - name: Label
// in: formData
// description: |
// Comma separated name value pairs
// example: {"label1","label2"}
// required: false
// type: string
// - name: ConfigLabel
// in: formData
// description: |
// Comma separated name value pairs
// example: {"label1","label2"}
// required: false
// type: string
// - name: VolumeID
// in: query
// description: Volume UUID
// required: false
// type: string
// format: uuid
// responses:
// '200':
// description: an array of volumes
// schema:
// type: array
// items:
// $ref: '#/definitions/Volume'
func (vd *volAPI) enumerate(w http.ResponseWriter, r *http.Request) {
var locator api.VolumeLocator
var configLabels map[string]string
var err error
var ids []string
var vols []*api.Volume
method := "enumerate"
// Get context with auth token
ctx, err := vd.annotateContext(r)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
// Get gRPC connection
conn, err := vd.getConn()
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusInternalServerError)
return
}
volumes := api.NewOpenStorageVolumeClient(conn)
params := r.URL.Query()
v := params[string(api.OptName)]
if v != nil {
locator.Name = v[0]
}
v = params[string(api.OptLabel)]
if v != nil {
if err = json.Unmarshal([]byte(v[0]), &locator.VolumeLabels); err != nil {
e := fmt.Errorf("Failed to parse parse VolumeLabels: %s", err.Error())
vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
}
}
v = params[string(api.OptConfigLabel)]
if v != nil {
if err = json.Unmarshal([]byte(v[0]), &configLabels); err != nil {
e := fmt.Errorf("Failed to parse parse configLabels: %s", err.Error())
vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
}
// Add config labels to locator object.
for l, _ := range configLabels {
locator.VolumeLabels[l] = configLabels[l]
}
}
v = params[string(api.OptVolumeID)]
if v != nil {
ids = make([]string, len(v))
for i, s := range v {
ids[i] = string(s)
}
} else {
vls, err := volumes.EnumerateWithFilters(ctx, &api.SdkVolumeEnumerateWithFiltersRequest{
Name: locator.Name,
Labels: locator.VolumeLabels,
})
//vols, err = d.Enumerate(&locator, configLabels)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusInternalServerError)
return
}
ids = vls.GetVolumeIds()
}
vols = make([]*api.Volume, 0)
for _, s := range ids {
vol, err := volumes.Inspect(ctx, &api.SdkVolumeInspectRequest{VolumeId: s})
if err == nil {
vols = append(vols, vol.GetVolume())
}
}
json.NewEncoder(w).Encode(vols)
}
// swagger:operation POST /osd-snapshots snapshot createSnap
//
// Take a snapshot of volume in SnapCreateRequest
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: query
// description: id to get volume with
// required: true
// type: integer
// - name: spec
// in: body
// description: spec to create snap with
// required: true
// schema:
// "$ref": "#/definitions/SnapCreateRequest"
// responses:
// '200':
// description: an array of volumes
// schema:
// "$ref": '#/definitions/SnapCreateResponse'
// default:
// description: unexpected error
// schema:
// "$ref": "#/definitions/SnapCreateResponse"
func (vd *volAPI) snap(w http.ResponseWriter, r *http.Request) {
var snapReq api.SnapCreateRequest
var snapRes api.SnapCreateResponse
method := "snap"
if err := json.NewDecoder(r.Body).Decode(&snapReq); err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
vd.logRequest(method, string(snapReq.Id)).Infoln("")
// Get context with auth token
ctx, err := vd.annotateContext(r)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
// Get gRPC connection
conn, err := vd.getConn()
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusInternalServerError)
return
}
volumes := api.NewOpenStorageVolumeClient(conn)
snapRes.VolumeCreateResponse = &api.VolumeCreateResponse{}
if snapReq.Readonly {
res, err := volumes.SnapshotCreate(ctx, &api.SdkVolumeSnapshotCreateRequest{VolumeId: snapReq.Id, Name: snapReq.Locator.Name, Labels: snapReq.Locator.VolumeLabels})
if err != nil {
snapRes.VolumeCreateResponse.VolumeResponse = &api.VolumeResponse{
Error: err.Error(),
}
} else {
snapRes.VolumeCreateResponse.Id = res.GetSnapshotId()
}
} else {
res, err := volumes.Clone(ctx, &api.SdkVolumeCloneRequest{ParentId: snapReq.Id, Name: snapReq.Locator.Name})
if err != nil {
snapRes.VolumeCreateResponse.VolumeResponse = &api.VolumeResponse{
Error: err.Error(),
}
} else {
snapRes.VolumeCreateResponse.Id = res.GetVolumeId()
}
}
json.NewEncoder(w).Encode(&snapRes)
}
// swagger:operation POST /osd-snapshots/restore/{id} snapshot restoreSnap
//
// Restore snapshot with specified id.
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id of snapshot to restore
// required: true
// type: integer
// responses:
// '200':
// description: Restored volume
// schema:
// "$ref": '#/definitions/VolumeResponse'
// default:
// description: unexpected error
// schema:
// "$ref": "#/definitions/VolumeResponse"
func (vd *volAPI) restore(w http.ResponseWriter, r *http.Request) {
var volumeID, snapID string
var err error
method := "restore"
if volumeID, err = vd.parseID(r); err != nil {
e := fmt.Errorf("Failed to parse parse volumeID: %s", err.Error())
vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
return
}
params := r.URL.Query()
v := params[api.OptSnapID]
if v != nil {
snapID = v[0]
} else {
vd.sendError(vd.name, method, w, "Missing "+api.OptSnapID+" param",
http.StatusBadRequest)
return
}
// Get context with auth token
ctx, err := vd.annotateContext(r)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
// Get gRPC connection
conn, err := vd.getConn()
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusInternalServerError)
return
}
volumeResponse := &api.VolumeResponse{}
volumes := api.NewOpenStorageVolumeClient(conn)
_, err = volumes.SnapshotRestore(ctx, &api.SdkVolumeSnapshotRestoreRequest{VolumeId: volumeID, SnapshotId: snapID})
if err != nil {
volumeResponse.Error = responseStatus(err)
}
json.NewEncoder(w).Encode(volumeResponse)
}
// swagger:operation GET /osd-snapshots snapshot enumerateSnaps
//
// Enumerate snapshots.
//
// ---
// consumes:
// - multipart/form-data
// produces:
// - application/json
// parameters:
// - name: name
// in: query
// description: Volume name that maps to this snap
// required: false
// type: string
// - name: VolumeLabels
// in: formData
// description: |
// Comma separated volume labels
// example: {"label1","label2"}
// required: false
// type: string
// - name: SnapLabels
// in: formData
// description: |
// Comma separated snap labels
// example: {"label1","label2"}
// required: false
// type: string
// - name: uuid
// in: query
// description: Snap UUID
// required: false
// type: string
// format: uuid
// responses:
// '200':
// description: an array of snapshots
// schema:
// type: array
// items:
// $ref: '#/definitions/Volume'
func (vd *volAPI) snapEnumerate(w http.ResponseWriter, r *http.Request) {
var err error
var labels map[string]string
var ids []string
method := "snapEnumerate"
params := r.URL.Query()
v := params[string(api.OptLabel)]
if v != nil {
if err = json.Unmarshal([]byte(v[0]), &labels); err != nil {
e := fmt.Errorf("Failed to parse parse VolumeLabels: %s", err.Error())
vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
}
}
v, ok := params[string(api.OptVolumeID)]
if v != nil && ok {
ids = make([]string, len(params))
for i, s := range v {
ids[i] = string(s)
}
}
request := &api.SdkVolumeSnapshotEnumerateWithFiltersRequest{}
if len(ids) > 0 {
request.VolumeId = ids[0]
}
if len(labels) > 0 {
request.Labels = labels
}
// Get context with auth token
ctx, err := vd.annotateContext(r)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
// Get gRPC connection
conn, err := vd.getConn()
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusInternalServerError)
return
}
volumes := api.NewOpenStorageVolumeClient(conn)
resp, err := volumes.SnapshotEnumerateWithFilters(ctx, request)
if err != nil {
e := fmt.Errorf("Failed to enumerate snaps: %s", err.Error())
vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
return
}
snaps := make([]*api.Volume, len(resp.GetVolumeSnapshotIds()))
for i, s := range resp.GetVolumeSnapshotIds() {
vol, err := volumes.Inspect(ctx, &api.SdkVolumeInspectRequest{VolumeId: s})
if err != nil {
e := fmt.Errorf("Failed to inspect volumeID: %s", err.Error())
vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
return
}
snaps[i] = vol.GetVolume()
}
json.NewEncoder(w).Encode(snaps)
}
// swagger:operation GET /osd-volumes/stats/{id} volume statsVolume
//
// Get stats for volume with specified id.
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id to get volume with
// required: true
// type: integer
// responses:
// '200':
// description: volume set response
// schema:
// "$ref": "#/definitions/Stats"
func (vd *volAPI) stats(w http.ResponseWriter, r *http.Request) {
var volumeID string
var err error
if volumeID, err = vd.parseID(r); err != nil {
e := fmt.Errorf("Failed to parse volumeID: %s", err.Error())
http.Error(w, e.Error(), http.StatusBadRequest)
return
}
params := r.URL.Query()
// By default always report /proc/diskstats style stats.
cumulative := true
if opt, ok := params[string(api.OptCumulative)]; ok {
if boolValue, err := strconv.ParseBool(strings.Join(opt[:], "")); !ok {
e := fmt.Errorf("Failed to parse %s option: %s",
api.OptCumulative, err.Error())
http.Error(w, e.Error(), http.StatusBadRequest)
return
} else {
cumulative = boolValue
}
}
d, err := vd.getVolDriver(r)
if err != nil {
notFound(w, r)
return
}
stats, err := d.Stats(volumeID, cumulative)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(stats)
}
/*
* Removed until we understand why this function if failing calling the SDK
*
func (vd *volAPI) stats(w http.ResponseWriter, r *http.Request) {
var volumeID string
var err error
var method = "stats"
if volumeID, err = vd.parseID(r); err != nil {
e := fmt.Errorf("Failed to parse volumeID: %s", err.Error())
http.Error(w, e.Error(), http.StatusBadRequest)
return
}
params := r.URL.Query()
// By default always report /proc/diskstats style stats.
cumulative := true
if opt, ok := params[string(api.OptCumulative)]; ok {
if boolValue, err := strconv.ParseBool(strings.Join(opt[:], "")); !ok {
e := fmt.Errorf("Failed to parse %s option: %s",
api.OptCumulative, err.Error())
http.Error(w, e.Error(), http.StatusBadRequest)
return
} else {
cumulative = boolValue
}
}
// Get context with auth token
ctx, err := vd.annotateContext(r)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
// Get gRPC connection
conn, err := vd.getConn()
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusInternalServerError)
return
}
volumes := api.NewOpenStorageVolumeClient(conn)
resp, err := volumes.Stats(ctx, &api.SdkVolumeStatsRequest{VolumeId: volumeID, NotCumulative: !cumulative})
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(resp.GetStats())
}
*/
// swagger:operation GET /osd-volumes/usedsize/{id} volume usedSizeVolume
//
// Get Used size of volume with specified id.
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id to get volume with
// required: true
// type: integer
// responses:
// '200':
// description: volume set response
// type: integer
// format: int64
func (vd *volAPI) usedsize(w http.ResponseWriter, r *http.Request) {
var volumeID string
var err error
if volumeID, err = vd.parseID(r); err != nil {
e := fmt.Errorf("Failed to parse volumeID: %s", err.Error())
http.Error(w, e.Error(), http.StatusBadRequest)
return
}
d, err := vd.getVolDriver(r)
if err != nil {
notFound(w, r)
return
}
used, err := d.UsedSize(volumeID)
if err != nil {
e := fmt.Errorf("Failed to get used size: %s", err.Error())
http.Error(w, e.Error(), http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(used)
}
/*
* Removed until we understand why this function if failing calling the SDK
*
func (vd *volAPI) usedsize(w http.ResponseWriter, r *http.Request) {
var volumeID string
var err error
var method = "usedsize"
if volumeID, err = vd.parseID(r); err != nil {
e := fmt.Errorf("Failed to parse volumeID: %s", err.Error())
http.Error(w, e.Error(), http.StatusBadRequest)
return
}
// Get context with auth token
ctx, err := vd.annotateContext(r)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
// Get gRPC connection
conn, err := vd.getConn()
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusInternalServerError)
return
}
volumes := api.NewOpenStorageVolumeClient(conn)
resp, err := volumes.CapacityUsage(ctx, &api.SdkVolumeCapacityUsageRequest{VolumeId: volumeID})
if err != nil {
e := fmt.Errorf("Failed to get used size: %s", err.Error())
http.Error(w, e.Error(), http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(resp.GetCapacityUsageInfo().TotalBytes)
}
*/
// swagger:operation POST /osd-volumes/requests/{id} volume requestsVolume
//
// Get Requests for volume with specified id.
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id to get volume with
// required: true
// type: integer
// responses:
// '200':
// description: volume set response
// schema:
// "$ref": "#/definitions/ActiveRequests"
func (vd *volAPI) requests(w http.ResponseWriter, r *http.Request) {
var err error
method := "requests"
d, err := vd.getVolDriver(r)
if err != nil {
notFound(w, r)
return
}
requests, err := d.GetActiveRequests()
if err != nil {
e := fmt.Errorf("Failed to get active requests: %s", err.Error())
vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(requests)
}
func (vd *volAPI) volumeusage(w http.ResponseWriter, r *http.Request) {
var err error
method := "volumeusage"
volumeID, err := vd.parseID(r)
if err != nil {
e := fmt.Errorf("Failed to parse volumeID: %s", err.Error())
http.Error(w, e.Error(), http.StatusBadRequest)
return
}
d, err := vd.getVolDriver(r)
if err != nil {
notFound(w, r)
return
}
capacityInfo, err := d.CapacityUsage(volumeID)
if err != nil || capacityInfo.Error != nil {
var e error
if err != nil {
e = fmt.Errorf("Failed to get CapacityUsage: %s", err.Error())
} else {
e = fmt.Errorf("Failed to get CapacityUsage: %s", capacityInfo.Error.Error())
}
vd.sendError(vd.name, method, w, e.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(capacityInfo)
}
// swagger:operation GET /osd-volumes/quiesce/{id} volume quiesceVolume
//
// Quiesce volume with specified id.
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id to get volume with
// required: true
// type: integer
// responses:
// '200':
// description: volume set response
// schema:
// "$ref": "#/definitions/VolumeResponse"
// default:
// description: unexpected error
// schema:
// "$ref": "#/definitions/VolumeResponse"
func (vd *volAPI) quiesce(w http.ResponseWriter, r *http.Request) {
var volumeID string
var err error
method := "quiesce"
if volumeID, err = vd.parseID(r); err != nil {
e := fmt.Errorf("Failed to parse parse volumeID: %s", err.Error())
vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
return
}
d, err := vd.getVolDriver(r)
if err != nil {
notFound(w, r)
return
}
params := r.URL.Query()
timeoutStr := params[api.OptTimeoutSec]
var timeoutSec uint64
if timeoutStr != nil {
var err error
timeoutSec, err = strconv.ParseUint(timeoutStr[0], 10, 64)
if err != nil {
vd.sendError(vd.name, method, w, api.OptTimeoutSec+" must be int",
http.StatusBadRequest)
return
}
}
quiesceIdParam := params[api.OptQuiesceID]
var quiesceId string
if len(quiesceIdParam) > 0 {
quiesceId = quiesceIdParam[0]
}
volumeResponse := &api.VolumeResponse{}
if err := d.Quiesce(volumeID, timeoutSec, quiesceId); err != nil {
volumeResponse.Error = responseStatus(err)
}
json.NewEncoder(w).Encode(volumeResponse)
}
// swagger:operation POST /osd-volumes/unquiesce/{id} volume unquiesceVolume
//
// Unquiesce volume with specified id.
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id to get volume with
// required: true
// type: integer
// responses:
// '200':
// description: volume set response
// schema:
// "$ref": "#/definitions/VolumeResponse"
// default:
// description: unexpected error
// schema:
// "$ref": "#/definitions/VolumeResponse"
func (vd *volAPI) unquiesce(w http.ResponseWriter, r *http.Request) {
var volumeID string
var err error
method := "unquiesce"
if volumeID, err = vd.parseID(r); err != nil {
e := fmt.Errorf("Failed to parse parse volumeID: %s", err.Error())
vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
return
}
d, err := vd.getVolDriver(r)
if err != nil {
notFound(w, r)
return
}
volumeResponse := &api.VolumeResponse{}
if err := d.Unquiesce(volumeID); err != nil {
volumeResponse.Error = responseStatus(err)
}
json.NewEncoder(w).Encode(volumeResponse)
}
// swagger:operation POST /osd-snapshots/groupsnap volumegroup snapVolumeGroup
//
// Take a snapshot of volumegroup
//
// ---
// produces:
// - application/json
// parameters:
// - name: groupspec
// in: body
// description: GroupSnap create request
// required: true
// schema:
// "$ref": "#/definitions/GroupSnapCreateRequest"
// responses:
// '200':
// description: group snap create response
// schema:
// "$ref": "#/definitions/GroupSnapCreateResponse"
// default:
// description: unexpected error
// schema:
// "$ref": "#/definitions/GroupSnapCreateResponse"
func (vd *volAPI) snapGroup(w http.ResponseWriter, r *http.Request) {
var snapReq api.GroupSnapCreateRequest
var snapRes *api.GroupSnapCreateResponse
method := "snapGroup"
if err := json.NewDecoder(r.Body).Decode(&snapReq); err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
d, err := vd.getVolDriver(r)
if err != nil {
notFound(w, r)
return
}
snapRes, err = d.SnapshotGroup(snapReq.Id, snapReq.Labels, snapReq.VolumeIds)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(&snapRes)
}
// swagger:operation GET /osd-volumes/versions volume listVersions
//
// Lists API versions supported by this volumeDriver.
//
// ---
// produces:
// - application/json
// responses:
// '200':
// description: Supported versions
// schema:
// type: array
// items:
// type: string
func (vd *volAPI) versions(w http.ResponseWriter, r *http.Request) {
versions := []string{
volume.APIVersion,
// Update supported versions by adding them here
}
json.NewEncoder(w).Encode(versions)
}
// swagger:operation GET /osd-volumes/catalog/{id} volume catalogVolume
//
// Catalog lists the files and folders on volume with specified id.
// Path is optional and default the behaviour is a catalog on the root of the volume.
//
// ---
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id to get volume with
// required: true
// type: integer
// - name: subfolder
// in: query
// description: Optional path inside mount to catalog.
// required: false
// type: string
// - name: depth
// in: query
// description: Folder depth we wish to return, default is all.
// required: false
// type: string
// responses:
// '200':
// description: volume catalog response
// schema:
// $ref: '#/definitions/CatalogResponse'
func (vd *volAPI) catalog(w http.ResponseWriter, r *http.Request) {
var err error
var volumeID string
var subfolder string
var depth = "0"
method := "catalog"
d, err := vd.getVolDriver(r)
if err != nil {
fmt.Println("Volume not found")
notFound(w, r)
return
}
if volumeID, err = vd.parseParam(r, "id"); err != nil {
e := fmt.Errorf("Failed to parse ID: %s", err.Error())
vd.sendError(vd.name, method, w, e.Error(), http.StatusBadRequest)
return
}
params := r.URL.Query()
folderParam := params[string(api.OptCatalogSubFolder)]
if len(folderParam) > 0 {
subfolder = folderParam[0]
}
depthParam := params[string(api.OptCatalogMaxDepth)]
if len(depthParam) > 0 {
depth = depthParam[0]
}
dk, err := d.Catalog(volumeID, subfolder, depth)
if err != nil {
vd.sendError(vd.name, method, w, err.Error(), http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(dk)
}
func volVersion(route, version string) string {
if version == "" {
return "/" + route
} else {
return "/" + version + "/" + route
}
}
func volPath(route, version string) string {
return volVersion(api.OsdVolumePath+route, version)
}
func snapPath(route, version string) string {
return volVersion(api.OsdSnapshotPath+route, version)
}
func credsPath(route, version string) string {
return volVersion(api.OsdCredsPath+route, version)
}
func backupPath(route, version string) string {
return volVersion(api.OsdBackupPath+route, version)
}
func migratePath(route, version string) string {
return volVersion(route, version)
}
func (vd *volAPI) versionRoute() *Route {
return &Route{verb: "GET", path: "/" + api.OsdVolumePath + "/versions", fn: vd.versions}
}
func (vd *volAPI) volumeCreateRoute() *Route {
return &Route{verb: "POST", path: volPath("", volume.APIVersion), fn: vd.create}
}
func (vd *volAPI) volumeDeleteRoute() *Route {
return &Route{verb: "DELETE", path: volPath("/{id}", volume.APIVersion), fn: vd.delete}
}
func (vd *volAPI) volumeSetRoute() *Route {
return &Route{verb: "PUT", path: volPath("/{id}", volume.APIVersion), fn: vd.volumeSet}
}
func (vd *volAPI) volumeInspectRoute() *Route {
return &Route{verb: "GET", path: volPath("/{id}", volume.APIVersion), fn: vd.inspect}
}
func (vd *volAPI) otherVolumeRoutes() []*Route {
return []*Route{
{verb: "GET", path: volPath("", volume.APIVersion), fn: vd.enumerate},
{verb: "GET", path: volPath("/stats", volume.APIVersion), fn: vd.stats},
{verb: "GET", path: volPath("/stats/{id}", volume.APIVersion), fn: vd.stats},
{verb: "GET", path: volPath("/usedsize", volume.APIVersion), fn: vd.usedsize},
{verb: "GET", path: volPath("/usedsize/{id}", volume.APIVersion), fn: vd.usedsize},
{verb: "GET", path: volPath("/requests", volume.APIVersion), fn: vd.requests},
{verb: "GET", path: volPath("/requests/{id}", volume.APIVersion), fn: vd.requests},
{verb: "GET", path: volPath("/usage", volume.APIVersion), fn: vd.volumeusage},
{verb: "GET", path: volPath("/usage/{id}", volume.APIVersion), fn: vd.volumeusage},
{verb: "POST", path: volPath("/quiesce/{id}", volume.APIVersion), fn: vd.quiesce},
{verb: "POST", path: volPath("/unquiesce/{id}", volume.APIVersion), fn: vd.unquiesce},
{verb: "GET", path: volPath("/catalog/{id}", volume.APIVersion), fn: vd.catalog},
}
}
func (vd *volAPI) backupRoutes() []*Route {
return []*Route{
{verb: "POST", path: backupPath("", volume.APIVersion), fn: vd.cloudBackupCreate},
{verb: "POST", path: backupPath("/group", volume.APIVersion), fn: vd.cloudBackupGroupCreate},
{verb: "POST", path: backupPath("/restore", volume.APIVersion), fn: vd.cloudBackupRestore},
{verb: "GET", path: backupPath("", volume.APIVersion), fn: vd.cloudBackupEnumerate},
{verb: "DELETE", path: backupPath("", volume.APIVersion), fn: vd.cloudBackupDelete},
{verb: "DELETE", path: backupPath("/all", volume.APIVersion), fn: vd.cloudBackupDeleteAll},
{verb: "GET", path: backupPath("/status", volume.APIVersion), fn: vd.cloudBackupStatus},
{verb: "GET", path: backupPath("/catalog", volume.APIVersion), fn: vd.cloudBackupCatalog},
{verb: "GET", path: backupPath("/history", volume.APIVersion), fn: vd.cloudBackupHistory},
{verb: "PUT", path: backupPath("/statechange", volume.APIVersion), fn: vd.cloudBackupStateChange},
{verb: "POST", path: backupPath("/sched", volume.APIVersion), fn: vd.cloudBackupSchedCreate},
{verb: "POST", path: backupPath("/schedgroup", volume.APIVersion), fn: vd.cloudBackupGroupSchedCreate},
{verb: "DELETE", path: backupPath("/sched", volume.APIVersion), fn: vd.cloudBackupSchedDelete},
{verb: "GET", path: backupPath("/sched", volume.APIVersion), fn: vd.cloudBackupSchedEnumerate},
}
}
func (vd *volAPI) credsRoutes() []*Route {
return []*Route{
{verb: "GET", path: credsPath("", volume.APIVersion), fn: vd.credsEnumerate},
{verb: "POST", path: credsPath("", volume.APIVersion), fn: vd.credsCreate},
{verb: "DELETE", path: credsPath("/{uuid}", volume.APIVersion), fn: vd.credsDelete},
{verb: "PUT", path: credsPath("/validate/{uuid}", volume.APIVersion), fn: vd.credsValidate},
}
}
func (vd *volAPI) migrateRoutes() []*Route {
return []*Route{
{verb: "POST", path: migratePath(api.OsdMigrateStartPath, volume.APIVersion), fn: vd.cloudMigrateStart},
{verb: "POST", path: migratePath(api.OsdMigrateCancelPath, volume.APIVersion), fn: vd.cloudMigrateCancel},
{verb: "GET", path: migratePath(api.OsdMigrateStatusPath, volume.APIVersion), fn: vd.cloudMigrateStatus},
}
}
func (vd *volAPI) snapRoutes() []*Route {
return []*Route{
{verb: "POST", path: snapPath("", volume.APIVersion), fn: vd.snap},
{verb: "GET", path: snapPath("", volume.APIVersion), fn: vd.snapEnumerate},
{verb: "POST", path: snapPath("/restore/{id}", volume.APIVersion), fn: vd.restore},
{verb: "POST", path: snapPath("/snapshotgroup", volume.APIVersion), fn: vd.snapGroup},
}
}
func (vd *volAPI) Routes() []*Route {
routes := []*Route{vd.versionRoute(), vd.volumeCreateRoute(), vd.volumeSetRoute(), vd.volumeDeleteRoute(), vd.volumeInspectRoute()}
routes = append(routes, vd.otherVolumeRoutes()...)
routes = append(routes, vd.snapRoutes()...)
routes = append(routes, vd.backupRoutes()...)
routes = append(routes, vd.credsRoutes()...)
routes = append(routes, vd.migrateRoutes()...)
return routes
}
func (vd *volAPI) SetupRoutesWithAuth(
router *mux.Router,
authProviderType secrets.AuthTokenProviders,
authProvider osecrets.Secrets,
) (*mux.Router, error) {
// We setup auth middlewares for all the APIs that get invoked
// from a Container Orchestrator.
// - CREATE
// - ATTACH/MOUNT
// - DETACH/UNMOUNT
// - DELETE
// For all other routes it is expected that the REST client uses an auth token
authM, err := NewAuthMiddleware(authProvider, authProviderType)
if err != nil {
return router, err
}
// Setup middleware for Create
nCreate := negroni.New()
nCreate.Use(negroni.HandlerFunc(authM.createWithAuth))
createRoute := vd.volumeCreateRoute()
nCreate.UseHandlerFunc(createRoute.fn)
router.Methods(createRoute.verb).Path(createRoute.path).Handler(nCreate)
// Setup middleware for Delete
nDelete := negroni.New()
nDelete.Use(negroni.HandlerFunc(authM.deleteWithAuth))
deleteRoute := vd.volumeDeleteRoute()
nDelete.UseHandlerFunc(deleteRoute.fn)
router.Methods(deleteRoute.verb).Path(deleteRoute.path).Handler(nDelete)
// Setup middleware for Set
nSet := negroni.New()
nSet.Use(negroni.HandlerFunc(authM.setWithAuth))
setRoute := vd.volumeSetRoute()
nSet.UseHandlerFunc(setRoute.fn)
router.Methods(setRoute.verb).Path(setRoute.path).Handler(nSet)
// Setup middleware for Inspect
nInspect := negroni.New()
nInspect.Use(negroni.HandlerFunc(authM.inspectWithAuth))
inspectRoute := vd.volumeInspectRoute()
nSet.UseHandlerFunc(inspectRoute.fn)
router.Methods(inspectRoute.verb).Path(inspectRoute.path).Handler(nInspect)
routes := []*Route{vd.versionRoute()}
routes = append(routes, vd.otherVolumeRoutes()...)
routes = append(routes, vd.snapRoutes()...)
routes = append(routes, vd.backupRoutes()...)
routes = append(routes, vd.credsRoutes()...)
routes = append(routes, vd.migrateRoutes()...)
for _, v := range routes {
router.Methods(v.verb).Path(v.path).HandlerFunc(v.fn)
}
return router, nil
}
// GetVolumeAPIRoutes returns all the volume routes.
// A driver could use this function if it does not want openstorage
// to setup the REST server but it sets up its own and wants to add
// volume routes
func GetVolumeAPIRoutes(name, sdkUds string) []*Route {
volMgmtApi := newVolumeAPI(name, sdkUds)
return volMgmtApi.Routes()
}
// ServerRegisterRoute is a callback function used by drivers to run their
// preRouteChecks before the actual volume route gets invoked
// This is added for legacy support before negroni middleware was added
type ServerRegisterRoute func(
routeFunc func(w http.ResponseWriter, r *http.Request),
preRouteCheck func(w http.ResponseWriter, r *http.Request) bool,
) func(w http.ResponseWriter, r *http.Request)
// GetVolumeAPIRoutesWithAuth returns a router with all the volume routes
// added to the router along with the auth middleware
// - preRouteCheckFn is a handler that gets executed before the actual volume handler
// is invoked. It is added for legacy support where negroni middleware was not used
func GetVolumeAPIRoutesWithAuth(
name, sdkUds string,
authProviderType secrets.AuthTokenProviders,
authProvider osecrets.Secrets,
router *mux.Router,
serverRegisterRoute ServerRegisterRoute,
preRouteCheckFn func(http.ResponseWriter, *http.Request) bool,
) (*mux.Router, error) {
vd := &volAPI{
restBase: restBase{version: volume.APIVersion, name: name},
sdkUds: sdkUds,
dummyMux: runtime.NewServeMux(),
}
authM, err := NewAuthMiddleware(authProvider, authProviderType)
if err != nil {
return router, err
}
// We setup auth middlewares for all the APIs that get invoked
// from a Container Orchestrator.
// - CREATE
// - ATTACH/MOUNT
// - DETACH/UNMOUNT
// - DELETE
// For all other routes it is expected that the REST client uses an auth token
// Setup middleware for Create
nCreate := negroni.New()
nCreate.Use(negroni.HandlerFunc(authM.createWithAuth))
createRoute := vd.volumeCreateRoute()
nCreate.UseHandlerFunc(serverRegisterRoute(createRoute.fn, preRouteCheckFn))
router.Methods(createRoute.verb).Path(createRoute.path).Handler(nCreate)
// Setup middleware for Delete
nDelete := negroni.New()
nDelete.Use(negroni.HandlerFunc(authM.deleteWithAuth))
deleteRoute := vd.volumeDeleteRoute()
nDelete.UseHandlerFunc(serverRegisterRoute(deleteRoute.fn, preRouteCheckFn))
router.Methods(deleteRoute.verb).Path(deleteRoute.path).Handler(nDelete)
// Setup middleware for Set
nSet := negroni.New()
nSet.Use(negroni.HandlerFunc(authM.setWithAuth))
setRoute := vd.volumeSetRoute()
nSet.UseHandlerFunc(serverRegisterRoute(setRoute.fn, preRouteCheckFn))
router.Methods(setRoute.verb).Path(setRoute.path).Handler(nSet)
// Setup middleware for Inspect
nInspect := negroni.New()
nInspect.Use(negroni.HandlerFunc(authM.inspectWithAuth))
inspectRoute := vd.volumeInspectRoute()
nInspect.UseHandlerFunc(serverRegisterRoute(inspectRoute.fn, preRouteCheckFn))
router.Methods(inspectRoute.verb).Path(inspectRoute.path).Handler(nInspect)
routes := []*Route{vd.versionRoute()}
routes = append(routes, vd.otherVolumeRoutes()...)
routes = append(routes, vd.snapRoutes()...)
routes = append(routes, vd.backupRoutes()...)
routes = append(routes, vd.credsRoutes()...)
routes = append(routes, vd.migrateRoutes()...)
for _, v := range routes {
router.Methods(v.verb).Path(v.path).HandlerFunc(serverRegisterRoute(v.fn, preRouteCheckFn))
}
return router, nil
}
| 1 | 8,124 | Instead of blindly ignoring all errors, this should just ignore the volume not found error. | libopenstorage-openstorage | go |
@@ -135,11 +135,9 @@ public class ParquetReader<T> extends CloseableGroup implements CloseableIterabl
throw new RuntimeIOException(e);
}
- long rowPosition = rowGroupsStartRowPos[nextRowGroup];
+ model.setPageSource(pages, rowGroupsStartRowPos == null ? 0 : rowGroupsStartRowPos[nextRowGroup]);
nextRowGroupStart += pages.getRowCount();
nextRowGroup += 1;
-
- model.setPageSource(pages, rowPosition);
}
@Override | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iceberg.parquet;
import java.io.IOException;
import java.util.function.Function;
import org.apache.iceberg.Schema;
import org.apache.iceberg.exceptions.RuntimeIOException;
import org.apache.iceberg.expressions.Expression;
import org.apache.iceberg.expressions.Expressions;
import org.apache.iceberg.io.CloseableGroup;
import org.apache.iceberg.io.CloseableIterable;
import org.apache.iceberg.io.CloseableIterator;
import org.apache.iceberg.io.InputFile;
import org.apache.iceberg.mapping.NameMapping;
import org.apache.parquet.ParquetReadOptions;
import org.apache.parquet.column.page.PageReadStore;
import org.apache.parquet.hadoop.ParquetFileReader;
import org.apache.parquet.schema.MessageType;
public class ParquetReader<T> extends CloseableGroup implements CloseableIterable<T> {
private final InputFile input;
private final Schema expectedSchema;
private final ParquetReadOptions options;
private final Function<MessageType, ParquetValueReader<?>> readerFunc;
private final Expression filter;
private final boolean reuseContainers;
private final boolean caseSensitive;
private final NameMapping nameMapping;
public ParquetReader(InputFile input, Schema expectedSchema, ParquetReadOptions options,
Function<MessageType, ParquetValueReader<?>> readerFunc, NameMapping nameMapping,
Expression filter, boolean reuseContainers, boolean caseSensitive) {
this.input = input;
this.expectedSchema = expectedSchema;
this.options = options;
this.readerFunc = readerFunc;
// replace alwaysTrue with null to avoid extra work evaluating a trivial filter
this.filter = filter == Expressions.alwaysTrue() ? null : filter;
this.reuseContainers = reuseContainers;
this.caseSensitive = caseSensitive;
this.nameMapping = nameMapping;
}
private ReadConf<T> conf = null;
private ReadConf<T> init() {
if (conf == null) {
ReadConf<T> readConf = new ReadConf<>(
input, options, expectedSchema, filter, readerFunc, null, nameMapping, reuseContainers,
caseSensitive, null);
this.conf = readConf.copy();
return readConf;
}
return conf;
}
@Override
public CloseableIterator<T> iterator() {
FileIterator<T> iter = new FileIterator<>(init());
addCloseable(iter);
return iter;
}
private static class FileIterator<T> implements CloseableIterator<T> {
private final ParquetFileReader reader;
private final boolean[] shouldSkip;
private final ParquetValueReader<T> model;
private final long totalValues;
private final boolean reuseContainers;
private final long[] rowGroupsStartRowPos;
private int nextRowGroup = 0;
private long nextRowGroupStart = 0;
private long valuesRead = 0;
private T last = null;
FileIterator(ReadConf<T> conf) {
this.reader = conf.reader();
this.shouldSkip = conf.shouldSkip();
this.model = conf.model();
this.totalValues = conf.totalValues();
this.reuseContainers = conf.reuseContainers();
this.rowGroupsStartRowPos = conf.startRowPositions();
}
@Override
public boolean hasNext() {
return valuesRead < totalValues;
}
@Override
public T next() {
if (valuesRead >= nextRowGroupStart) {
advance();
}
if (reuseContainers) {
this.last = model.read(last);
} else {
this.last = model.read(null);
}
valuesRead += 1;
return last;
}
private void advance() {
while (shouldSkip[nextRowGroup]) {
nextRowGroup += 1;
reader.skipNextRowGroup();
}
PageReadStore pages;
try {
pages = reader.readNextRowGroup();
} catch (IOException e) {
throw new RuntimeIOException(e);
}
long rowPosition = rowGroupsStartRowPos[nextRowGroup];
nextRowGroupStart += pages.getRowCount();
nextRowGroup += 1;
model.setPageSource(pages, rowPosition);
}
@Override
public void close() throws IOException {
reader.close();
}
}
}
| 1 | 27,347 | The `rowPosition` will be ignored if the position column is not projected. | apache-iceberg | java |
@@ -215,6 +215,16 @@ spec:
protocol: TCP
- containerPort: 3232
protocol: TCP
+ livenessProbe:
+ exec:
+ command:
+ - /bin/sh
+ - -c
+ - zfs set io.openebs:livenesstimestap='$(date)' cstor-$OPENEBS_IO_CSTOR_ID
+ failureThreshold: 3
+ initialDelaySeconds: 300
+ periodSeconds: 10
+ timeoutSeconds: 30
securityContext:
privileged: true
volumeMounts: | 1 | /*
Copyright 2018 The OpenEBS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// TODO
// Rename this file by removing the version suffix information
package v1alpha1
const cstorPoolYamls = `
---
apiVersion: openebs.io/v1alpha1
kind: CASTemplate
metadata:
name: cstor-pool-create-default
spec:
defaultConfig:
# CstorPoolImage is the container image that executes zpool replication and
# communicates with cstor iscsi target
- name: CstorPoolImage
value: {{env "OPENEBS_IO_CSTOR_POOL_IMAGE" | default "openebs/cstor-pool:latest"}}
# CstorPoolMgmtImage runs cstor pool and cstor volume replica related CRUD
# operations
- name: CstorPoolMgmtImage
value: {{env "OPENEBS_IO_CSTOR_POOL_MGMT_IMAGE" | default "openebs/cstor-pool-mgmt:latest"}}
# HostPathType is a hostPath volume i.e. mounts a file or directory from the
# host node’s filesystem into a Pod. 'DirectoryOrCreate' value ensures
# nothing exists at the given path i.e. an empty directory will be created.
- name: HostPathType
value: DirectoryOrCreate
# SparseDir is a hostPath directory where to look for sparse files
- name: SparseDir
value: {{env "OPENEBS_IO_CSTOR_POOL_SPARSE_DIR" | default "/var/openebs/sparse"}}
# RunNamespace is the namespace where namespaced resources related to pool
# will be placed
- name: RunNamespace
value: {{env "OPENEBS_NAMESPACE"}}
# ServiceAccountName is the account name assigned to pool management pod
# with permissions to view, create, edit, delete required custom resources
- name: ServiceAccountName
value: {{env "OPENEBS_SERVICE_ACCOUNT"}}
# PoolResourceRequests allow you to specify resource requests that need to be available
# before scheduling the containers. If not specified, the default is to use the limits
# from PoolResourceLimits or the default requests set in the cluster.
- name: PoolResourceRequests
value: "none"
# PoolResourceLimits allow you to set the limits on memory and cpu for pool pods
# The resource and limit value should be in the same format as expected by
# Kubernetes. Example:
#- name: PoolResourceLimits
# value: |-
# memory: 1Gi
- name: PoolResourceLimits
value: "none"
# AuxResourceRequests allow you to set requests on side cars. Requests have to be specified
# in the format expected by Kubernetes
- name: AuxResourceRequests
value: "none"
# AuxResourceLimits allow you to set limits on side cars. Limits have to be specified
# in the format expected by Kubernetes
- name: AuxResourceLimits
value: "none"
# ResyncInterval specifies duration after which a controller should
# resync the resource status
- name: ResyncInterval
value: "30"
taskNamespace: {{env "OPENEBS_NAMESPACE"}}
run:
tasks:
# Following are the list of run tasks executed in this order to
# create a cstor storage pool
- cstor-pool-create-putcstorpoolcr-default
- cstor-pool-create-putcstorpooldeployment-default
- cstor-pool-create-putstoragepoolcr-default
- cstor-pool-create-patchstoragepoolclaim-default
---
apiVersion: openebs.io/v1alpha1
kind: CASTemplate
metadata:
name: cstor-pool-delete-default
spec:
defaultConfig:
# RunNamespace is the namespace to use to delete pool resources
- name: RunNamespace
value: {{env "OPENEBS_NAMESPACE"}}
taskNamespace: {{env "OPENEBS_NAMESPACE"}}
run:
tasks:
# Following are run tasks executed in this order to delete a storage pool
- cstor-pool-delete-listcstorpoolcr-default
- cstor-pool-delete-deletecstorpoolcr-default
- cstor-pool-delete-listcstorpooldeployment-default
- cstor-pool-delete-deletecstorpooldeployment-default
- cstor-pool-delete-liststoragepoolcr-default
- cstor-pool-delete-deletestoragepoolcr-default
---
apiVersion: openebs.io/v1alpha1
kind: RunTask
metadata:
name: cstor-pool-create-putcstorpoolcr-default
spec:
meta: |
apiVersion: openebs.io/v1alpha1
kind: CStorPool
action: put
id: putcstorpoolcr
post: |
{{- jsonpath .JsonResult "{.metadata.name}" | trim | addTo "putcstorpoolcr.objectName" .TaskResult | noop -}}
{{- jsonpath .JsonResult "{.metadata.uid}" | trim | addTo "putcstorpoolcr.objectUID" .TaskResult | noop -}}
{{- jsonpath .JsonResult "{.metadata.labels.kubernetes\\.io/hostname}" | trim | addTo "putcstorpoolcr.nodeName" .TaskResult | noop -}}
task: |-
{{- $diskDeviceIdList:= .Storagepool.diskDeviceIdList }}
apiVersion: openebs.io/v1alpha1
kind: CStorPool
metadata:
name: {{.Storagepool.owner}}-{{randAlphaNum 4 |lower }}
labels:
openebs.io/storage-pool-claim: {{.Storagepool.owner}}
kubernetes.io/hostname: {{.Storagepool.nodeName}}
openebs.io/version: {{ .CAST.version }}
openebs.io/cas-template-name: {{ .CAST.castName }}
spec:
disks:
diskList:
{{- range $k, $deviceID := $diskDeviceIdList }}
- {{ $deviceID }}
{{- end }}
poolSpec:
poolType: {{.Storagepool.poolType}}
cacheFile: /tmp/{{.Storagepool.owner}}.cache
overProvisioning: false
status:
phase: Init
---
apiVersion: openebs.io/v1alpha1
kind: RunTask
metadata:
name: cstor-pool-create-putcstorpooldeployment-default
spec:
meta: |
runNamespace: {{.Config.RunNamespace.value}}
apiVersion: extensions/v1beta1
kind: Deployment
action: put
id: putcstorpooldeployment
post: |
{{- jsonpath .JsonResult "{.metadata.name}" | trim | addTo "putcstorpooldeployment.objectName" .TaskResult | noop -}}
task: |-
{{- $setResourceRequests := .Config.PoolResourceRequests.value | default "none" -}}
{{- $resourceRequestsVal := fromYaml .Config.PoolResourceRequests.value -}}
{{- $setResourceLimits := .Config.PoolResourceLimits.value | default "none" -}}
{{- $resourceLimitsVal := fromYaml .Config.PoolResourceLimits.value -}}
{{- $setAuxResourceRequests := .Config.AuxResourceRequests.value | default "none" -}}
{{- $auxResourceRequestsVal := fromYaml .Config.AuxResourceRequests.value -}}
{{- $setAuxResourceLimits := .Config.AuxResourceLimits.value | default "none" -}}
{{- $auxResourceLimitsVal := fromYaml .Config.AuxResourceLimits.value -}}
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: {{.TaskResult.putcstorpoolcr.objectName}}
labels:
openebs.io/storage-pool-claim: {{.Storagepool.owner}}
openebs.io/cstor-pool: {{.TaskResult.putcstorpoolcr.objectName}}
app: cstor-pool
openebs.io/version: {{ .CAST.version }}
openebs.io/cas-template-name: {{ .CAST.castName }}
spec:
strategy:
type: Recreate
replicas: 1
selector:
matchLabels:
app: cstor-pool
template:
metadata:
labels:
app: cstor-pool
openebs.io/storage-pool-claim: {{.Storagepool.owner}}
spec:
serviceAccountName: {{ .Config.ServiceAccountName.value }}
nodeSelector:
kubernetes.io/hostname: {{.Storagepool.nodeName}}
containers:
- name: cstor-pool
image: {{ .Config.CstorPoolImage.value }}
resources:
{{- if ne $setResourceLimits "none" }}
limits:
{{- range $rKey, $rLimit := $resourceLimitsVal }}
{{ $rKey }}: {{ $rLimit }}
{{- end }}
{{- end }}
{{- if ne $setResourceRequests "none" }}
requests:
{{- range $rKey, $rReq := $resourceRequestsVal }}
{{ $rKey }}: {{ $rReq }}
{{- end }}
{{- end }}
ports:
- containerPort: 12000
protocol: TCP
- containerPort: 3233
protocol: TCP
- containerPort: 3232
protocol: TCP
securityContext:
privileged: true
volumeMounts:
- name: device
mountPath: /dev
- name: tmp
mountPath: /tmp
- name: sparse
mountPath: {{ .Config.SparseDir.value }}
- name: udev
mountPath: /run/udev
# To avoid clash between terminating and restarting pod
# in case older zrepl gets deleted faster, we keep initial delay
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "sleep 2"]
- name: cstor-pool-mgmt
image: {{ .Config.CstorPoolMgmtImage.value }}
resources:
{{- if ne $setAuxResourceRequests "none" }}
requests:
{{- range $rKey, $rLimit := $auxResourceRequestsVal }}
{{ $rKey }}: {{ $rLimit }}
{{- end }}
{{- end }}
{{- if ne $setAuxResourceLimits "none" }}
limits:
{{- range $rKey, $rLimit := $auxResourceLimitsVal }}
{{ $rKey }}: {{ $rLimit }}
{{- end }}
{{- end }}
ports:
- containerPort: 9500
protocol: TCP
securityContext:
privileged: true
volumeMounts:
- name: device
mountPath: /dev
- name: tmp
mountPath: /tmp
- name: sparse
mountPath: {{ .Config.SparseDir.value }}
- name: udev
mountPath: /run/udev
env:
# OPENEBS_IO_CSTOR_ID env has UID of cStorPool CR.
- name: OPENEBS_IO_CSTOR_ID
value: {{.TaskResult.putcstorpoolcr.objectUID}}
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: RESYNC_INTERVAL
value: {{ .Config.ResyncInterval.value }}
volumes:
- name: device
hostPath:
# directory location on host
path: /dev
# this field is optional
type: Directory
- name: tmp
hostPath:
# From host, dir called /var/openebs/shared-<uid> is created to avoid clash if two replicas run on same node.
path: /var/openebs/shared-{{.Storagepool.owner}}
type: {{ .Config.HostPathType.value }}
- name: sparse
hostPath:
path: {{ .Config.SparseDir.value }}
type: {{ .Config.HostPathType.value }}
- name: udev
hostPath:
path: /run/udev
type: Directory
---
apiVersion: openebs.io/v1alpha1
kind: RunTask
metadata:
name: cstor-pool-create-putstoragepoolcr-default
spec:
meta: |
apiVersion: openebs.io/v1alpha1
kind: StoragePool
action: put
id: putstoragepool
post: |
{{- jsonpath .JsonResult "{.metadata.name}" | trim | addTo "putstoragepool.objectName" .TaskResult | noop -}}
task: |-
{{- $diskList:= .Storagepool.diskList }}
apiVersion: openebs.io/v1alpha1
kind: StoragePool
metadata:
name: {{.TaskResult.putcstorpooldeployment.objectName}}
labels:
openebs.io/storage-pool-claim: {{.Storagepool.owner}}
openebs.io/cstor-pool: {{.TaskResult.putcstorpooldeployment.objectName}}
openebs.io/cas-type: cstor
kubernetes.io/hostname: {{ .Storagepool.nodeName}}
openebs.io/version: {{ .CAST.version }}
openebs.io/cas-template-name: {{ .CAST.castName }}
spec:
disks:
diskList:
{{- range $k, $diskName := $diskList }}
- {{ $diskName }}
{{- end }}
poolSpec:
poolType: {{.Storagepool.poolType}}
cacheFile: /tmp/{{.Storagepool.owner}}.cache
overProvisioning: false
---
apiVersion: openebs.io/v1alpha1
kind: RunTask
metadata:
name: cstor-pool-create-patchstoragepoolclaim-default
spec:
meta: |
id: patchstoragepoolclaim
apiVersion: openebs.io/v1alpha1
kind: StoragePoolClaim
objectName: {{.Storagepool.owner}}
action: patch
task: |-
type: merge
pspec: |-
status:
phase: Online
---
# This run task lists all cstor pool CRs that need to be deleted
apiVersion: openebs.io/v1alpha1
kind: RunTask
metadata:
name: cstor-pool-delete-listcstorpoolcr-default
spec:
meta: |
id: listcstorpoolcr
apiVersion: openebs.io/v1alpha1
kind: CStorPool
action: list
options: |-
labelSelector: openebs.io/storage-pool-claim={{.Storagepool.owner}}
post: |
{{- $csps := jsonpath .JsonResult "{range .items[*]}pkey=csps,{@.metadata.name}=;{end}" | trim | default "" | splitList ";" -}}
{{- $csps | notFoundErr "cstor pool cr not found" | saveIf "listcstorpoolcr.notFoundErr" .TaskResult | noop -}}
{{- $csps | keyMap "csplist" .ListItems | noop -}}
---
# This run task delete all the required cstor pool CR
apiVersion: openebs.io/v1alpha1
kind: RunTask
metadata:
name: cstor-pool-delete-deletecstorpoolcr-default
spec:
meta: |
apiVersion: openebs.io/v1alpha1
kind: CStorPool
action: delete
id: deletecstorpoolcr
objectName: {{ keys .ListItems.csplist.csps | join "," }}
---
# This run task lists all the required cstor pool deployments that need to be deleted
apiVersion: openebs.io/v1alpha1
kind: RunTask
metadata:
name: cstor-pool-delete-listcstorpooldeployment-default
spec:
meta: |
id: listcstorpooldeployment
apiVersion: extensions/v1beta1
runNamespace: {{.Config.RunNamespace.value}}
kind: Deployment
action: list
options: |-
labelSelector: openebs.io/storage-pool-claim={{.Storagepool.owner}}
post: |
{{- $csds := jsonpath .JsonResult "{range .items[*]}pkey=csds,{@.metadata.name}=;{end}" | trim | default "" | splitList ";" -}}
{{- $csds | notFoundErr "cstor pool deployment not found" | saveIf "listcstorpooldeployment.notFoundErr" .TaskResult | noop -}}
{{- $csds | keyMap "csdlist" .ListItems | noop -}}
---
# This run task deletes all the required cstor pool deployments
apiVersion: openebs.io/v1alpha1
kind: RunTask
metadata:
name: cstor-pool-delete-deletecstorpooldeployment-default
spec:
meta: |
id: deletecstorpooldeployment
runNamespace: {{.Config.RunNamespace.value}}
apiVersion: extensions/v1beta1
kind: Deployment
action: delete
objectName: {{ keys .ListItems.csdlist.csds | join "," }}
---
# This run task lists all storage pool CRs that need to be deleted
apiVersion: openebs.io/v1alpha1
kind: RunTask
metadata:
name: cstor-pool-delete-liststoragepoolcr-default
spec:
meta: |
id: liststoragepoolcr
apiVersion: openebs.io/v1alpha1
kind: StoragePool
action: list
options: |-
labelSelector: openebs.io/storage-pool-claim={{.Storagepool.owner}}
post: |
{{- $sps := jsonpath .JsonResult "{range .items[*]}pkey=sps,{@.metadata.name}=;{end}" | trim | default "" | splitList ";" -}}
{{- $sps | notFoundErr "storge pool cr not found" | saveIf "listcstorpoolcr.notFoundErr" .TaskResult | noop -}}
{{- $sps | keyMap "splist" .ListItems | noop -}}
---
# This run task deletes the required storagepool object
apiVersion: openebs.io/v1alpha1
kind: RunTask
metadata:
name: cstor-pool-delete-deletestoragepoolcr-default
spec:
meta: |
id: deletestoragepoolcr
apiVersion: openebs.io/v1alpha1
kind: StoragePool
action: delete
objectName: {{ keys .ListItems.splist.sps | join "," }}
---
`
// CstorPoolArtifacts returns the cstor pool related artifacts corresponding to
// latest version
func CstorPoolArtifacts() (list artifactList) {
list.Items = append(list.Items, ParseArtifactListFromMultipleYamls(cstorPools{})...)
return
}
type cstorPools struct{}
// FetchYamls returns all the yamls related to cstor pool in a string
// format
//
// NOTE:
// This is an implementation of MultiYamlFetcher
func (c cstorPools) FetchYamls() string {
return cstorPoolYamls
}
| 1 | 11,110 | Is there a possibility of a clash between periodSeconds and timeoutSeconds? For instance, the current probe is not yet timed-out and the next one has started. | openebs-maya | go |
@@ -38,12 +38,11 @@ public class BesuCommandCustomFactory implements CommandLine.IFactory {
return (T) new VersionProvider(pluginVersionsProvider);
}
- final Constructor<T> constructor = cls.getDeclaredConstructor();
try {
+ final Constructor<T> constructor = cls.getDeclaredConstructor();
return constructor.newInstance();
} catch (Exception e) {
- constructor.setAccessible(true);
- return constructor.newInstance();
+ return CommandLine.defaultFactory().create(cls);
}
}
} | 1 | /*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.cli.util;
import org.hyperledger.besu.services.PluginVersionsProvider;
import java.lang.reflect.Constructor;
import picocli.CommandLine;
/**
* Custom PicoCli IFactory to handle version provider construction with plugin versions. Based on
* same logic as PicoCLI DefaultFactory.
*/
public class BesuCommandCustomFactory implements CommandLine.IFactory {
private final PluginVersionsProvider pluginVersionsProvider;
public BesuCommandCustomFactory(final PluginVersionsProvider pluginVersionsProvider) {
this.pluginVersionsProvider = pluginVersionsProvider;
}
@SuppressWarnings("unchecked")
@Override
public <T> T create(final Class<T> cls) throws Exception {
if (CommandLine.IVersionProvider.class.isAssignableFrom(cls)) {
return (T) new VersionProvider(pluginVersionsProvider);
}
final Constructor<T> constructor = cls.getDeclaredConstructor();
try {
return constructor.newInstance();
} catch (Exception e) {
constructor.setAccessible(true);
return constructor.newInstance();
}
}
}
| 1 | 21,368 | This logic is already been performed in `CommandLine.defaultFactory().create(cls)` ... whats the point of repeating it here? | hyperledger-besu | java |
@@ -410,7 +410,7 @@ class ManualColumnMove extends BasePlugin {
* @private
*/
updateColumnsMapper() {
- let countCols = this.hot.countSourceCols();
+ let countCols = Math.max(this.hot.countCols(), this.hot.countSourceCols());
let columnsMapperLen = this.columnsMapper._arrayMap.length;
if (columnsMapperLen === 0) { | 1 | import BasePlugin from './../_base.js';
import Hooks from './../../pluginHooks';
import {arrayEach} from './../../helpers/array';
import {addClass, removeClass, offset} from './../../helpers/dom/element';
import {rangeEach} from './../../helpers/number';
import EventManager from './../../eventManager';
import {registerPlugin} from './../../plugins';
import ColumnsMapper from './columnsMapper';
import BacklightUI from './ui/backlight';
import GuidelineUI from './ui/guideline';
import {CellCoords} from './../../3rdparty/walkontable/src';
import './manualColumnMove.css';
Hooks.getSingleton().register('beforeColumnMove');
Hooks.getSingleton().register('afterColumnMove');
Hooks.getSingleton().register('unmodifyCol');
const privatePool = new WeakMap();
const CSS_PLUGIN = 'ht__manualColumnMove';
const CSS_SHOW_UI = 'show-ui';
const CSS_ON_MOVING = 'on-moving--columns';
const CSS_AFTER_SELECTION = 'after-selection--columns';
/**
* @plugin ManualColumnMove
*
* @description
* This plugin allows to change columns order.
*
* API:
* - moveColumn - move single column to the new position.
* - moveColumns - move many columns (as an array of indexes) to the new position.
*
* If you want apply visual changes, you have to call manually the render() method on the instance of Handsontable.
*
* UI components:
* - backlight - highlight of selected columns.
* - guideline - line which shows where rows has been moved.
*
* @class ManualColumnMove
* @plugin ManualColumnMove
*/
class ManualColumnMove extends BasePlugin {
constructor(hotInstance) {
super(hotInstance);
/**
* Set up WeakMap of plugin to sharing private parameters;
*/
privatePool.set(this, {
columnsToMove: [],
countCols: 0,
fixedColumns: 0,
pressed: void 0,
disallowMoving: void 0,
target: {
eventPageX: void 0,
coords: void 0,
TD: void 0,
col: void 0
}
});
/**
* List of last removed row indexes.
*
* @type {Array}
*/
this.removedColumns = [];
/**
* Object containing visual row indexes mapped to data source indexes.
*
* @type {RowsMapper}
*/
this.columnsMapper = new ColumnsMapper(this);
/**
* Event Manager object.
*
* @type {Object}
*/
this.eventManager = new EventManager(this);
/**
* Backlight UI object.
*
* @type {Object}
*/
this.backlight = new BacklightUI(hotInstance);
/**
* Guideline UI object.
*
* @type {Object}
*/
this.guideline = new GuidelineUI(hotInstance);
}
/**
* Check if plugin is enabled.
*
* @returns {Boolean}
*/
isEnabled() {
return !!this.hot.getSettings().manualColumnMove;
}
/**
* Enable the plugin.
*/
enablePlugin() {
if (this.enabled) {
return;
}
this.addHook('beforeOnCellMouseDown', (event, coords, TD, blockCalculations) => this.onBeforeOnCellMouseDown(event, coords, TD, blockCalculations));
this.addHook('beforeOnCellMouseOver', (event, coords, TD, blockCalculations) => this.onBeforeOnCellMouseOver(event, coords, TD, blockCalculations));
this.addHook('afterScrollVertically', () => this.onAfterScrollVertically());
this.addHook('modifyCol', (row, source) => this.onModifyCol(row, source));
this.addHook('beforeRemoveCol', (index, amount) => this.onBeforeRemoveCol(index, amount));
this.addHook('afterRemoveCol', () => this.onAfterRemoveCol());
this.addHook('afterCreateCol', (index, amount) => this.onAfterCreateCol(index, amount));
this.addHook('afterLoadData', () => this.onAfterLoadData());
this.addHook('unmodifyCol', (column) => this.onUnmodifyCol(column));
this.registerEvents();
// TODO: move adding plugin classname to BasePlugin.
addClass(this.hot.rootElement, CSS_PLUGIN);
super.enablePlugin();
}
/**
* Updates the plugin to use the latest options you have specified.
*/
updatePlugin() {
this.disablePlugin();
this.enablePlugin();
this.onAfterPluginsInitialized();
super.updatePlugin();
}
/**
* Disable plugin for this Handsontable instance.
*/
disablePlugin() {
let pluginSettings = this.hot.getSettings().manualColumnMove;
if (Array.isArray(pluginSettings)) {
this.columnsMapper.clearMap();
}
removeClass(this.hot.rootElement, CSS_PLUGIN);
this.unregisterEvents();
this.backlight.destroy();
this.guideline.destroy();
super.disablePlugin();
}
/**
* Move a single column.
*
* @param {Number} column Visual column index to be moved.
* @param {Number} target Visual column index being a target for the moved column.
*/
moveColumn(column, target) {
this.moveColumns([column], target);
}
/**
* Move multiple columns.
*
* @param {Array} columns Array of visual column indexes to be moved.
* @param {Number} target Visual column index being a target for the moved columns.
*/
moveColumns(columns, target) {
let priv = privatePool.get(this);
let beforeColumnHook = this.hot.runHooks('beforeColumnMove', columns, target);
priv.disallowMoving = !beforeColumnHook;
if (beforeColumnHook !== false) {
// first we need to rewrite an visual indexes to physical for save reference after move
arrayEach(columns, (column, index, array) => {
array[index] = this.columnsMapper.getValueByIndex(column);
});
// next, when we have got an physical indexes, we can move columns
arrayEach(columns, (column, index) => {
let actualPosition = this.columnsMapper.getIndexByValue(column);
if (actualPosition !== target) {
this.columnsMapper.swapIndexes(actualPosition, target + index);
}
});
}
this.hot.runHooks('afterColumnMove', columns, target);
}
/**
* Correct the cell selection after the move action. Fired only when action was made with a mouse.
* That means that changing the column order using the API won't correct the selection.
*
* @private
* @param {Number} startColumn Visual column index for the start of the selection.
* @param {Number} endColumn Visual column index for the end of the selection.
*/
changeSelection(startColumn, endColumn) {
let selection = this.hot.selection;
let lastRowIndex = this.hot.countRows() - 1;
selection.setRangeStartOnly(new CellCoords(0, startColumn));
selection.setRangeEnd(new CellCoords(lastRowIndex, endColumn), false);
}
/**
* Get the sum of the widths of columns in the provided range.
*
* @private
* @param {Number} from Visual column index.
* @param {Number} to Visual column index.
* @returns {Number}
*/
getColumnsWidth(from, to) {
let width = 0;
for (let i = from; i < to; i++) {
let columnWidth = 0;
if (i < 0) {
columnWidth = this.hot.view.wt.wtViewport.getRowHeaderWidth() || 0;
} else {
columnWidth = this.hot.view.wt.wtTable.getStretchedColumnWidth(i) || 0;
}
width += columnWidth;
}
return width;
}
/**
* Load initial settings when persistent state is saved or when plugin was initialized as an array.
*
* @private
*/
initialSettings() {
let pluginSettings = this.hot.getSettings().manualColumnMove;
if (Array.isArray(pluginSettings)) {
this.moveColumns(pluginSettings, 0);
} else if (pluginSettings !== void 0) {
this.persistentStateLoad();
}
}
/**
* Check if the provided column is in the fixedColumnsLeft section.
*
* @private
* @param {Number} column Visual column index to check.
* @returns {Boolean}
*/
isFixedColumnsLeft(column) {
return column < this.hot.getSettings().fixedColumnsLeft;
}
/**
* Save the manual column positions to the persistent state.
*
* @private
*/
persistentStateSave() {
this.hot.runHooks('persistentStateSave', 'manualColumnMove', this.columnsMapper._arrayMap);
}
/**
* Load the manual column positions from the persistent state.
*
* @private
*/
persistentStateLoad() {
let storedState = {};
this.hot.runHooks('persistentStateLoad', 'manualColumnMove', storedState);
if (storedState.value) {
this.columnsMapper._arrayMap = storedState.value;
}
}
/**
* Prepare array of indexes based on actual selection.
*
* @private
* @returns {Array}
*/
prepareColumnsToMoving(start, end) {
let selectedColumns = [];
rangeEach(start, end, (i) => {
selectedColumns.push(i);
});
return selectedColumns;
}
/**
* Update the UI visual position.
*
* @private
*/
refreshPositions() {
let priv = privatePool.get(this);
let firstVisible = this.hot.view.wt.wtTable.getFirstVisibleColumn();
let lastVisible = this.hot.view.wt.wtTable.getLastVisibleColumn();
let wtTable = this.hot.view.wt.wtTable;
let scrollableElement = this.hot.view.wt.wtOverlays.scrollableElement;
let scrollLeft = typeof scrollableElement.scrollX === 'number' ? scrollableElement.scrollX : scrollableElement.scrollLeft;
let tdOffsetLeft = this.hot.view.THEAD.offsetLeft + this.getColumnsWidth(0, priv.coordsColumn);
let mouseOffsetLeft = priv.target.eventPageX - (priv.rootElementOffset - (scrollableElement.scrollX === void 0 ? scrollLeft : 0));
let hiderWidth = wtTable.hider.offsetWidth;
let tbodyOffsetLeft = wtTable.TBODY.offsetLeft;
let backlightElemMarginLeft = this.backlight.getOffset().left;
let backlightElemWidth = this.backlight.getSize().width;
let rowHeaderWidth = 0;
if ((priv.rootElementOffset + wtTable.holder.offsetWidth + scrollLeft) < priv.target.eventPageX) {
if (priv.coordsColumn < priv.countCols) {
priv.coordsColumn++;
}
}
if (priv.hasRowHeaders) {
rowHeaderWidth = this.hot.view.wt.wtOverlays.leftOverlay.clone.wtTable.getColumnHeader(-1).offsetWidth;
}
if (this.isFixedColumnsLeft(priv.coordsColumn)) {
tdOffsetLeft += scrollLeft;
}
tdOffsetLeft += rowHeaderWidth;
if (priv.coordsColumn < 0) {
// if hover on rowHeader
if (priv.fixedColumns > 0) {
priv.target.col = 0;
} else {
priv.target.col = firstVisible > 0 ? firstVisible - 1 : firstVisible;
}
} else if (((priv.target.TD.offsetWidth / 2) + tdOffsetLeft) <= mouseOffsetLeft) {
let newCoordsCol = priv.coordsColumn >= priv.countCols ? priv.countCols - 1 : priv.coordsColumn;
// if hover on right part of TD
priv.target.col = newCoordsCol + 1;
// unfortunately first column is bigger than rest
tdOffsetLeft += priv.target.TD.offsetWidth;
if (priv.target.col > lastVisible) {
this.hot.scrollViewportTo(void 0, lastVisible + 1, void 0, true);
}
} else {
// elsewhere on table
priv.target.col = priv.coordsColumn;
if (priv.target.col <= firstVisible && priv.target.col >= priv.fixedColumns) {
this.hot.scrollViewportTo(void 0, firstVisible - 1);
}
}
if (priv.target.col <= firstVisible && priv.target.col >= priv.fixedColumns) {
this.hot.scrollViewportTo(void 0, firstVisible - 1);
}
let backlightLeft = mouseOffsetLeft;
let guidelineLeft = tdOffsetLeft;
if (mouseOffsetLeft + backlightElemWidth + backlightElemMarginLeft >= hiderWidth) {
// prevent display backlight on the right side of the table
backlightLeft = hiderWidth - backlightElemWidth - backlightElemMarginLeft;
} else if (mouseOffsetLeft + backlightElemMarginLeft < tbodyOffsetLeft + rowHeaderWidth) {
// prevent display backlight on the left side of the table
backlightLeft = tbodyOffsetLeft + rowHeaderWidth + Math.abs(backlightElemMarginLeft);
}
if (tdOffsetLeft >= hiderWidth - 1) {
// prevent display guideline outside the table
guidelineLeft = hiderWidth - 1;
} else if (guidelineLeft === 0) {
// guideline has got `margin-left: -1px` as default
guidelineLeft = 1;
} else if (scrollableElement.scrollX !== void 0 && priv.coordsColumn < priv.fixedColumns) {
guidelineLeft -= ((priv.rootElementOffset <= scrollableElement.scrollX) ? priv.rootElementOffset : 0);
}
this.backlight.setPosition(null, backlightLeft);
this.guideline.setPosition(null, guidelineLeft);
}
/**
* This method checks arrayMap from columnsMapper and updates the columnsMapper if it's necessary.
*
* @private
*/
updateColumnsMapper() {
let countCols = this.hot.countSourceCols();
let columnsMapperLen = this.columnsMapper._arrayMap.length;
if (columnsMapperLen === 0) {
this.columnsMapper.createMap(countCols || this.hot.getSettings().startCols);
} else if (columnsMapperLen < countCols) {
let diff = countCols - columnsMapperLen;
this.columnsMapper.insertItems(columnsMapperLen, diff);
} else if (columnsMapperLen > countCols) {
let maxIndex = countCols - 1;
let columnsToRemove = [];
arrayEach(this.columnsMapper._arrayMap, (value, index) => {
if (value > maxIndex) {
columnsToRemove.push(index);
}
});
this.columnsMapper.removeItems(columnsToRemove);
}
}
/**
* Bind the events used by the plugin.
*
* @private
*/
registerEvents() {
this.eventManager.addEventListener(document.documentElement, 'mousemove', (event) => this.onMouseMove(event));
this.eventManager.addEventListener(document.documentElement, 'mouseup', () => this.onMouseUp());
}
/**
* Unbind the events used by the plugin.
*
* @private
*/
unregisterEvents() {
this.eventManager.clear();
}
/**
* Change the behavior of selection / dragging.
*
* @private
* @param {MouseEvent} event `mousedown` event properties.
* @param {CellCoords} coords Visual cell coordinates where was fired event.
* @param {HTMLElement} TD Cell represented as HTMLElement.
* @param {Object} blockCalculations Object which contains information about blockCalculation for row, column or cells.
*/
onBeforeOnCellMouseDown(event, coords, TD, blockCalculations) {
let wtTable = this.hot.view.wt.wtTable;
let isHeaderSelection = this.hot.selection.selectedHeader.cols;
let selection = this.hot.getSelectedRange();
let priv = privatePool.get(this);
let isSortingElement = event.realTarget.className.indexOf('columnSorting') > -1;
if (!selection || !isHeaderSelection || priv.pressed || event.button !== 0 || isSortingElement) {
priv.pressed = false;
priv.columnsToMove.length = 0;
removeClass(this.hot.rootElement, [CSS_ON_MOVING, CSS_SHOW_UI]);
return;
}
let guidelineIsNotReady = this.guideline.isBuilt() && !this.guideline.isAppended();
let backlightIsNotReady = this.backlight.isBuilt() && !this.backlight.isAppended();
if (guidelineIsNotReady && backlightIsNotReady) {
this.guideline.appendTo(wtTable.hider);
this.backlight.appendTo(wtTable.hider);
}
let {from, to} = selection;
let start = Math.min(from.col, to.col);
let end = Math.max(from.col, to.col);
if (coords.row < 0 && (coords.col >= start && coords.col <= end)) {
blockCalculations.column = true;
priv.pressed = true;
priv.target.eventPageX = event.pageX;
priv.coordsColumn = coords.col;
priv.target.TD = TD;
priv.target.col = coords.col;
priv.columnsToMove = this.prepareColumnsToMoving(start, end);
priv.hasRowHeaders = !!this.hot.getSettings().rowHeaders;
priv.countCols = this.hot.countCols();
priv.fixedColumns = this.hot.getSettings().fixedColumnsLeft;
priv.rootElementOffset = offset(this.hot.rootElement).left;
let countColumnsFrom = priv.hasRowHeaders ? -1 : 0;
let topPos = wtTable.holder.scrollTop + wtTable.getColumnHeaderHeight(0) + 1;
let fixedColumns = coords.col < priv.fixedColumns;
let scrollableElement = this.hot.view.wt.wtOverlays.scrollableElement;
let wrapperIsWindow = scrollableElement.scrollX ? scrollableElement.scrollX - priv.rootElementOffset : 0;
let mouseOffset = event.layerX - (fixedColumns ? wrapperIsWindow : 0);
let leftOffset = Math.abs(this.getColumnsWidth(start, coords.col) + mouseOffset);
this.backlight.setPosition(topPos, this.getColumnsWidth(countColumnsFrom, start) + leftOffset);
this.backlight.setSize(this.getColumnsWidth(start, end + 1), wtTable.hider.offsetHeight - topPos);
this.backlight.setOffset(null, leftOffset * -1);
addClass(this.hot.rootElement, CSS_ON_MOVING);
} else {
removeClass(this.hot.rootElement, CSS_AFTER_SELECTION);
priv.pressed = false;
priv.columnsToMove.length = 0;
}
}
/**
* 'mouseMove' event callback. Fired when pointer move on document.documentElement.
*
* @private
* @param {MouseEvent} event `mousemove` event properties.
*/
onMouseMove(event) {
let priv = privatePool.get(this);
if (!priv.pressed) {
return;
}
// callback for browser which doesn't supports CSS pointer-event: none
if (event.realTarget === this.backlight.element) {
let width = this.backlight.getSize().width;
this.backlight.setSize(0);
setTimeout(function() {
this.backlight.setPosition(width);
});
}
priv.target.eventPageX = event.pageX;
this.refreshPositions();
}
/**
* 'beforeOnCellMouseOver' hook callback. Fired when pointer was over cell.
*
* @private
* @param {MouseEvent} event `mouseover` event properties.
* @param {CellCoords} coords Visual cell coordinates where was fired event.
* @param {HTMLElement} TD Cell represented as HTMLElement.
* @param {Object} blockCalculations Object which contains information about blockCalculation for row, column or cells.
*/
onBeforeOnCellMouseOver(event, coords, TD, blockCalculations) {
let selectedRange = this.hot.getSelectedRange();
let priv = privatePool.get(this);
if (!selectedRange || !priv.pressed) {
return;
}
if (priv.columnsToMove.indexOf(coords.col) > -1) {
removeClass(this.hot.rootElement, CSS_SHOW_UI);
} else {
addClass(this.hot.rootElement, CSS_SHOW_UI);
}
blockCalculations.row = true;
blockCalculations.column = true;
blockCalculations.cell = true;
priv.coordsColumn = coords.col;
priv.target.TD = TD;
}
/**
* `onMouseUp` hook callback.
*
* @private
*/
onMouseUp() {
let priv = privatePool.get(this);
priv.pressed = false;
priv.backlightWidth = 0;
removeClass(this.hot.rootElement, [CSS_ON_MOVING, CSS_SHOW_UI, CSS_AFTER_SELECTION]);
if (this.hot.selection.selectedHeader.cols) {
addClass(this.hot.rootElement, CSS_AFTER_SELECTION);
}
if (priv.columnsToMove.length < 1 || priv.target.col === void 0 || priv.columnsToMove.indexOf(priv.target.col) > -1) {
return;
}
this.moveColumns(priv.columnsToMove, priv.coordsColumn);
this.persistentStateSave();
this.hot.render();
this.hot.view.wt.wtOverlays.adjustElementsSize(true);
if (!priv.disallowMoving) {
let selectionStart = this.columnsMapper.getIndexByValue(priv.columnsToMove[0]);
let selectionEnd = this.columnsMapper.getIndexByValue(priv.columnsToMove[priv.columnsToMove.length - 1]);
this.changeSelection(selectionStart, selectionEnd);
}
priv.columnsToMove.length = 0;
}
/**
* `afterScrollHorizontally` hook callback. Fired the table was scrolled horizontally.
*
* @private
*/
onAfterScrollVertically() {
let wtTable = this.hot.view.wt.wtTable;
let headerHeight = wtTable.getColumnHeaderHeight(0) + 1;
let scrollTop = wtTable.holder.scrollTop;
let posTop = headerHeight + scrollTop;
this.backlight.setPosition(posTop);
this.backlight.setSize(null, wtTable.hider.offsetHeight - posTop);
}
/**
* `afterCreateCol` hook callback.
*
* @private
* @param {Number} index Visual index of the created column.
* @param {Number} amount Amount of created columns.
*/
onAfterCreateCol(index, amount) {
this.columnsMapper.shiftItems(index, amount);
}
/**
* On before remove column listener.
*
* @private
* @param {Number} index Visual column index.
* @param {Number} amount Defines how many columns removed.
*/
onBeforeRemoveCol(index, amount) {
this.removedColumns.length = 0;
if (index !== false) {
// Collect physical row index.
rangeEach(index, index + amount - 1, (removedIndex) => {
this.removedColumns.push(this.hot.runHooks('modifyCol', removedIndex, this.pluginName));
});
}
}
/**
* `afterRemoveCol` hook callback.
*
* @private
*/
onAfterRemoveCol() {
this.columnsMapper.unshiftItems(this.removedColumns);
}
/**
* `afterLoadData` hook callback.
*
* @private
*/
onAfterLoadData() {
this.updateColumnsMapper();
}
/**
* 'modifyRow' hook callback.
*
* @private
* @param {Number} column Visual column index.
* @returns {Number} Physical column index.
*/
onModifyCol(column, source) {
if (source !== this.pluginName) {
// ugly fix for try to insert new, needed columns after pasting data
let columnInMapper = this.columnsMapper.getValueByIndex(column);
column = columnInMapper === null ? column : columnInMapper;
}
return column;
}
/**
* 'unmodifyCol' hook callback.
*
* @private
* @param {Number} column Physical column index.
* @returns {Number} Visual column index.
*/
onUnmodifyCol(column) {
let indexInMapper = this.columnsMapper.getIndexByValue(column);
return indexInMapper === null ? column : indexInMapper;
}
/**
* `afterPluginsInitialized` hook callback.
*
* @private
*/
onAfterPluginsInitialized() {
this.updateColumnsMapper();
this.initialSettings();
this.backlight.build();
this.guideline.build();
}
/**
* Destroy plugin instance.
*/
destroy() {
this.backlight.destroy();
this.guideline.destroy();
super.destroy();
}
}
registerPlugin('ManualColumnMove', ManualColumnMove);
export default ManualColumnMove;
| 1 | 14,517 | Please change from `let` to `const` here and above. Setting value to `this.hot.countSourceCols()` should be enought probably. | handsontable-handsontable | js |
@@ -796,7 +796,10 @@ int flb_upstream_conn_timeouts(struct mk_list *list)
* waiting for I/O will receive the notification and trigger
* the error to it caller.
*/
- shutdown(u_conn->fd, SHUT_RDWR);
+ if (u_conn->fd != -1) {
+ shutdown(u_conn->fd, SHUT_RDWR);
+ }
+
u_conn->net_error = ETIMEDOUT;
prepare_destroy_conn(u_conn);
} | 1 | /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Fluent Bit
* ==========
* Copyright (C) 2019-2021 The Fluent Bit Authors
* Copyright (C) 2015-2018 Treasure Data Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <monkey/mk_core.h>
#include <fluent-bit/flb_info.h>
#include <fluent-bit/flb_mem.h>
#include <fluent-bit/flb_kv.h>
#include <fluent-bit/flb_slist.h>
#include <fluent-bit/flb_str.h>
#include <fluent-bit/flb_upstream.h>
#include <fluent-bit/flb_io.h>
#include <fluent-bit/tls/flb_tls.h>
#include <fluent-bit/flb_utils.h>
#include <fluent-bit/flb_thread_storage.h>
FLB_TLS_DEFINE(struct mk_list, flb_upstream_list_key);
/* Config map for Upstream networking setup */
struct flb_config_map upstream_net[] = {
{
FLB_CONFIG_MAP_STR, "net.dns.mode", NULL,
0, FLB_TRUE, offsetof(struct flb_net_setup, dns_mode),
"Select the primary DNS connection type (TCP or UDP)"
},
{
FLB_CONFIG_MAP_BOOL, "net.keepalive", "true",
0, FLB_TRUE, offsetof(struct flb_net_setup, keepalive),
"Enable or disable Keepalive support"
},
{
FLB_CONFIG_MAP_TIME, "net.keepalive_idle_timeout", "30s",
0, FLB_TRUE, offsetof(struct flb_net_setup, keepalive_idle_timeout),
"Set maximum time allowed for an idle Keepalive connection"
},
{
FLB_CONFIG_MAP_TIME, "net.connect_timeout", "10s",
0, FLB_TRUE, offsetof(struct flb_net_setup, connect_timeout),
"Set maximum time allowed to establish a connection, this time "
"includes the TLS handshake"
},
{
FLB_CONFIG_MAP_STR, "net.source_address", NULL,
0, FLB_TRUE, offsetof(struct flb_net_setup, source_address),
"Specify network address to bind for data traffic"
},
{
FLB_CONFIG_MAP_INT, "net.keepalive_max_recycle", "2000",
0, FLB_TRUE, offsetof(struct flb_net_setup, keepalive_max_recycle),
"Set maximum number of times a keepalive connection can be used "
"before it is retired."
},
/* EOF */
{0}
};
int flb_upstream_needs_proxy(const char *host, const char *proxy,
const char *no_proxy);
/* Enable thread-safe mode for upstream connection */
void flb_upstream_thread_safe(struct flb_upstream *u)
{
u->thread_safe = FLB_TRUE;
pthread_mutex_init(&u->mutex_lists, NULL);
/*
* Upon upstream creation, automatically the upstream is linked into
* the main Fluent Bit context (struct flb_config *)->upstreams. We
* have to avoid any access to this context outside of the worker
* thread.
*/
mk_list_del(&u->_head);
}
struct mk_list *flb_upstream_get_config_map(struct flb_config *config)
{
size_t config_index;
struct mk_list *config_map;
/* If a global dns mode was provided in the SERVICE category then we set it as
* the default value for net.dns_mode, that way the user can set a global value and
* override it on a per plugin basis, however, it's not because of this flexibility
* that it was done but because in order to be able to save the value in the
* flb_net_setup structure (and not lose it when flb_output_upstream_set overwrites
* the structure) we need to do it this way (or at least that's what I think)
*/
if (config->dns_mode != NULL) {
for (config_index = 0 ; upstream_net[config_index].name != NULL ; config_index++) {
if(strcmp(upstream_net[config_index].name, "net.dns.mode") == 0)
{
upstream_net[config_index].def_value = config->dns_mode;
}
}
}
config_map = flb_config_map_create(config, upstream_net);
return config_map;
}
void flb_upstream_queue_init(struct flb_upstream_queue *uq)
{
mk_list_init(&uq->av_queue);
mk_list_init(&uq->busy_queue);
mk_list_init(&uq->destroy_queue);
}
struct flb_upstream_queue *flb_upstream_queue_get(struct flb_upstream *u)
{
struct mk_list *head;
struct mk_list *list;
struct flb_upstream *th_u;
struct flb_upstream_queue *uq;
/*
* Get the upstream queue, this might be different if the upstream is running
* in single-thread or multi-thread mode.
*/
if (u->thread_safe == FLB_TRUE) {
list = flb_upstream_list_get();
if (!list) {
/*
* Here is the issue: a plugin enabled in multiworker mode in the
* initialization callback might wanted to use an upstream
* connection, but the init callback does not run in threaded mode
* so we hit this problem.
*
* As a fallback mechanism: just cross our fingers and return the
* principal upstream queue.
*/
return (struct flb_upstream_queue *) &u->queue;
}
mk_list_foreach(head, list) {
th_u = mk_list_entry(head, struct flb_upstream, _head);
if (th_u->parent_upstream == u) {
break;
}
th_u = NULL;
}
if (!th_u) {
return NULL;
}
uq = &th_u->queue;
}
else {
uq = &u->queue;
}
return uq;
}
void flb_upstream_list_set(struct mk_list *list)
{
FLB_TLS_SET(flb_upstream_list_key, list);
}
struct mk_list *flb_upstream_list_get()
{
return FLB_TLS_GET(flb_upstream_list_key);
}
/* Initialize any upstream environment context */
void flb_upstream_init()
{
/* Initialize the upstream queue thread local storage */
FLB_TLS_INIT(flb_upstream_list_key);
}
/* Creates a new upstream context */
struct flb_upstream *flb_upstream_create(struct flb_config *config,
const char *host, int port, int flags,
struct flb_tls *tls)
{
int ret;
char *proxy_protocol = NULL;
char *proxy_host = NULL;
char *proxy_port = NULL;
char *proxy_username = NULL;
char *proxy_password = NULL;
struct flb_upstream *u;
u = flb_calloc(1, sizeof(struct flb_upstream));
if (!u) {
flb_errno();
return NULL;
}
/* Set default networking setup values */
flb_net_setup_init(&u->net);
/* Set upstream to the http_proxy if it is specified. */
if (flb_upstream_needs_proxy(host, config->http_proxy, config->no_proxy) == FLB_TRUE) {
flb_debug("[upstream] config->http_proxy: %s", config->http_proxy);
ret = flb_utils_proxy_url_split(config->http_proxy, &proxy_protocol,
&proxy_username, &proxy_password,
&proxy_host, &proxy_port);
if (ret == -1) {
flb_errno();
flb_free(u);
return NULL;
}
u->tcp_host = flb_strdup(proxy_host);
u->tcp_port = atoi(proxy_port);
u->proxied_host = flb_strdup(host);
u->proxied_port = port;
if (proxy_username && proxy_password) {
u->proxy_username = flb_strdup(proxy_username);
u->proxy_password = flb_strdup(proxy_password);
}
flb_free(proxy_protocol);
flb_free(proxy_host);
flb_free(proxy_port);
flb_free(proxy_username);
flb_free(proxy_password);
}
else {
u->tcp_host = flb_strdup(host);
u->tcp_port = port;
}
if (!u->tcp_host) {
flb_free(u);
return NULL;
}
u->flags = flags;
u->flags |= FLB_IO_ASYNC;
u->thread_safe = FLB_FALSE;
/* Initialize queues */
flb_upstream_queue_init(&u->queue);
#ifdef FLB_HAVE_TLS
u->tls = tls;
#endif
mk_list_add(&u->_head, &config->upstreams);
return u;
}
/*
* Checks whehter a destinate URL should be proxied.
*/
int flb_upstream_needs_proxy(const char *host, const char *proxy,
const char *no_proxy)
{
int ret;
struct mk_list no_proxy_list;
struct mk_list *head;
struct flb_slist_entry *e = NULL;
/* No HTTP_PROXY, should not set up proxy for the upstream `host`. */
if (proxy == NULL) {
return FLB_FALSE;
}
/* No NO_PROXY with HTTP_PROXY set, should set up proxy for the upstream `host`. */
if (no_proxy == NULL) {
return FLB_TRUE;
}
/* NO_PROXY=`*`, it matches all hosts. */
if (strcmp(no_proxy, "*") == 0) {
return FLB_FALSE;
}
/* check the URL list in the NO_PROXY */
ret = flb_slist_create(&no_proxy_list);
if (ret != 0) {
return FLB_TRUE;
}
ret = flb_slist_split_string(&no_proxy_list, no_proxy, ',', -1);
if (ret <= 0) {
return FLB_TRUE;
}
ret = FLB_TRUE;
mk_list_foreach(head, &no_proxy_list) {
e = mk_list_entry(head, struct flb_slist_entry, _head);
if (strcmp(host, e->str) == 0) {
ret = FLB_FALSE;
break;
}
}
/* clean up the resources. */
flb_slist_destroy(&no_proxy_list);
return ret;
}
/* Create an upstream context using a valid URL (protocol, host and port) */
struct flb_upstream *flb_upstream_create_url(struct flb_config *config,
const char *url, int flags,
struct flb_tls *tls)
{
int ret;
int tmp_port = 0;
char *prot = NULL;
char *host = NULL;
char *port = NULL;
char *uri = NULL;
struct flb_upstream *u = NULL;
/* Parse and split URL */
ret = flb_utils_url_split(url, &prot, &host, &port, &uri);
if (ret == -1) {
flb_error("[upstream] invalid URL: %s", url);
return NULL;
}
if (!prot) {
flb_error("[upstream] unknown protocol type from URL: %s", url);
goto out;
}
/* Manage some default ports */
if (!port) {
if (strcasecmp(prot, "http") == 0) {
tmp_port = 80;
}
else if (strcasecmp(prot, "https") == 0) {
tmp_port = 443;
if ((flags & FLB_IO_TLS) == 0) {
flags |= FLB_IO_TLS;
}
}
}
else {
tmp_port = atoi(port);
}
if (tmp_port <= 0) {
flb_error("[upstream] unknown TCP port in URL: %s", url);
goto out;
}
u = flb_upstream_create(config, host, tmp_port, flags, tls);
if (!u) {
flb_error("[upstream] error creating context from URL: %s", url);
}
out:
if (prot) {
flb_free(prot);
}
if (host) {
flb_free(host);
}
if (port) {
flb_free(port);
}
if (uri) {
flb_free(uri);
}
return u;
}
/*
* This function moves the 'upstream connection' into the queue to be
* destroyed. Note that the caller is responsible to validate and check
* required mutex if this is being used in multi-worker mode.
*/
static int prepare_destroy_conn(struct flb_upstream_conn *u_conn)
{
struct flb_upstream *u = u_conn->u;
struct flb_upstream_queue *uq;
uq = flb_upstream_queue_get(u);
flb_trace("[upstream] destroy connection #%i to %s:%i",
u_conn->fd, u->tcp_host, u->tcp_port);
if (u->flags & FLB_IO_ASYNC) {
mk_event_del(u_conn->evl, &u_conn->event);
}
if (u_conn->fd > 0) {
flb_socket_close(u_conn->fd);
u_conn->fd = -1;
u_conn->event.fd = -1;
}
/* remove connection from the queue */
mk_list_del(&u_conn->_head);
/* Add node to destroy queue */
mk_list_add(&u_conn->_head, &uq->destroy_queue);
/*
* note: the connection context is destroyed by the engine once all events
* have been processed.
*/
return 0;
}
/* 'safe' version of prepare_destroy_conn. It set locks if necessary */
static inline int prepare_destroy_conn_safe(struct flb_upstream_conn *u_conn)
{
int ret;
struct flb_upstream *u = u_conn->u;
if (u->thread_safe == FLB_TRUE) {
pthread_mutex_lock(&u->mutex_lists);
}
ret = prepare_destroy_conn(u_conn);
if (u->thread_safe == FLB_TRUE) {
pthread_mutex_unlock(&u->mutex_lists);
}
return ret;
}
static int destroy_conn(struct flb_upstream_conn *u_conn)
{
#ifdef FLB_HAVE_TLS
if (u_conn->tls_session) {
flb_tls_session_destroy(u_conn->tls, u_conn);
}
#endif
mk_list_del(&u_conn->_head);
flb_free(u_conn);
return 0;
}
static struct flb_upstream_conn *create_conn(struct flb_upstream *u)
{
int ret;
time_t now;
struct mk_event_loop *evl;
struct flb_coro *coro = flb_coro_get();
struct flb_upstream_conn *conn;
struct flb_upstream_queue *uq;
now = time(NULL);
conn = flb_calloc(1, sizeof(struct flb_upstream_conn));
if (!conn) {
flb_errno();
return NULL;
}
conn->u = u;
conn->fd = -1;
conn->net_error = -1;
/* retrieve the event loop */
evl = flb_engine_evl_get();
conn->evl = evl;
if (u->net.connect_timeout > 0) {
conn->ts_connect_timeout = now + u->net.connect_timeout;
}
else {
conn->ts_connect_timeout = -1;
}
#ifdef FLB_HAVE_TLS
conn->tls = NULL;
conn->tls_session = NULL;
#endif
conn->ts_created = time(NULL);
conn->ts_assigned = time(NULL);
conn->ts_available = 0;
conn->ka_count = 0;
conn->coro = coro;
if (u->net.keepalive == FLB_TRUE) {
flb_upstream_conn_recycle(conn, FLB_TRUE);
}
else {
flb_upstream_conn_recycle(conn, FLB_FALSE);
}
MK_EVENT_ZERO(&conn->event);
if (u->thread_safe == FLB_TRUE) {
pthread_mutex_lock(&u->mutex_lists);
}
/* Link new connection to the busy queue */
uq = flb_upstream_queue_get(u);
mk_list_add(&conn->_head, &uq->busy_queue);
if (u->thread_safe == FLB_TRUE) {
pthread_mutex_unlock(&u->mutex_lists);
}
/* Start connection */
ret = flb_io_net_connect(conn, coro);
if (ret == -1) {
flb_debug("[upstream] connection #%i failed to %s:%i",
conn->fd, u->tcp_host, u->tcp_port);
prepare_destroy_conn_safe(conn);
return NULL;
}
if (conn->u->flags & FLB_IO_TCP_KA) {
flb_debug("[upstream] KA connection #%i to %s:%i is connected",
conn->fd, u->tcp_host, u->tcp_port);
}
/* Invalidate timeout for connection */
conn->ts_connect_timeout = -1;
return conn;
}
int flb_upstream_destroy(struct flb_upstream *u)
{
struct mk_list *tmp;
struct mk_list *head;
struct flb_upstream_conn *u_conn;
struct flb_upstream_queue *uq;
uq = flb_upstream_queue_get(u);
if (!uq) {
uq = &u->queue;
}
mk_list_foreach_safe(head, tmp, &uq->av_queue) {
u_conn = mk_list_entry(head, struct flb_upstream_conn, _head);
prepare_destroy_conn(u_conn);
}
mk_list_foreach_safe(head, tmp, &uq->busy_queue) {
u_conn = mk_list_entry(head, struct flb_upstream_conn, _head);
prepare_destroy_conn(u_conn);
}
mk_list_foreach_safe(head, tmp, &uq->destroy_queue) {
u_conn = mk_list_entry(head, struct flb_upstream_conn, _head);
destroy_conn(u_conn);
}
flb_free(u->tcp_host);
flb_free(u->proxied_host);
flb_free(u->proxy_username);
flb_free(u->proxy_password);
mk_list_del(&u->_head);
flb_free(u);
return 0;
}
/* Enable or disable 'recycle' flag for the connection */
int flb_upstream_conn_recycle(struct flb_upstream_conn *conn, int val)
{
if (val == FLB_TRUE || val == FLB_FALSE) {
conn->recycle = val;
}
return -1;
}
struct flb_upstream_conn *flb_upstream_conn_get(struct flb_upstream *u)
{
int err;
struct mk_list *tmp;
struct mk_list *head;
struct flb_upstream_conn *conn = NULL;
struct flb_upstream_queue *uq;
uq = flb_upstream_queue_get(u);
flb_trace("[upstream] get new connection for %s:%i, net setup:\n"
"net.connect_timeout = %i seconds\n"
"net.source_address = %s\n"
"net.keepalive = %s\n"
"net.keepalive_idle_timeout = %i seconds",
u->tcp_host, u->tcp_port,
u->net.connect_timeout,
u->net.source_address ? u->net.source_address: "any",
u->net.keepalive ? "enabled": "disabled",
u->net.keepalive_idle_timeout);
/* On non Keepalive mode, always create a new TCP connection */
if (u->net.keepalive == FLB_FALSE) {
return create_conn(u);
}
/*
* If we are in keepalive mode, iterate list of available connections,
* take a little of time to do some cleanup and assign a connection. If no
* entries exists, just create a new one.
*/
mk_list_foreach_safe(head, tmp, &uq->av_queue) {
conn = mk_list_entry(head, struct flb_upstream_conn, _head);
if (u->thread_safe == FLB_TRUE) {
pthread_mutex_lock(&u->mutex_lists);
}
/* This connection works, let's move it to the busy queue */
mk_list_del(&conn->_head);
mk_list_add(&conn->_head, &uq->busy_queue);
if (u->thread_safe == FLB_TRUE) {
pthread_mutex_unlock(&u->mutex_lists);
}
/* Reset errno */
conn->net_error = -1;
err = flb_socket_error(conn->fd);
if (!FLB_EINPROGRESS(err) && err != 0) {
flb_debug("[upstream] KA connection #%i is in a failed state "
"to: %s:%i, cleaning up",
conn->fd, u->tcp_host, u->tcp_port);
prepare_destroy_conn_safe(conn);
conn = NULL;
continue;
}
/* Connect timeout */
conn->ts_assigned = time(NULL);
flb_debug("[upstream] KA connection #%i to %s:%i has been assigned (recycled)",
conn->fd, u->tcp_host, u->tcp_port);
/*
* Note: since we are in a keepalive connection, the socket is already being
* monitored for possible disconnections while idle. Upon re-use by the caller
* when it try to send some data, the I/O interface (flb_io.c) will put the
* proper event mask and reuse, there is no need to remove the socket from
* the event loop and re-add it again.
*
* So just return the connection context.
*/
return conn;
}
/* No keepalive connection available, create a new one */
if (!conn) {
conn = create_conn(u);
}
return conn;
}
/*
* An 'idle' and keepalive might be disconnected, if so, this callback will perform
* the proper connection cleanup.
*/
static int cb_upstream_conn_ka_dropped(void *data)
{
struct flb_upstream_conn *conn;
conn = (struct flb_upstream_conn *) data;
flb_debug("[upstream] KA connection #%i to %s:%i has been disconnected "
"by the remote service",
conn->fd, conn->u->tcp_host, conn->u->tcp_port);
return prepare_destroy_conn_safe(conn);
}
int flb_upstream_conn_release(struct flb_upstream_conn *conn)
{
int ret;
struct flb_upstream *u = conn->u;
struct flb_upstream_queue *uq;
uq = flb_upstream_queue_get(u);
/* If this is a valid KA connection just recycle */
if (conn->u->net.keepalive == FLB_TRUE && conn->recycle == FLB_TRUE && conn->fd > -1) {
/*
* This connection is still useful, move it to the 'available' queue and
* initialize variables.
*/
if (u->thread_safe == FLB_TRUE) {
pthread_mutex_lock(&u->mutex_lists);
}
mk_list_del(&conn->_head);
mk_list_add(&conn->_head, &uq->av_queue);
if (u->thread_safe == FLB_TRUE) {
pthread_mutex_unlock(&u->mutex_lists);
}
conn->ts_available = time(NULL);
/*
* The socket at this point is not longer monitored, so if we want to be
* notified if the 'available keepalive connection' gets disconnected by
* the remote endpoint we need to add it again.
*/
conn->event.handler = cb_upstream_conn_ka_dropped;
ret = mk_event_add(conn->evl, conn->fd,
FLB_ENGINE_EV_CUSTOM,
MK_EVENT_CLOSE, &conn->event);
if (ret == -1) {
/* We failed the registration, for safety just destroy the connection */
flb_debug("[upstream] KA connection #%i to %s:%i could not be "
"registered, closing.",
conn->fd, conn->u->tcp_host, conn->u->tcp_port);
return prepare_destroy_conn_safe(conn);
}
flb_debug("[upstream] KA connection #%i to %s:%i is now available",
conn->fd, conn->u->tcp_host, conn->u->tcp_port);
conn->ka_count++;
/* if we have exceeded our max number of uses of this connection, destroy it */
if (conn->u->net.keepalive_max_recycle > 0 &&
conn->ka_count > conn->u->net.keepalive_max_recycle) {
flb_debug("[upstream] KA count %i exceeded configured limit "
"of %i: closing.",
conn->ka_count, conn->u->net.keepalive_max_recycle);
return prepare_destroy_conn(conn);
}
return 0;
}
/* No keepalive connections must be destroyed */
return prepare_destroy_conn_safe(conn);
}
int flb_upstream_conn_timeouts(struct mk_list *list)
{
time_t now;
int drop;
struct mk_list *head;
struct mk_list *u_head;
struct mk_list *tmp;
struct flb_upstream *u;
struct flb_upstream_conn *u_conn;
struct flb_upstream_queue *uq;
now = time(NULL);
/* Iterate all upstream contexts */
mk_list_foreach(head, list) {
u = mk_list_entry(head, struct flb_upstream, _head);
uq = flb_upstream_queue_get(u);
if (u->thread_safe == FLB_TRUE) {
pthread_mutex_lock(&u->mutex_lists);
}
/* Iterate every busy connection */
mk_list_foreach_safe(u_head, tmp, &uq->busy_queue) {
u_conn = mk_list_entry(u_head, struct flb_upstream_conn, _head);
drop = FLB_FALSE;
/* Connect timeouts */
if (u->net.connect_timeout > 0 &&
u_conn->ts_connect_timeout > 0 &&
u_conn->ts_connect_timeout <= now) {
drop = FLB_TRUE;
flb_error("[upstream] connection #%i to %s:%i timed out after "
"%i seconds",
u_conn->fd,
u->tcp_host, u->tcp_port, u->net.connect_timeout);
}
if (drop == FLB_TRUE) {
/*
* Shutdown the connection, this is the safest way to indicate
* that the socket cannot longer work and any co-routine on
* waiting for I/O will receive the notification and trigger
* the error to it caller.
*/
shutdown(u_conn->fd, SHUT_RDWR);
u_conn->net_error = ETIMEDOUT;
prepare_destroy_conn(u_conn);
}
}
/* Check every available Keepalive connection */
mk_list_foreach_safe(u_head, tmp, &uq->av_queue) {
u_conn = mk_list_entry(u_head, struct flb_upstream_conn, _head);
if ((now - u_conn->ts_available) >= u->net.keepalive_idle_timeout) {
shutdown(u_conn->fd, SHUT_RDWR);
prepare_destroy_conn(u_conn);
flb_debug("[upstream] drop keepalive connection #%i to %s:%i "
"(keepalive idle timeout)",
u_conn->fd, u->tcp_host, u->tcp_port);
}
}
if (u->thread_safe == FLB_TRUE) {
pthread_mutex_unlock(&u->mutex_lists);
}
}
return 0;
}
int flb_upstream_conn_pending_destroy(struct flb_upstream *u)
{
struct mk_list *tmp;
struct mk_list *head;
struct flb_upstream_conn *u_conn;
struct flb_upstream_queue *uq;
uq = flb_upstream_queue_get(u);
if (u->thread_safe == FLB_TRUE) {
pthread_mutex_lock(&u->mutex_lists);
}
/* Real destroy of connections context */
mk_list_foreach_safe(head, tmp, &uq->destroy_queue) {
u_conn = mk_list_entry(head, struct flb_upstream_conn, _head);
destroy_conn(u_conn);
}
if (u->thread_safe == FLB_TRUE) {
pthread_mutex_unlock(&u->mutex_lists);
}
return 0;
}
int flb_upstream_conn_active_destroy(struct flb_upstream *u)
{
struct mk_list *tmp;
struct mk_list *head;
struct flb_upstream_conn *u_conn;
struct flb_upstream_queue *uq;
uq = flb_upstream_queue_get(u);
/* Real destroy of connections context */
mk_list_foreach_safe(head, tmp, &uq->av_queue) {
u_conn = mk_list_entry(head, struct flb_upstream_conn, _head);
destroy_conn(u_conn);
}
return 0;
}
int flb_upstream_conn_active_destroy_list(struct mk_list *list)
{
struct mk_list *head;
struct flb_upstream *u;
/* Iterate all upstream contexts */
mk_list_foreach(head, list) {
u = mk_list_entry(head, struct flb_upstream, _head);
flb_upstream_conn_active_destroy(u);
}
return 0;
}
int flb_upstream_conn_pending_destroy_list(struct mk_list *list)
{
struct mk_list *head;
struct flb_upstream *u;
/* Iterate all upstream contexts */
mk_list_foreach(head, list) {
u = mk_list_entry(head, struct flb_upstream, _head);
flb_upstream_conn_pending_destroy(u);
}
return 0;
}
int flb_upstream_is_async(struct flb_upstream *u)
{
if (u->flags & FLB_IO_ASYNC) {
return FLB_TRUE;
}
return FLB_FALSE;
}
| 1 | 15,465 | Somewhat nitpick: I see the `!=` pattern mentioned in the fluent-bit style guide, but imo, it would be safer to check that a fd is non-negative with ` > -1` or `>= 0` | fluent-fluent-bit | c |
@@ -0,0 +1,17 @@
+class CreatePgSearchDocuments < ActiveRecord::Migration
+ def self.up
+ say_with_time("Creating table for pg_search multisearch") do
+ create_table :pg_search_documents do |t|
+ t.text :content
+ t.belongs_to :searchable, :polymorphic => true, :index => true
+ t.timestamps null: false
+ end
+ end
+ end
+
+ def self.down
+ say_with_time("Dropping table for pg_search multisearch") do
+ drop_table :pg_search_documents
+ end
+ end
+end | 1 | 1 | 15,165 | Use the new Ruby 1.9 hash syntax. | thoughtbot-upcase | rb |
|
@@ -25,6 +25,8 @@ import (
"github.com/gogits/gogs/modules/bindata"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/user"
+
+ "strk.kbt.io/projects/go/libravatar"
)
type Scheme string | 1 | // Copyright 2014 The Gogs 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 setting
import (
"fmt"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/Unknwon/com"
_ "github.com/go-macaron/cache/memcache"
_ "github.com/go-macaron/cache/redis"
"github.com/go-macaron/session"
_ "github.com/go-macaron/session/redis"
"gopkg.in/ini.v1"
"github.com/gogits/gogs/modules/bindata"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/user"
)
type Scheme string
const (
HTTP Scheme = "http"
HTTPS Scheme = "https"
FCGI Scheme = "fcgi"
)
type LandingPage string
const (
LANDING_PAGE_HOME LandingPage = "/"
LANDING_PAGE_EXPLORE LandingPage = "/explore"
)
var (
// Build information
BuildTime string
BuildGitHash string
// App settings
AppVer string
AppName string
AppUrl string
AppSubUrl string
AppSubUrlDepth int // Number of slashes
AppPath string
AppDataPath string
// Server settings
Protocol Scheme
Domain string
HttpAddr, HttpPort string
LocalURL string
OfflineMode bool
DisableRouterLog bool
CertFile, KeyFile string
StaticRootPath string
EnableGzip bool
LandingPageUrl LandingPage
SSH struct {
Disabled bool `ini:"DISABLE_SSH"`
StartBuiltinServer bool `ini:"START_SSH_SERVER"`
Domain string `ini:"SSH_DOMAIN"`
Port int `ini:"SSH_PORT"`
ListenPort int `ini:"SSH_LISTEN_PORT"`
RootPath string `ini:"SSH_ROOT_PATH"`
KeyTestPath string `ini:"SSH_KEY_TEST_PATH"`
KeygenPath string `ini:"SSH_KEYGEN_PATH"`
MinimumKeySizeCheck bool `ini:"-"`
MinimumKeySizes map[string]int `ini:"-"`
}
// Security settings
InstallLock bool
SecretKey string
LogInRememberDays int
CookieUserName string
CookieRememberName string
ReverseProxyAuthUser string
// Database settings
UseSQLite3 bool
UseMySQL bool
UsePostgreSQL bool
UseTiDB bool
// Webhook settings
Webhook struct {
QueueLength int
DeliverTimeout int
SkipTLSVerify bool
Types []string
PagingNum int
}
// Repository settings
Repository struct {
AnsiCharset string
ForcePrivate bool
MaxCreationLimit int
PullRequestQueueLength int
}
RepoRootPath string
ScriptType string
// UI settings
ExplorePagingNum int
IssuePagingNum int
FeedMaxCommitNum int
AdminUserPagingNum int
AdminRepoPagingNum int
AdminNoticePagingNum int
AdminOrgPagingNum int
ThemeColorMetaTag string
MaxDisplayFileSize int64
// Markdown sttings
Markdown struct {
EnableHardLineBreak bool
CustomURLSchemes []string `ini:"CUSTOM_URL_SCHEMES"`
}
// Picture settings
AvatarUploadPath string
GravatarSource string
DisableGravatar bool
// Log settings
LogRootPath string
LogModes []string
LogConfigs []string
// Attachment settings
AttachmentPath string
AttachmentAllowedTypes string
AttachmentMaxSize int64
AttachmentMaxFiles int
AttachmentEnabled bool
// Time settings
TimeFormat string
// Cache settings
CacheAdapter string
CacheInternal int
CacheConn string
// Session settings
SessionConfig session.Options
CSRFCookieName = "_csrf"
// Cron tasks
Cron struct {
UpdateMirror struct {
Enabled bool
RunAtStart bool
Schedule string
} `ini:"cron.update_mirrors"`
RepoHealthCheck struct {
Enabled bool
RunAtStart bool
Schedule string
Timeout time.Duration
Args []string `delim:" "`
} `ini:"cron.repo_health_check"`
CheckRepoStats struct {
Enabled bool
RunAtStart bool
Schedule string
} `ini:"cron.check_repo_stats"`
}
// Git settings
Git struct {
MaxGitDiffLines int
MaxGitDiffLineCharacters int
MaxGitDiffFiles int
GcArgs []string `delim:" "`
Timeout struct {
Migrate int
Mirror int
Clone int
Pull int
} `ini:"git.timeout"`
}
// API settings
API struct {
MaxResponseItems int
}
// I18n settings
Langs, Names []string
dateLangs map[string]string
// Highlight settings are loaded in modules/template/hightlight.go
// Other settings
ShowFooterBranding bool
ShowFooterVersion bool
SupportMiniWinService bool
// Global setting objects
Cfg *ini.File
CustomPath string // Custom directory path
CustomConf string
ProdMode bool
RunUser string
IsWindows bool
HasRobotsTxt bool
)
func DateLang(lang string) string {
name, ok := dateLangs[lang]
if ok {
return name
}
return "en"
}
// execPath returns the executable path.
func execPath() (string, error) {
file, err := exec.LookPath(os.Args[0])
if err != nil {
return "", err
}
return filepath.Abs(file)
}
func init() {
IsWindows = runtime.GOOS == "windows"
log.NewLogger(0, "console", `{"level": 0}`)
var err error
if AppPath, err = execPath(); err != nil {
log.Fatal(4, "fail to get app path: %v\n", err)
}
// Note: we don't use path.Dir here because it does not handle case
// which path starts with two "/" in Windows: "//psf/Home/..."
AppPath = strings.Replace(AppPath, "\\", "/", -1)
}
// WorkDir returns absolute path of work directory.
func WorkDir() (string, error) {
wd := os.Getenv("GOGS_WORK_DIR")
if len(wd) > 0 {
return wd, nil
}
i := strings.LastIndex(AppPath, "/")
if i == -1 {
return AppPath, nil
}
return AppPath[:i], nil
}
func forcePathSeparator(path string) {
if strings.Contains(path, "\\") {
log.Fatal(4, "Do not use '\\' or '\\\\' in paths, instead, please use '/' in all places")
}
}
// NewContext initializes configuration context.
// NOTE: do not print any log except error.
func NewContext() {
workDir, err := WorkDir()
if err != nil {
log.Fatal(4, "Fail to get work directory: %v", err)
}
Cfg, err = ini.Load(bindata.MustAsset("conf/app.ini"))
if err != nil {
log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
}
CustomPath = os.Getenv("GOGS_CUSTOM")
if len(CustomPath) == 0 {
CustomPath = workDir + "/custom"
}
if len(CustomConf) == 0 {
CustomConf = CustomPath + "/conf/app.ini"
}
if com.IsFile(CustomConf) {
if err = Cfg.Append(CustomConf); err != nil {
log.Fatal(4, "Fail to load custom conf '%s': %v", CustomConf, err)
}
} else {
log.Warn("Custom config '%s' not found, ignore this if you're running first time", CustomConf)
}
Cfg.NameMapper = ini.AllCapsUnderscore
homeDir, err := com.HomeDir()
if err != nil {
log.Fatal(4, "Fail to get home directory: %v", err)
}
homeDir = strings.Replace(homeDir, "\\", "/", -1)
LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
forcePathSeparator(LogRootPath)
sec := Cfg.Section("server")
AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs: Go Git Service")
AppUrl = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
if AppUrl[len(AppUrl)-1] != '/' {
AppUrl += "/"
}
// Check if has app suburl.
url, err := url.Parse(AppUrl)
if err != nil {
log.Fatal(4, "Invalid ROOT_URL '%s': %s", AppUrl, err)
}
// Suburl should start with '/' and end without '/', such as '/{subpath}'.
AppSubUrl = strings.TrimSuffix(url.Path, "/")
AppSubUrlDepth = strings.Count(AppSubUrl, "/")
Protocol = HTTP
if sec.Key("PROTOCOL").String() == "https" {
Protocol = HTTPS
CertFile = sec.Key("CERT_FILE").String()
KeyFile = sec.Key("KEY_FILE").String()
} else if sec.Key("PROTOCOL").String() == "fcgi" {
Protocol = FCGI
}
Domain = sec.Key("DOMAIN").MustString("localhost")
HttpAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
HttpPort = sec.Key("HTTP_PORT").MustString("3000")
LocalURL = sec.Key("LOCAL_ROOT_URL").MustString(string(Protocol) + "://localhost:" + HttpPort + "/")
OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
AppDataPath = sec.Key("APP_DATA_PATH").MustString("data")
EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
switch sec.Key("LANDING_PAGE").MustString("home") {
case "explore":
LandingPageUrl = LANDING_PAGE_EXPLORE
default:
LandingPageUrl = LANDING_PAGE_HOME
}
SSH.RootPath = path.Join(homeDir, ".ssh")
SSH.KeyTestPath = os.TempDir()
if err = Cfg.Section("server").MapTo(&SSH); err != nil {
log.Fatal(4, "Fail to map SSH settings: %v", err)
}
// When disable SSH, start builtin server value is ignored.
if SSH.Disabled {
SSH.StartBuiltinServer = false
}
if !SSH.Disabled && !SSH.StartBuiltinServer {
if err := os.MkdirAll(SSH.RootPath, 0700); err != nil {
log.Fatal(4, "Fail to create '%s': %v", SSH.RootPath, err)
} else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil {
log.Fatal(4, "Fail to create '%s': %v", SSH.KeyTestPath, err)
}
}
SSH.MinimumKeySizeCheck = sec.Key("MINIMUM_KEY_SIZE_CHECK").MustBool()
SSH.MinimumKeySizes = map[string]int{}
minimumKeySizes := Cfg.Section("ssh.minimum_key_sizes").Keys()
for _, key := range minimumKeySizes {
if key.MustInt() != -1 {
SSH.MinimumKeySizes[strings.ToLower(key.Name())] = key.MustInt()
}
}
sec = Cfg.Section("security")
InstallLock = sec.Key("INSTALL_LOCK").MustBool()
SecretKey = sec.Key("SECRET_KEY").String()
LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
CookieUserName = sec.Key("COOKIE_USERNAME").String()
CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
sec = Cfg.Section("attachment")
AttachmentPath = sec.Key("PATH").MustString(path.Join(AppDataPath, "attachments"))
if !filepath.IsAbs(AttachmentPath) {
AttachmentPath = path.Join(workDir, AttachmentPath)
}
AttachmentAllowedTypes = strings.Replace(sec.Key("ALLOWED_TYPES").MustString("image/jpeg,image/png"), "|", ",", -1)
AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(4)
AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(5)
AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
TimeFormat = map[string]string{
"ANSIC": time.ANSIC,
"UnixDate": time.UnixDate,
"RubyDate": time.RubyDate,
"RFC822": time.RFC822,
"RFC822Z": time.RFC822Z,
"RFC850": time.RFC850,
"RFC1123": time.RFC1123,
"RFC1123Z": time.RFC1123Z,
"RFC3339": time.RFC3339,
"RFC3339Nano": time.RFC3339Nano,
"Kitchen": time.Kitchen,
"Stamp": time.Stamp,
"StampMilli": time.StampMilli,
"StampMicro": time.StampMicro,
"StampNano": time.StampNano,
}[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
RunUser = Cfg.Section("").Key("RUN_USER").String()
curUser := user.CurrentUsername()
// Does not check run user when the install lock is off.
if InstallLock && RunUser != curUser {
log.Fatal(4, "Expect user(%s) but current user is: %s", RunUser, curUser)
}
// Determine and create root git repository path.
sec = Cfg.Section("repository")
RepoRootPath = sec.Key("ROOT").MustString(path.Join(homeDir, "gogs-repositories"))
forcePathSeparator(RepoRootPath)
if !filepath.IsAbs(RepoRootPath) {
RepoRootPath = path.Join(workDir, RepoRootPath)
} else {
RepoRootPath = path.Clean(RepoRootPath)
}
ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
if err = Cfg.Section("repository").MapTo(&Repository); err != nil {
log.Fatal(4, "Fail to map Repository settings: %v", err)
}
// UI settings.
sec = Cfg.Section("ui")
ExplorePagingNum = sec.Key("EXPLORE_PAGING_NUM").MustInt(20)
IssuePagingNum = sec.Key("ISSUE_PAGING_NUM").MustInt(10)
FeedMaxCommitNum = sec.Key("FEED_MAX_COMMIT_NUM").MustInt(5)
MaxDisplayFileSize = sec.Key("MAX_DISPLAY_FILE_SIZE").MustInt64(8388608)
sec = Cfg.Section("ui.admin")
AdminUserPagingNum = sec.Key("USER_PAGING_NUM").MustInt(50)
AdminRepoPagingNum = sec.Key("REPO_PAGING_NUM").MustInt(50)
AdminNoticePagingNum = sec.Key("NOTICE_PAGING_NUM").MustInt(50)
AdminOrgPagingNum = sec.Key("ORG_PAGING_NUM").MustInt(50)
ThemeColorMetaTag = sec.Key("THEME_COLOR_META_TAG").MustString("#ff5343")
sec = Cfg.Section("picture")
AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString(path.Join(AppDataPath, "avatars"))
forcePathSeparator(AvatarUploadPath)
if !filepath.IsAbs(AvatarUploadPath) {
AvatarUploadPath = path.Join(workDir, AvatarUploadPath)
}
switch source := sec.Key("GRAVATAR_SOURCE").MustString("gravatar"); source {
case "duoshuo":
GravatarSource = "http://gravatar.duoshuo.com/avatar/"
case "gravatar":
GravatarSource = "https://secure.gravatar.com/avatar/"
default:
GravatarSource = source
}
DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
if OfflineMode {
DisableGravatar = true
}
if err = Cfg.Section("markdown").MapTo(&Markdown); err != nil {
log.Fatal(4, "Fail to map Markdown settings: %v", err)
} else if err = Cfg.Section("cron").MapTo(&Cron); err != nil {
log.Fatal(4, "Fail to map Cron settings: %v", err)
} else if err = Cfg.Section("git").MapTo(&Git); err != nil {
log.Fatal(4, "Fail to map Git settings: %v", err)
} else if err = Cfg.Section("api").MapTo(&API); err != nil {
log.Fatal(4, "Fail to map API settings: %v", err)
}
Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
dateLangs = Cfg.Section("i18n.datelang").KeysHash()
ShowFooterBranding = Cfg.Section("other").Key("SHOW_FOOTER_BRANDING").MustBool()
ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool()
HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
}
var Service struct {
ActiveCodeLives int
ResetPwdCodeLives int
RegisterEmailConfirm bool
DisableRegistration bool
ShowRegistrationButton bool
RequireSignInView bool
EnableNotifyMail bool
EnableReverseProxyAuth bool
EnableReverseProxyAutoRegister bool
EnableCaptcha bool
}
func newService() {
sec := Cfg.Section("service")
Service.ActiveCodeLives = sec.Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
Service.ResetPwdCodeLives = sec.Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
Service.DisableRegistration = sec.Key("DISABLE_REGISTRATION").MustBool()
Service.ShowRegistrationButton = sec.Key("SHOW_REGISTRATION_BUTTON").MustBool(!Service.DisableRegistration)
Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool()
}
var logLevels = map[string]string{
"Trace": "0",
"Debug": "1",
"Info": "2",
"Warn": "3",
"Error": "4",
"Critical": "5",
}
func newLogService() {
log.Info("%s %s", AppName, AppVer)
if len(BuildTime) > 0 {
log.Info("Build Time: %s", BuildTime)
log.Info("Build Git Hash: %s", BuildGitHash)
}
// Get and check log mode.
LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
LogConfigs = make([]string, len(LogModes))
for i, mode := range LogModes {
mode = strings.TrimSpace(mode)
sec, err := Cfg.GetSection("log." + mode)
if err != nil {
log.Fatal(4, "Unknown log mode: %s", mode)
}
validLevels := []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}
// Log level.
levelName := Cfg.Section("log."+mode).Key("LEVEL").In(
Cfg.Section("log").Key("LEVEL").In("Trace", validLevels),
validLevels)
level, ok := logLevels[levelName]
if !ok {
log.Fatal(4, "Unknown log level: %s", levelName)
}
// Generate log configuration.
switch mode {
case "console":
LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
case "file":
logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
if err = os.MkdirAll(path.Dir(logPath), os.ModePerm); err != nil {
panic(err.Error())
}
LogConfigs[i] = fmt.Sprintf(
`{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
logPath,
sec.Key("LOG_ROTATE").MustBool(true),
sec.Key("MAX_LINES").MustInt(1000000),
1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
sec.Key("DAILY_ROTATE").MustBool(true),
sec.Key("MAX_DAYS").MustInt(7))
case "conn":
LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
sec.Key("RECONNECT_ON_MSG").MustBool(),
sec.Key("RECONNECT").MustBool(),
sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
sec.Key("ADDR").MustString(":7020"))
case "smtp":
LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
sec.Key("USER").MustString("[email protected]"),
sec.Key("PASSWD").MustString("******"),
sec.Key("HOST").MustString("127.0.0.1:25"),
sec.Key("RECEIVERS").MustString("[]"),
sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
case "database":
LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
sec.Key("DRIVER").String(),
sec.Key("CONN").String())
}
log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
}
}
func newCacheService() {
CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
switch CacheAdapter {
case "memory":
CacheInternal = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
case "redis", "memcache":
CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
default:
log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
}
log.Info("Cache Service Enabled")
}
func newSessionService() {
SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
[]string{"memory", "file", "redis", "mysql"})
SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
SessionConfig.CookiePath = AppSubUrl
SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
log.Info("Session Service Enabled")
}
// Mailer represents mail service.
type Mailer struct {
QueueLength int
Name string
Host string
From string
User, Passwd string
DisableHelo bool
HeloHostname string
SkipVerify bool
UseCertificate bool
CertFile, KeyFile string
EnableHTMLAlternative bool
}
var (
MailService *Mailer
)
func newMailService() {
sec := Cfg.Section("mailer")
// Check mailer setting.
if !sec.Key("ENABLED").MustBool() {
return
}
MailService = &Mailer{
QueueLength: sec.Key("SEND_BUFFER_LEN").MustInt(100),
Name: sec.Key("NAME").MustString(AppName),
Host: sec.Key("HOST").String(),
User: sec.Key("USER").String(),
Passwd: sec.Key("PASSWD").String(),
DisableHelo: sec.Key("DISABLE_HELO").MustBool(),
HeloHostname: sec.Key("HELO_HOSTNAME").String(),
SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
CertFile: sec.Key("CERT_FILE").String(),
KeyFile: sec.Key("KEY_FILE").String(),
EnableHTMLAlternative: sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(),
}
MailService.From = sec.Key("FROM").MustString(MailService.User)
log.Info("Mail Service Enabled")
}
func newRegisterMailService() {
if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
return
} else if MailService == nil {
log.Warn("Register Mail Service: Mail Service is not enabled")
return
}
Service.RegisterEmailConfirm = true
log.Info("Register Mail Service Enabled")
}
func newNotifyMailService() {
if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
return
} else if MailService == nil {
log.Warn("Notify Mail Service: Mail Service is not enabled")
return
}
Service.EnableNotifyMail = true
log.Info("Notify Mail Service Enabled")
}
func newWebhookService() {
sec := Cfg.Section("webhook")
Webhook.QueueLength = sec.Key("QUEUE_LENGTH").MustInt(1000)
Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
Webhook.Types = []string{"gogs", "slack"}
Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
}
func NewServices() {
newService()
newLogService()
newCacheService()
newSessionService()
newMailService()
newRegisterMailService()
newNotifyMailService()
newWebhookService()
}
| 1 | 11,141 | Please host to a GitHub repo. | gogs-gogs | go |
@@ -197,6 +197,12 @@ func (s *server) doneSplit(w http.ResponseWriter, r *http.Request) {
return
}
- tag.DoneSplit(tagr.Address)
+ _, err = tag.DoneSplit(tagr.Address)
+ if err != nil {
+ s.Logger.Debugf("done split: %v", err)
+ s.Logger.Error("done split: %v", err)
+ jsonhttp.InternalServerError(w, nil)
+ return
+ }
jsonhttp.OK(w, "ok")
} | 1 | // Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package api
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
"github.com/ethersphere/bee/pkg/jsonhttp"
"github.com/ethersphere/bee/pkg/swarm"
"github.com/ethersphere/bee/pkg/tags"
"github.com/gorilla/mux"
)
type tagRequest struct {
Name string `json:"name,omitempty"`
Address swarm.Address `json:"address,omitempty"`
}
type tagResponse struct {
Total int64 `json:"total"`
Split int64 `json:"split"`
Seen int64 `json:"seen"`
Stored int64 `json:"stored"`
Sent int64 `json:"sent"`
Synced int64 `json:"synced"`
Uid uint32 `json:"uid"`
Anonymous bool `json:"anonymous"`
Name string `json:"name"`
Address swarm.Address `json:"address"`
StartedAt time.Time `json:"startedAt"`
}
func newTagResponse(tag *tags.Tag) tagResponse {
return tagResponse{
Total: tag.Total,
Split: tag.Split,
Seen: tag.Seen,
Stored: tag.Stored,
Sent: tag.Sent,
Synced: tag.Synced,
Uid: tag.Uid,
Name: tag.Name,
Address: tag.Address,
StartedAt: tag.StartedAt,
}
}
func (s *server) createTag(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
if jsonhttp.HandleBodyReadError(err, w) {
return
}
s.Logger.Debugf("create tag: read request body error: %v", err)
s.Logger.Error("create tag: read request body error")
jsonhttp.InternalServerError(w, "cannot read request")
return
}
tagr := tagRequest{}
if len(body) > 0 {
err = json.Unmarshal(body, &tagr)
if err != nil {
s.Logger.Debugf("create tag: unmarshal tag name error: %v", err)
s.Logger.Errorf("create tag: unmarshal tag name error")
jsonhttp.InternalServerError(w, "error unmarshaling metadata")
return
}
}
if tagr.Name == "" {
tagr.Name = fmt.Sprintf("unnamed_tag_%d", time.Now().Unix())
}
tag, err := s.Tags.Create(tagr.Name, 0)
if err != nil {
s.Logger.Debugf("create tag: tag create error: %v", err)
s.Logger.Error("create tag: tag create error")
jsonhttp.InternalServerError(w, "cannot create tag")
return
}
w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
jsonhttp.Created(w, newTagResponse(tag))
}
func (s *server) getTag(w http.ResponseWriter, r *http.Request) {
idStr := mux.Vars(r)["id"]
id, err := strconv.Atoi(idStr)
if err != nil {
s.Logger.Debugf("get tag: parse id %s: %v", idStr, err)
s.Logger.Error("get tag: parse id")
jsonhttp.BadRequest(w, "invalid id")
return
}
tag, err := s.Tags.Get(uint32(id))
if err != nil {
if errors.Is(err, tags.ErrNotFound) {
s.Logger.Debugf("get tag: tag not present: %v, id %s", err, idStr)
s.Logger.Error("get tag: tag not present")
jsonhttp.NotFound(w, "tag not present")
return
}
s.Logger.Debugf("get tag: tag %v: %v", idStr, err)
s.Logger.Errorf("get tag: %v", idStr)
jsonhttp.InternalServerError(w, "cannot get tag")
return
}
w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
jsonhttp.OK(w, newTagResponse(tag))
}
func (s *server) deleteTag(w http.ResponseWriter, r *http.Request) {
idStr := mux.Vars(r)["id"]
id, err := strconv.Atoi(idStr)
if err != nil {
s.Logger.Debugf("delete tag: parse id %s: %v", idStr, err)
s.Logger.Error("delete tag: parse id")
jsonhttp.BadRequest(w, "invalid id")
return
}
tag, err := s.Tags.Get(uint32(id))
if err != nil {
if errors.Is(err, tags.ErrNotFound) {
s.Logger.Debugf("delete tag: tag not present: %v, id %s", err, idStr)
s.Logger.Error("delete tag: tag not present")
jsonhttp.NotFound(w, "tag not present")
return
}
s.Logger.Debugf("delete tag: tag %v: %v", idStr, err)
s.Logger.Errorf("delete tag: %v", idStr)
jsonhttp.InternalServerError(w, "cannot get tag")
return
}
s.Tags.Delete(tag.Uid)
jsonhttp.NoContent(w)
}
func (s *server) doneSplit(w http.ResponseWriter, r *http.Request) {
idStr := mux.Vars(r)["id"]
id, err := strconv.Atoi(idStr)
if err != nil {
s.Logger.Debugf("done split tag: parse id %s: %v", idStr, err)
s.Logger.Error("done split tag: parse id")
jsonhttp.BadRequest(w, "invalid id")
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
if jsonhttp.HandleBodyReadError(err, w) {
return
}
s.Logger.Debugf("done split tag: read request body error: %v", err)
s.Logger.Error("done split tag: read request body error")
jsonhttp.InternalServerError(w, "cannot read request")
return
}
tagr := tagRequest{}
if len(body) > 0 {
err = json.Unmarshal(body, &tagr)
if err != nil {
s.Logger.Debugf("done split tag: unmarshal tag name error: %v", err)
s.Logger.Errorf("done split tag: unmarshal tag name error")
jsonhttp.InternalServerError(w, "error unmarshaling metadata")
return
}
}
tag, err := s.Tags.Get(uint32(id))
if err != nil {
if errors.Is(err, tags.ErrNotFound) {
s.Logger.Debugf("done split: tag not present: %v, id %s", err, idStr)
s.Logger.Error("done split: tag not present")
jsonhttp.NotFound(w, "tag not present")
return
}
s.Logger.Debugf("done split: tag %v: %v", idStr, err)
s.Logger.Errorf("done split: %v", idStr)
jsonhttp.InternalServerError(w, "cannot get tag")
return
}
tag.DoneSplit(tagr.Address)
jsonhttp.OK(w, "ok")
}
| 1 | 11,916 | The Error log message should not expose internals. The message should be something like this `"done split failed for address %v", tagr.Address`. Also, the Debugf would be more informative with the address in the message. | ethersphere-bee | go |
@@ -13,11 +13,15 @@
package args
-import "flag"
+import (
+ "flag"
+)
const (
versionUsage = "Print the agent version information and exit"
- logLevelUsage = "Loglevel: [<crit>|<error>|<warn>|<info>|<debug>]"
+ logLevelUsage = "Loglevel overrides loglevel-driver and loglevel-on-instance and sets the same level for both on-instance and driver logging: [<crit>|<error>|<warn>|<info>|<debug>]"
+ driverLogLevelUsage = "Loglevel for docker logging driver: [<crit>|<error>|<warn>|<info>|<debug>]"
+ instanceLogLevelUsage = "Loglevel for Agent on-instance log file: [<none>|<crit>|<error>|<warn>|<info>|<debug>]"
ecsAttributesUsage = "Print the Agent's ECS Attributes based on its environment"
acceptInsecureCertUsage = "Disable SSL certificate verification. We do not recommend setting this option"
licenseUsage = "Print the LICENSE and NOTICE files and exit" | 1 | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package args
import "flag"
const (
versionUsage = "Print the agent version information and exit"
logLevelUsage = "Loglevel: [<crit>|<error>|<warn>|<info>|<debug>]"
ecsAttributesUsage = "Print the Agent's ECS Attributes based on its environment"
acceptInsecureCertUsage = "Disable SSL certificate verification. We do not recommend setting this option"
licenseUsage = "Print the LICENSE and NOTICE files and exit"
blacholeEC2MetadataUsage = "Blackhole the EC2 Metadata requests. Setting this option can cause the ECS Agent to fail to work properly. We do not recommend setting this option"
windowsServiceUsage = "Run the ECS agent as a Windows Service"
healthcheckServiceUsage = "Run the agent healthcheck"
versionFlagName = "version"
logLevelFlagName = "loglevel"
ecsAttributesFlagName = "ecs-attributes"
acceptInsecureCertFlagName = "k"
licenseFlagName = "license"
blackholeEC2MetadataFlagName = "blackhole-ec2-metadata"
windowsServiceFlagName = "windows-service"
healthCheckFlagName = "healthcheck"
)
// Args wraps various ECS Agent arguments
type Args struct {
// Version indicates if the version information should be printed
Version *bool
// LogLevel represents the ECS Agent's log level
LogLevel *string
// AcceptInsecureCert indicates if SSL certificate verification
// should be disabled
AcceptInsecureCert *bool
// License indicates if the license information should be printed
License *bool
// BlackholeEC2Metadata indicates if EC2 Metadata requests should be
// blackholed
BlackholeEC2Metadata *bool
// ECSAttributes indicates that the agent should print its attributes
ECSAttributes *bool
// WindowsService indicates that the agent should run as a Windows service
WindowsService *bool
// Healthcheck indicates that agent should run healthcheck
Healthcheck *bool
}
// New creates a new Args object from the argument list
func New(arguments []string) (*Args, error) {
flagset := flag.NewFlagSet("Amazon ECS Agent", flag.ContinueOnError)
args := &Args{
Version: flagset.Bool(versionFlagName, false, versionUsage),
LogLevel: flagset.String(logLevelFlagName, "", logLevelUsage),
AcceptInsecureCert: flagset.Bool(acceptInsecureCertFlagName, false, acceptInsecureCertUsage),
License: flagset.Bool(licenseFlagName, false, licenseUsage),
BlackholeEC2Metadata: flagset.Bool(blackholeEC2MetadataFlagName, false, blacholeEC2MetadataUsage),
ECSAttributes: flagset.Bool(ecsAttributesFlagName, false, ecsAttributesUsage),
WindowsService: flagset.Bool(windowsServiceFlagName, false, windowsServiceUsage),
Healthcheck: flagset.Bool(healthCheckFlagName, false, healthcheckServiceUsage),
}
err := flagset.Parse(arguments)
if err != nil {
return nil, err
}
return args, nil
}
| 1 | 24,806 | can we rename `fileLogLevelUsage` to be more generic like `instanceLogLevelUsage`? Same goes for other var below like fileLogLevelFlagName, FileLogLevel. | aws-amazon-ecs-agent | go |
@@ -169,11 +169,8 @@ define(["loading", "layoutManager", "userSettings", "events", "libraryBrowser",
valueChangeEvent: "click"
});
- if (layoutManager.desktop || layoutManager.mobile) {
- alphaPickerElement.classList.add("alphabetPicker-right");
- itemsContainer.classList.remove("padded-left-withalphapicker");
- itemsContainer.classList.add("padded-right-withalphapicker");
- }
+ alphaPickerElement.classList.add("alphaPicker-fixed-right");
+ itemsContainer.classList.add("padded-right-withalphapicker");
}
var btnFilter = tabContent.querySelector(".btnFilter"); | 1 | define(["loading", "layoutManager", "userSettings", "events", "libraryBrowser", "alphaPicker", "listView", "cardBuilder", "emby-itemscontainer"], function (loading, layoutManager, userSettings, events, libraryBrowser, alphaPicker, listView, cardBuilder) {
"use strict";
return function (view, params, tabContent, options) {
function onViewStyleChange() {
if (self.getCurrentViewStyle() == "List") {
itemsContainer.classList.add("vertical-list");
itemsContainer.classList.remove("vertical-wrap");
} else {
itemsContainer.classList.remove("vertical-list");
itemsContainer.classList.add("vertical-wrap");
}
itemsContainer.innerHTML = "";
}
function updateFilterControls() {
if (self.alphaPicker) {
self.alphaPicker.value(query.NameStartsWithOrGreater);
}
}
function fetchData() {
isLoading = true;
loading.show();
return ApiClient.getItems(ApiClient.getCurrentUserId(), query);
}
function afterRefresh(result) {
function onNextPageClick() {
if (isLoading) {
return;
}
query.StartIndex += query.Limit;
itemsContainer.refreshItems();
}
function onPreviousPageClick() {
if (isLoading) {
return;
}
query.StartIndex -= query.Limit;
itemsContainer.refreshItems();
}
window.scrollTo(0, 0);
updateFilterControls();
var pagingHtml = libraryBrowser.getQueryPagingHtml({
startIndex: query.StartIndex,
limit: query.Limit,
totalRecordCount: result.TotalRecordCount,
showLimit: false,
updatePageSizeSetting: false,
addLayoutButton: false,
sortButton: false,
filterButton: false
});
var i;
var length;
var elems = tabContent.querySelectorAll(".paging");
for (i = 0, length = elems.length; i < length; i++) {
elems[i].innerHTML = pagingHtml;
}
elems = tabContent.querySelectorAll(".btnNextPage");
for (i = 0, length = elems.length; i < length; i++) {
elems[i].addEventListener("click", onNextPageClick);
}
elems = tabContent.querySelectorAll(".btnPreviousPage");
for (i = 0, length = elems.length; i < length; i++) {
elems[i].addEventListener("click", onPreviousPageClick);
}
isLoading = false;
loading.hide();
require(["autoFocuser"], function (autoFocuser) {
autoFocuser.autoFocus(tabContent);
});
}
function getItemsHtml(items) {
var html;
var viewStyle = self.getCurrentViewStyle();
if (viewStyle == "Thumb") {
html = cardBuilder.getCardsHtml({
items: items,
shape: "backdrop",
preferThumb: true,
context: "movies",
lazy: true,
overlayPlayButton: true,
showTitle: true,
showYear: true,
centerText: true
});
} else if (viewStyle == "ThumbCard") {
html = cardBuilder.getCardsHtml({
items: items,
shape: "backdrop",
preferThumb: true,
context: "movies",
lazy: true,
cardLayout: true,
showTitle: true,
showYear: true,
centerText: true
});
} else if (viewStyle == "Banner") {
html = cardBuilder.getCardsHtml({
items: items,
shape: "banner",
preferBanner: true,
context: "movies",
lazy: true
});
} else if (viewStyle == "List") {
html = listView.getListViewHtml({
items: items,
context: "movies",
sortBy: query.SortBy
});
} else if (viewStyle == "PosterCard") {
html = cardBuilder.getCardsHtml({
items: items,
shape: "portrait",
context: "movies",
showTitle: true,
showYear: true,
centerText: true,
lazy: true,
cardLayout: true
});
} else {
html = cardBuilder.getCardsHtml({
items: items,
shape: "portrait",
context: "movies",
overlayPlayButton: true,
showTitle: true,
showYear: true,
centerText: true
});
}
return html;
}
function initPage(tabContent) {
itemsContainer.fetchData = fetchData;
itemsContainer.getItemsHtml = getItemsHtml;
itemsContainer.afterRefresh = afterRefresh;
var alphaPickerElement = tabContent.querySelector(".alphaPicker");
if (alphaPickerElement) {
alphaPickerElement.addEventListener("alphavaluechanged", function (e) {
var newValue = e.detail.value;
query.NameStartsWithOrGreater = newValue;
query.StartIndex = 0;
itemsContainer.refreshItems();
});
self.alphaPicker = new alphaPicker({
element: alphaPickerElement,
valueChangeEvent: "click"
});
if (layoutManager.desktop || layoutManager.mobile) {
alphaPickerElement.classList.add("alphabetPicker-right");
itemsContainer.classList.remove("padded-left-withalphapicker");
itemsContainer.classList.add("padded-right-withalphapicker");
}
}
var btnFilter = tabContent.querySelector(".btnFilter");
if (btnFilter) {
btnFilter.addEventListener("click", function () {
self.showFilterMenu();
});
}
var btnSort = tabContent.querySelector(".btnSort");
if (btnSort) {
btnSort.addEventListener("click", function (e) {
libraryBrowser.showSortMenu({
items: [{
name: Globalize.translate("OptionNameSort"),
id: "SortName,ProductionYear"
}, {
name: Globalize.translate("OptionImdbRating"),
id: "CommunityRating,SortName,ProductionYear"
}, {
name: Globalize.translate("OptionCriticRating"),
id: "CriticRating,SortName,ProductionYear"
}, {
name: Globalize.translate("OptionDateAdded"),
id: "DateCreated,SortName,ProductionYear"
}, {
name: Globalize.translate("OptionDatePlayed"),
id: "DatePlayed,SortName,ProductionYear"
}, {
name: Globalize.translate("OptionParentalRating"),
id: "OfficialRating,SortName,ProductionYear"
}, {
name: Globalize.translate("OptionPlayCount"),
id: "PlayCount,SortName,ProductionYear"
}, {
name: Globalize.translate("OptionReleaseDate"),
id: "PremiereDate,SortName,ProductionYear"
}, {
name: Globalize.translate("OptionRuntime"),
id: "Runtime,SortName,ProductionYear"
}],
callback: function () {
query.StartIndex = 0;
userSettings.saveQuerySettings(savedQueryKey, query);
itemsContainer.refreshItems();
},
query: query,
button: e.target
});
});
}
var btnSelectView = tabContent.querySelector(".btnSelectView");
btnSelectView.addEventListener("click", function (e) {
libraryBrowser.showLayoutMenu(e.target, self.getCurrentViewStyle(), "Banner,List,Poster,PosterCard,Thumb,ThumbCard".split(","));
});
btnSelectView.addEventListener("layoutchange", function (e) {
var viewStyle = e.detail.viewStyle;
userSettings.set(savedViewKey, viewStyle);
query.StartIndex = 0;
onViewStyleChange();
itemsContainer.refreshItems();
});
}
var self = this;
var itemsContainer = tabContent.querySelector(".itemsContainer");
var savedQueryKey = params.topParentId + "-" + options.mode;
var savedViewKey = savedQueryKey + "-view";
var query = {
SortBy: "SortName,ProductionYear",
SortOrder: "Ascending",
IncludeItemTypes: "Movie",
Recursive: true,
Fields: "PrimaryImageAspectRatio,MediaSourceCount,BasicSyncInfo",
ImageTypeLimit: 1,
EnableImageTypes: "Primary,Backdrop,Banner,Thumb",
StartIndex: 0,
Limit: 100,
ParentId: params.topParentId
};
var isLoading = false;
if (options.mode === "favorites") {
query.IsFavorite = true;
}
query = userSettings.loadQuerySettings(savedQueryKey, query);
self.showFilterMenu = function () {
require(["components/filterdialog/filterdialog"], function (filterDialogFactory) {
var filterDialog = new filterDialogFactory({
query: query,
mode: "movies",
serverId: ApiClient.serverId()
});
events.on(filterDialog, "filterchange", function () {
query.StartIndex = 0;
itemsContainer.refreshItems();
});
filterDialog.show();
});
};
self.getCurrentViewStyle = function () {
return userSettings.get(savedViewKey) || "Poster";
};
self.initTab = function () {
initPage(tabContent);
onViewStyleChange();
};
self.renderTab = function () {
itemsContainer.refreshItems();
updateFilterControls();
};
self.destroy = function () {
itemsContainer = null;
};
};
});
| 1 | 12,841 | Does this one not need the `tabContent` object used in the other files? | jellyfin-jellyfin-web | js |
@@ -102,6 +102,16 @@ type ClassicELB struct {
Tags map[string]string `json:"tags,omitempty"`
}
+// IsUnmanaged returns true if the Classic ELB is unmanaged.
+func (b *ClassicELB) IsUnmanaged(clusterName string) bool {
+ return b.Name != "" && !Tags(b.Tags).HasOwned(clusterName)
+}
+
+// IsManaged returns true if Classic ELB is managed.
+func (b *ClassicELB) IsManaged(clusterName string) bool {
+ return !b.IsUnmanaged(clusterName)
+}
+
// ClassicELBAttributes defines extra attributes associated with a classic load balancer.
type ClassicELBAttributes struct {
// IdleTimeout is time that the connection is allowed to be idle (no data | 1 | /*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1beta1
import (
"fmt"
"sort"
"time"
)
// NetworkStatus encapsulates AWS networking resources.
type NetworkStatus struct {
// SecurityGroups is a map from the role/kind of the security group to its unique name, if any.
SecurityGroups map[SecurityGroupRole]SecurityGroup `json:"securityGroups,omitempty"`
// APIServerELB is the Kubernetes api server classic load balancer.
APIServerELB ClassicELB `json:"apiServerElb,omitempty"`
}
// ClassicELBScheme defines the scheme of a classic load balancer.
type ClassicELBScheme string
var (
// ClassicELBSchemeInternetFacing defines an internet-facing, publicly
// accessible AWS Classic ELB scheme.
ClassicELBSchemeInternetFacing = ClassicELBScheme("internet-facing")
// ClassicELBSchemeInternal defines an internal-only facing
// load balancer internal to an ELB.
ClassicELBSchemeInternal = ClassicELBScheme("internal")
// ClassicELBSchemeIncorrectInternetFacing was inaccurately used to define an internet-facing LB in v0.6 releases > v0.6.6 and v0.7.0 release.
ClassicELBSchemeIncorrectInternetFacing = ClassicELBScheme("Internet-facing")
)
func (e ClassicELBScheme) String() string {
return string(e)
}
// ClassicELBProtocol defines listener protocols for a classic load balancer.
type ClassicELBProtocol string
var (
// ClassicELBProtocolTCP defines the ELB API string representing the TCP protocol.
ClassicELBProtocolTCP = ClassicELBProtocol("TCP")
// ClassicELBProtocolSSL defines the ELB API string representing the TLS protocol.
ClassicELBProtocolSSL = ClassicELBProtocol("SSL")
// ClassicELBProtocolHTTP defines the ELB API string representing the HTTP protocol at L7.
ClassicELBProtocolHTTP = ClassicELBProtocol("HTTP")
// ClassicELBProtocolHTTPS defines the ELB API string representing the HTTP protocol at L7.
ClassicELBProtocolHTTPS = ClassicELBProtocol("HTTPS")
)
// ClassicELB defines an AWS classic load balancer.
type ClassicELB struct {
// The name of the load balancer. It must be unique within the set of load balancers
// defined in the region. It also serves as identifier.
Name string `json:"name,omitempty"`
// DNSName is the dns name of the load balancer.
DNSName string `json:"dnsName,omitempty"`
// Scheme is the load balancer scheme, either internet-facing or private.
Scheme ClassicELBScheme `json:"scheme,omitempty"`
// AvailabilityZones is an array of availability zones in the VPC attached to the load balancer.
AvailabilityZones []string `json:"availabilityZones,omitempty"`
// SubnetIDs is an array of subnets in the VPC attached to the load balancer.
SubnetIDs []string `json:"subnetIds,omitempty"`
// SecurityGroupIDs is an array of security groups assigned to the load balancer.
SecurityGroupIDs []string `json:"securityGroupIds,omitempty"`
// Listeners is an array of classic elb listeners associated with the load balancer. There must be at least one.
Listeners []ClassicELBListener `json:"listeners,omitempty"`
// HealthCheck is the classic elb health check associated with the load balancer.
HealthCheck *ClassicELBHealthCheck `json:"healthChecks,omitempty"`
// Attributes defines extra attributes associated with the load balancer.
Attributes ClassicELBAttributes `json:"attributes,omitempty"`
// Tags is a map of tags associated with the load balancer.
Tags map[string]string `json:"tags,omitempty"`
}
// ClassicELBAttributes defines extra attributes associated with a classic load balancer.
type ClassicELBAttributes struct {
// IdleTimeout is time that the connection is allowed to be idle (no data
// has been sent over the connection) before it is closed by the load balancer.
IdleTimeout time.Duration `json:"idleTimeout,omitempty"`
// CrossZoneLoadBalancing enables the classic load balancer load balancing.
// +optional
CrossZoneLoadBalancing bool `json:"crossZoneLoadBalancing,omitempty"`
}
// ClassicELBListener defines an AWS classic load balancer listener.
type ClassicELBListener struct {
Protocol ClassicELBProtocol `json:"protocol"`
Port int64 `json:"port"`
InstanceProtocol ClassicELBProtocol `json:"instanceProtocol"`
InstancePort int64 `json:"instancePort"`
}
// ClassicELBHealthCheck defines an AWS classic load balancer health check.
type ClassicELBHealthCheck struct {
Target string `json:"target"`
Interval time.Duration `json:"interval"`
Timeout time.Duration `json:"timeout"`
HealthyThreshold int64 `json:"healthyThreshold"`
UnhealthyThreshold int64 `json:"unhealthyThreshold"`
}
// NetworkSpec encapsulates all things related to AWS network.
type NetworkSpec struct {
// VPC configuration.
// +optional
VPC VPCSpec `json:"vpc,omitempty"`
// Subnets configuration.
// +optional
Subnets Subnets `json:"subnets,omitempty"`
// CNI configuration
// +optional
CNI *CNISpec `json:"cni,omitempty"`
// SecurityGroupOverrides is an optional set of security groups to use for cluster instances
// This is optional - if not provided new security groups will be created for the cluster
// +optional
SecurityGroupOverrides map[SecurityGroupRole]string `json:"securityGroupOverrides,omitempty"`
}
// VPCSpec configures an AWS VPC.
type VPCSpec struct {
// ID is the vpc-id of the VPC this provider should use to create resources.
ID string `json:"id,omitempty"`
// CidrBlock is the CIDR block to be used when the provider creates a managed VPC.
// Defaults to 10.0.0.0/16.
CidrBlock string `json:"cidrBlock,omitempty"`
// InternetGatewayID is the id of the internet gateway associated with the VPC.
// +optional
InternetGatewayID *string `json:"internetGatewayId,omitempty"`
// Tags is a collection of tags describing the resource.
Tags Tags `json:"tags,omitempty"`
// AvailabilityZoneUsageLimit specifies the maximum number of availability zones (AZ) that
// should be used in a region when automatically creating subnets. If a region has more
// than this number of AZs then this number of AZs will be picked randomly when creating
// default subnets. Defaults to 3
// +kubebuilder:default=3
// +kubebuilder:validation:Minimum=1
AvailabilityZoneUsageLimit *int `json:"availabilityZoneUsageLimit,omitempty"`
// AvailabilityZoneSelection specifies how AZs should be selected if there are more AZs
// in a region than specified by AvailabilityZoneUsageLimit. There are 2 selection schemes:
// Ordered - selects based on alphabetical order
// Random - selects AZs randomly in a region
// Defaults to Ordered
// +kubebuilder:default=Ordered
// +kubebuilder:validation:Enum=Ordered;Random
AvailabilityZoneSelection *AZSelectionScheme `json:"availabilityZoneSelection,omitempty"`
}
// String returns a string representation of the VPC.
func (v *VPCSpec) String() string {
return fmt.Sprintf("id=%s", v.ID)
}
// IsUnmanaged returns true if the VPC is unmanaged.
func (v *VPCSpec) IsUnmanaged(clusterName string) bool {
return v.ID != "" && !v.Tags.HasOwned(clusterName)
}
// IsManaged returns true if VPC is managed.
func (v *VPCSpec) IsManaged(clusterName string) bool {
return !v.IsUnmanaged(clusterName)
}
// SubnetSpec configures an AWS Subnet.
type SubnetSpec struct {
// ID defines a unique identifier to reference this resource.
ID string `json:"id,omitempty"`
// CidrBlock is the CIDR block to be used when the provider creates a managed VPC.
CidrBlock string `json:"cidrBlock,omitempty"`
// AvailabilityZone defines the availability zone to use for this subnet in the cluster's region.
AvailabilityZone string `json:"availabilityZone,omitempty"`
// IsPublic defines the subnet as a public subnet. A subnet is public when it is associated with a route table that has a route to an internet gateway.
// +optional
IsPublic bool `json:"isPublic"`
// RouteTableID is the routing table id associated with the subnet.
// +optional
RouteTableID *string `json:"routeTableId,omitempty"`
// NatGatewayID is the NAT gateway id associated with the subnet.
// Ignored unless the subnet is managed by the provider, in which case this is set on the public subnet where the NAT gateway resides. It is then used to determine routes for private subnets in the same AZ as the public subnet.
// +optional
NatGatewayID *string `json:"natGatewayId,omitempty"`
// Tags is a collection of tags describing the resource.
Tags Tags `json:"tags,omitempty"`
}
// String returns a string representation of the subnet.
func (s *SubnetSpec) String() string {
return fmt.Sprintf("id=%s/az=%s/public=%v", s.ID, s.AvailabilityZone, s.IsPublic)
}
// Subnets is a slice of Subnet.
type Subnets []SubnetSpec
// ToMap returns a map from id to subnet.
func (s Subnets) ToMap() map[string]*SubnetSpec {
res := make(map[string]*SubnetSpec)
for i := range s {
x := s[i]
res[x.ID] = &x
}
return res
}
// IDs returns a slice of the subnet ids.
func (s Subnets) IDs() []string {
res := []string{}
for _, subnet := range s {
res = append(res, subnet.ID)
}
return res
}
// FindByID returns a single subnet matching the given id or nil.
func (s Subnets) FindByID(id string) *SubnetSpec {
for _, x := range s {
if x.ID == id {
return &x
}
}
return nil
}
// FindEqual returns a subnet spec that is equal to the one passed in.
// Two subnets are defined equal to each other if their id is equal
// or if they are in the same vpc and the cidr block is the same.
func (s Subnets) FindEqual(spec *SubnetSpec) *SubnetSpec {
for _, x := range s {
if (spec.ID != "" && x.ID == spec.ID) || (spec.CidrBlock == x.CidrBlock) {
return &x
}
}
return nil
}
// FilterPrivate returns a slice containing all subnets marked as private.
func (s Subnets) FilterPrivate() (res Subnets) {
for _, x := range s {
if !x.IsPublic {
res = append(res, x)
}
}
return
}
// FilterPublic returns a slice containing all subnets marked as public.
func (s Subnets) FilterPublic() (res Subnets) {
for _, x := range s {
if x.IsPublic {
res = append(res, x)
}
}
return
}
// FilterByZone returns a slice containing all subnets that live in the availability zone specified.
func (s Subnets) FilterByZone(zone string) (res Subnets) {
for _, x := range s {
if x.AvailabilityZone == zone {
res = append(res, x)
}
}
return
}
// GetUniqueZones returns a slice containing the unique zones of the subnets.
func (s Subnets) GetUniqueZones() []string {
keys := make(map[string]bool)
zones := []string{}
for _, x := range s {
if _, value := keys[x.AvailabilityZone]; !value {
keys[x.AvailabilityZone] = true
zones = append(zones, x.AvailabilityZone)
}
}
return zones
}
// CNISpec defines configuration for CNI.
type CNISpec struct {
// CNIIngressRules specify rules to apply to control plane and worker node security groups.
// The source for the rule will be set to control plane and worker security group IDs.
CNIIngressRules CNIIngressRules `json:"cniIngressRules,omitempty"`
}
// CNIIngressRules is a slice of CNIIngressRule.
type CNIIngressRules []CNIIngressRule
// CNIIngressRule defines an AWS ingress rule for CNI requirements.
type CNIIngressRule struct {
Description string `json:"description"`
Protocol SecurityGroupProtocol `json:"protocol"`
FromPort int64 `json:"fromPort"`
ToPort int64 `json:"toPort"`
}
// RouteTable defines an AWS routing table.
type RouteTable struct {
ID string `json:"id"`
}
// SecurityGroupRole defines the unique role of a security group.
type SecurityGroupRole string
var (
// SecurityGroupBastion defines an SSH bastion role.
SecurityGroupBastion = SecurityGroupRole("bastion")
// SecurityGroupNode defines a Kubernetes workload node role.
SecurityGroupNode = SecurityGroupRole("node")
// SecurityGroupEKSNodeAdditional defines an extra node group from eks nodes.
SecurityGroupEKSNodeAdditional = SecurityGroupRole("node-eks-additional")
// SecurityGroupControlPlane defines a Kubernetes control plane node role.
SecurityGroupControlPlane = SecurityGroupRole("controlplane")
// SecurityGroupAPIServerLB defines a Kubernetes API Server Load Balancer role.
SecurityGroupAPIServerLB = SecurityGroupRole("apiserver-lb")
// SecurityGroupLB defines a container for the cloud provider to inject its load balancer ingress rules.
SecurityGroupLB = SecurityGroupRole("lb")
)
// SecurityGroup defines an AWS security group.
type SecurityGroup struct {
// ID is a unique identifier.
ID string `json:"id"`
// Name is the security group name.
Name string `json:"name"`
// IngressRules is the inbound rules associated with the security group.
// +optional
IngressRules IngressRules `json:"ingressRule,omitempty"`
// Tags is a map of tags associated with the security group.
Tags Tags `json:"tags,omitempty"`
}
// String returns a string representation of the security group.
func (s *SecurityGroup) String() string {
return fmt.Sprintf("id=%s/name=%s", s.ID, s.Name)
}
// SecurityGroupProtocol defines the protocol type for a security group rule.
type SecurityGroupProtocol string
var (
// SecurityGroupProtocolAll is a wildcard for all IP protocols.
SecurityGroupProtocolAll = SecurityGroupProtocol("-1")
// SecurityGroupProtocolIPinIP represents the IP in IP protocol in ingress rules.
SecurityGroupProtocolIPinIP = SecurityGroupProtocol("4")
// SecurityGroupProtocolTCP represents the TCP protocol in ingress rules.
SecurityGroupProtocolTCP = SecurityGroupProtocol("tcp")
// SecurityGroupProtocolUDP represents the UDP protocol in ingress rules.
SecurityGroupProtocolUDP = SecurityGroupProtocol("udp")
// SecurityGroupProtocolICMP represents the ICMP protocol in ingress rules.
SecurityGroupProtocolICMP = SecurityGroupProtocol("icmp")
// SecurityGroupProtocolICMPv6 represents the ICMPv6 protocol in ingress rules.
SecurityGroupProtocolICMPv6 = SecurityGroupProtocol("58")
)
// IngressRule defines an AWS ingress rule for security groups.
type IngressRule struct {
Description string `json:"description"`
Protocol SecurityGroupProtocol `json:"protocol"`
FromPort int64 `json:"fromPort"`
ToPort int64 `json:"toPort"`
// List of CIDR blocks to allow access from. Cannot be specified with SourceSecurityGroupID.
// +optional
CidrBlocks []string `json:"cidrBlocks,omitempty"`
// The security group id to allow access from. Cannot be specified with CidrBlocks.
// +optional
SourceSecurityGroupIDs []string `json:"sourceSecurityGroupIds,omitempty"`
}
// String returns a string representation of the ingress rule.
func (i *IngressRule) String() string {
return fmt.Sprintf("protocol=%s/range=[%d-%d]/description=%s", i.Protocol, i.FromPort, i.ToPort, i.Description)
}
// IngressRules is a slice of AWS ingress rules for security groups.
type IngressRules []IngressRule
// Difference returns the difference between this slice and the other slice.
func (i IngressRules) Difference(o IngressRules) (out IngressRules) {
for index := range i {
x := i[index]
found := false
for oIndex := range o {
y := o[oIndex]
if x.Equals(&y) {
found = true
break
}
}
if !found {
out = append(out, x)
}
}
return
}
// Equals returns true if two IngressRule are equal.
func (i *IngressRule) Equals(o *IngressRule) bool {
if len(i.CidrBlocks) != len(o.CidrBlocks) {
return false
}
sort.Strings(i.CidrBlocks)
sort.Strings(o.CidrBlocks)
for i, v := range i.CidrBlocks {
if v != o.CidrBlocks[i] {
return false
}
}
if len(i.SourceSecurityGroupIDs) != len(o.SourceSecurityGroupIDs) {
return false
}
sort.Strings(i.SourceSecurityGroupIDs)
sort.Strings(o.SourceSecurityGroupIDs)
for i, v := range i.SourceSecurityGroupIDs {
if v != o.SourceSecurityGroupIDs[i] {
return false
}
}
if i.Description != o.Description || i.Protocol != o.Protocol {
return false
}
// AWS seems to ignore the From/To port when set on protocols where it doesn't apply, but
// we avoid serializing it out for clarity's sake.
// See: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_IpPermission.html
switch i.Protocol {
case SecurityGroupProtocolTCP,
SecurityGroupProtocolUDP,
SecurityGroupProtocolICMP,
SecurityGroupProtocolICMPv6:
return i.FromPort == o.FromPort && i.ToPort == o.ToPort
case SecurityGroupProtocolAll, SecurityGroupProtocolIPinIP:
// FromPort / ToPort are not applicable
}
return true
}
| 1 | 20,857 | Our use of the terms `managed` and `unmanaged` in CAPA is interesting. I think we should probably update the docs (as part of a separate PR) to explain that we are referring to whether its CAPA managed infra. As opposed to meaning AWS managed service. | kubernetes-sigs-cluster-api-provider-aws | go |
@@ -246,7 +246,7 @@ def record_listens(request, data):
lookup = defaultdict(dict)
for key, value in data.items():
- if key == "sk" or key == "token" or key == "api_key" or key == "method":
+ if key == "sk" or key == "token" or key == "api_key" or key == "method" or key == "api_sig":
continue
matches = re.match('(.*)\[(\d+)\]', key)
if matches: | 1 | import time
import json
import re
from collections import defaultdict
from yattag import Doc
import yattag
from flask import Blueprint, request, render_template
from flask_login import login_required, current_user
from webserver.external import messybrainz
from webserver.rate_limiter import ratelimit
from webserver.errors import InvalidAPIUsage
import xmltodict
from api_tools import insert_payload
from db.lastfm_user import User
from db.lastfm_session import Session
from db.lastfm_token import Token
import calendar
from datetime import datetime
api_bp = Blueprint('api_compat', __name__)
@api_bp.route('/api/auth/', methods=['GET'])
@ratelimit()
@login_required
def api_auth():
""" Renders the token activation page.
"""
token = request.args['token']
return render_template(
"user/auth.html",
user_id=current_user.musicbrainz_id,
token=token
)
@api_bp.route('/api/auth/', methods=['POST'])
@ratelimit()
@login_required
def api_auth_approve():
""" Authenticate the user token provided.
"""
user = User.load_by_name(current_user.musicbrainz_id)
if "token" not in request.form:
return render_template(
"user/auth.html",
user_id=current_user.musicbrainz_id,
msg="Missing required parameters. Please provide correct parameters and try again."
)
token = Token.load(request.form['token'])
if not token:
return render_template(
"user/auth.html",
user_id=current_user.musicbrainz_id,
msg="Either this token is already used or invalid. Please try again."
)
if token.user:
return render_template(
"user/auth.html",
user_id=current_user.musicbrainz_id,
msg="This token is already approved. Please check the token and try again."
)
if token.has_expired():
return render_template(
"user/auth.html",
user_id=current_user.musicbrainz_id,
msg="This token has expired. Please create a new token and try again."
)
token.approve(user.name)
return render_template(
"user/auth.html",
user_id=current_user.musicbrainz_id,
msg="Token %s approved for user %s, press continue in client." % (token.token, current_user.musicbrainz_id)
)
@api_bp.route('/2.0/', methods=['POST', 'GET'])
@ratelimit()
def api_methods():
""" Receives both (GET & POST)-API calls and redirects them to appropriate methods.
"""
data = request.args if request.method == 'GET' else request.form
method = data['method'].lower()
if method in ('track.updatenowplaying', 'track.scrobble'):
return record_listens(request, data)
elif method == 'auth.getsession':
return get_session(request, data)
elif method == 'auth.gettoken':
return get_token(request, data)
elif method == 'user.getinfo':
return user_info(request, data)
elif method == 'auth.getsessioninfo':
return session_info
else:
# Invalid Method
raise InvalidAPIUsage(3, output_format=data.get('format', "xml"))
def session_info(request, data):
try:
sk = data['sk']
api_key = data['api_key']
output_format = data.get('format', 'xml')
username = data['username']
except KeyError:
raise InvalidAPIUsage(6, output_format=output_format) # Missing Required Params
session = Session.load(sk, api_key)
if (not session) or User.load_by_name(username).id != session.user.id:
raise InvalidAPIUsage(9, output_format=output_format) # Invalid Session KEY
print("SESSION INFO for session %s, user %s" % (session.id, session.user.name))
doc, tag, text = Doc().tagtext()
with tag('lfm', status='ok'):
with tag('application'):
with tag('session'):
with tag('name'):
text(session.user.name)
with tag('key'):
text(session.id)
with tag('subscriber'):
text('0')
with tag('country'):
text('US')
return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
output_format)
def get_token(request, data):
""" Issue a token to user after verying his API_KEY
"""
output_format = data.get('format', 'xml')
api_key = data.get('api_key')
if not api_key:
raise InvalidAPIUsage(6, output_format=output_format) # Missing required params
if not Token.is_valid_api_key(api_key):
raise InvalidAPIUsage(10, output_format=output_format) # Invalid API_KEY
token = Token.generate(api_key)
doc, tag, text = Doc().tagtext()
with tag('lfm', status='ok'):
with tag('token'):
text(token.token)
return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
output_format)
def get_session(request, data):
""" Create new session after validating the API_key and token.
"""
output_format = data.get('format', 'xml')
try:
api_key = data['api_key']
token = Token.load(data['token'], api_key)
except KeyError:
raise InvalidAPIUsage(6, output_format=output_format) # Missing Required Params
if not token:
if not Token.is_valid_api_key(api_key):
raise InvalidAPIUsage(10, output_format=output_format) # Invalid API_key
raise InvalidAPIUsage(4, output_format=output_format) # Invalid token
if token.has_expired():
raise InvalidAPIUsage(15, output_format=output_format) # Token expired
if not token.user:
raise InvalidAPIUsage(14, output_format=output_format) # Unauthorized token
session = Session.create(token)
doc, tag, text = Doc().tagtext()
with tag('lfm', status='ok'):
with tag('session'):
with tag('name'):
text(session.user.name)
with tag('key'):
text(session.sid)
with tag('subscriber'):
text('0')
return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
data.get('format', "xml"))
def _to_native_api(lookup, method="track.scrobble", output_format="xml"):
""" Converts the list of listens received in the new Last.fm submission format
to the native ListenBrainz API format.
Returns: type_of_listen and listen_payload
"""
listen_type = 'listens'
if method == 'track.updateNowPlaying':
listen_type = 'playing_now'
if len(lookup.keys()) != 1:
raise InvalidAPIUsage(6, output_format=output_format) # Invalid parameters
listens = []
for ind, data in lookup.iteritems():
listen = {
'track_metadata': {
'additional_info': {}
}
}
if 'artist' in data:
listen['track_metadata']['artist_name'] = data['artist']
if 'track' in data:
listen['track_metadata']['track_name'] = data['track']
if 'timestamp' in data:
listen['listened_at'] = data['timestamp']
if 'album' in data:
listen['track_metadata']['release_name'] = data['album']
if 'context' in data:
listen['track_metadata']['additional_info']['context'] = data['context']
if 'streamId' in data:
listen['track_metadata']['additional_info']['stream_id'] = data['streamId']
if 'trackNumber' in data:
listen['track_metadata']['additional_info']['tracknumber'] = data['trackNumber']
if 'mbid' in data:
listen['track_metadata']['release_mbid'] = data['mbid']
if 'duration' in data:
listen['track_metadata']['additional_info']['duration'] = data['duration']
# Choosen_by_user is 1 by default
listen['track_metadata']['additional_info']['choosen_by_user'] = data.get('choosenByUser', 1)
listens.append(listen)
return listen_type, listens
def record_listens(request, data):
""" Submit the listen in the lastfm format to be inserted in db.
Accepts listens for both track.updateNowPlaying and track.scrobble methods.
"""
output_format = data.get('format', 'xml')
try:
sk, api_key = data['sk'], data['api_key']
except KeyError:
raise InvalidAPIUsage(6, output_format=output_format) # Invalid parameters
session = Session.load(sk, api_key)
if not session:
if not Token.is_valid_api_key(api_key):
raise InvalidAPIUsage(10, output_format=output_format) # Invalid API_KEY
raise InvalidAPIUsage(9, output_format=output_format) # Invalid Session KEY
lookup = defaultdict(dict)
for key, value in data.items():
if key == "sk" or key == "token" or key == "api_key" or key == "method":
continue
matches = re.match('(.*)\[(\d+)\]', key)
if matches:
key = matches.group(1)
number = matches.group(2)
else:
number = 0
lookup[number][key] = value
if request.form['method'].lower() == 'track.updatenowplaying':
for i, listen in lookup.iteritems():
if 'timestamp' not in listen:
listen['timestamp'] = calendar.timegm(datetime.now().utctimetuple())
# Convert to native payload then submit 'em.
listen_type, native_payload = _to_native_api(lookup, data['method'], output_format)
augmented_listens = insert_payload(native_payload, str(session.user.id), listen_type=listen_type)
# With corrections than the original submitted listen.
doc, tag, text = Doc().tagtext()
with tag('lfm', status='ok'):
with tag('nowplaying' if listen_type == 'playing_now' else 'scrobbles'):
for origL, augL in zip(lookup.values(), augmented_listens):
corr = defaultdict(lambda: '0')
track = augL['track_metadata']['track_name']
if origL['track'] != augL['track_metadata']['track_name']:
corr['track'] = '1'
artist = augL['track_metadata']['artist_name']
if origL['artist'] != augL['track_metadata']['artist_name']:
corr['artist'] = '1'
ts = augL['listened_at']
albumArtist = artist
if origL.get('albumArtist', origL['artist']) != artist:
corr['albumArtist'] = '1'
# TODO: Add the album part
album = ""
with tag('scrobble'):
with tag('track', corrected=corr['track']):
text(track)
with tag('artist', corrected=corr['artist']):
text(artist)
with tag('album', corrected=corr['album']):
text(album)
with tag('albumArtist', corrected=corr['albumArtist']):
text(albumArtist)
with tag('timestamp'):
text(ts)
with tag('ignoredMessage', code="0"):
text('')
return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
output_format)
def format_response(data, format="xml"):
""" Convert the XML response to required format.
NOTE: The order of attributes may change while converting from XML to other formats.
NOTE: The rendering format for the error does not follow these rules and has been managed separately
in the error handlers.
The response is a translation of the XML response format, converted according to the
following rules:
1. Attributes are expressed as string member values with the attribute name as key.
2. Element child nodes are expressed as object members values with the node name as key.
3. Text child nodes are expressed as string values, unless the element also contains
attributes, in which case the text node is expressed as a string member value with the
key #text.
4. Repeated child nodes will be grouped as an array member with the shared node name as key.
(The #text notation is rarely used in XML responses.)
"""
if format == 'xml':
return data
elif format == 'json':
# Remove the <lfm> tag and its attributes
jsonData = xmltodict.parse(data)['lfm']
for k in jsonData.keys():
if k[0] == '@':
jsonData.pop(k)
def remove_attrib_prefix(data):
""" Filter the JSON response to merge some attributes and clean dict.
NOTE: This won't keep the dict ordered !!
"""
if not isinstance(data, dict):
return data
for k in data.keys():
if k[0] == "@":
data[k[1:]] = data.pop(k)
elif isinstance(data[k], basestring):
continue
elif isinstance(data[k], list):
for ind, item in enumerate(data[k]):
data[k][ind] = remove_attrib_prefix(item)
elif isinstance(data[k], dict):
data[k] = remove_attrib_prefix(data[k])
else:
print type(data[k])
return data
return json.dumps(remove_attrib_prefix(jsonData), indent=4)
def user_info(request, data):
""" Gives information about the user specified in the parameters.
"""
try:
api_key = data['api_key']
output_format = data.get('format', 'xml')
sk = data.get('sk')
username = data.get('user')
if not (sk or username):
raise KeyError
if not Token.is_valid_api_key(api_key):
raise InvalidAPIUsage(10, output_format=output_format) # Invalid API key
user = User.load_by_sessionkey(sk, api_key)
if not user:
raise InvalidAPIUsage(9, output_format=output_format) # Invalid Session key
query_user = User.load_by_name(username) if (username and username != user.name) else user
if not query_user:
raise InvalidAPIUsage(7, output_format=output_format) # Invalid resource specified
except KeyError:
raise InvalidAPIUsage(6, output_format=output_format) # Missing required params
doc, tag, text = Doc().tagtext()
with tag('lfm', status='ok'):
with tag('user'):
with tag('name'):
text(query_user.name)
with tag('realname'):
text(query_user.name)
with tag('url'):
text('http://listenbrainz.org/user/' + query_user.name)
with tag('playcount'):
text(User.get_play_count(query_user.id))
with tag('registered', unixtime=str(query_user.created.strftime("%s"))):
text(str(query_user.created))
return format_response('<?xml version="1.0" encoding="utf-8"?>\n' + yattag.indent(doc.getvalue()),
data.get('format', "xml"))
| 1 | 13,995 | Looks like all of these can be put into a list. | metabrainz-listenbrainz-server | py |
@@ -38,6 +38,8 @@ func CanonicalizeHeaderKey(k string) string {
type Headers struct {
// This representation allows us to make zero-value valid
items map[string]string
+ // map from canonicalized key to original key
+ keyMapping map[string]string
}
// NewHeaders builds a new Headers object. | 1 | // Copyright (c) 2018 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package transport
import "strings"
// CanonicalizeHeaderKey canonicalizes the given header key for storage into
// Headers.
func CanonicalizeHeaderKey(k string) string {
// TODO: Deal with unsupported header keys (anything that's not a valid HTTP
// header key).
return strings.ToLower(k)
}
// Headers is the transport-level representation of application headers.
//
// var headers transport.Headers
// headers = headers.With("foo", "bar")
// headers = headers.With("baz", "qux")
type Headers struct {
// This representation allows us to make zero-value valid
items map[string]string
}
// NewHeaders builds a new Headers object.
func NewHeaders() Headers {
return Headers{}
}
// NewHeadersWithCapacity allocates a new Headers object with the given
// capacity. A capacity of zero or less is ignored.
func NewHeadersWithCapacity(capacity int) Headers {
if capacity <= 0 {
return Headers{}
}
return Headers{items: make(map[string]string, capacity)}
}
// With returns a Headers object with the given key-value pair added to it.
//
// The returned object MAY not point to the same Headers underlying data store
// as the original Headers so the returned Headers MUST always be used instead
// of the original object.
//
// headers = headers.With("foo", "bar").With("baz", "qux")
func (h Headers) With(k, v string) Headers {
if h.items == nil {
h.items = make(map[string]string)
}
h.items[CanonicalizeHeaderKey(k)] = v
return h
}
// Del deletes the header with the given name from the Headers map.
//
// This is a no-op if the key does not exist.
func (h Headers) Del(k string) {
delete(h.items, CanonicalizeHeaderKey(k))
}
// Get retrieves the value associated with the given header name.
func (h Headers) Get(k string) (string, bool) {
v, ok := h.items[CanonicalizeHeaderKey(k)]
return v, ok
}
// Len returns the number of headers defined on this object.
func (h Headers) Len() int {
return len(h.items)
}
// Global empty map used by Items() for the case where h.items is nil.
var emptyMap = map[string]string{}
// Items returns the underlying map for this Headers object. The returned map
// MUST NOT be changed. Doing so will result in undefined behavior.
//
// Keys in the map are normalized using CanonicalizeHeaderKey.
func (h Headers) Items() map[string]string {
if h.items == nil {
return emptyMap
}
return h.items
}
// HeadersFromMap builds a new Headers object from the given map of header
// key-value pairs.
func HeadersFromMap(m map[string]string) Headers {
if len(m) == 0 {
return Headers{}
}
headers := NewHeadersWithCapacity(len(m))
for k, v := range m {
headers = headers.With(k, v)
}
return headers
}
| 1 | 16,153 | nit: "*mapping" for a map is unnecessary. Consider calling this `originalNames` or similar. | yarpc-yarpc-go | go |
@@ -171,11 +171,11 @@ class ProfilesDialog(wx.Dialog):
index = self.profileList.Selection
if gui.messageBox(
# Translators: The confirmation prompt displayed when the user requests to delete a configuration profile.
- _("Are you sure you want to delete this profile? This cannot be undone."),
+ _("This profile will be permanently deleted, this action cannot be undone."),
# Translators: The title of the confirmation dialog for deletion of a configuration profile.
_("Confirm Deletion"),
- wx.YES | wx.NO | wx.ICON_QUESTION, self
- ) == wx.NO:
+ wx.OK | wx.CANCEL | wx.ICON_QUESTION, self
+ ) != wx.OK:
return
name = self.profileNames[index]
try: | 1 | #gui/configProfiles.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2013 NV Access Limited
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
import wx
import config
import api
import gui
from logHandler import log
import appModuleHandler
import globalVars
import guiHelper
class ProfilesDialog(wx.Dialog):
shouldSuspendConfigProfileTriggers = True
_instance = None
def __new__(cls, *args, **kwargs):
# Make this a singleton.
if ProfilesDialog._instance is None:
return super(ProfilesDialog, cls).__new__(cls, *args, **kwargs)
return ProfilesDialog._instance
def __init__(self, parent):
if ProfilesDialog._instance is not None:
return
ProfilesDialog._instance = self
# Translators: The title of the Configuration Profiles dialog.
super(ProfilesDialog, self).__init__(parent, title=_("Configuration Profiles"))
self.currentAppName = (gui.mainFrame.prevFocus or api.getFocusObject()).appModule.appName
self.profileNames = [None]
self.profileNames.extend(config.conf.listProfiles())
mainSizer = wx.BoxSizer(wx.VERTICAL)
sHelper = guiHelper.BoxSizerHelper(self,orientation=wx.VERTICAL)
profilesListGroupSizer = wx.StaticBoxSizer(wx.StaticBox(self), wx.HORIZONTAL)
profilesListGroupContents = wx.BoxSizer(wx.HORIZONTAL)
#contains the profile list and activation button in vertical arrangement.
changeProfilesSizer = wx.BoxSizer(wx.VERTICAL)
item = self.profileList = wx.ListBox(self,
choices=[self.getProfileDisplay(name, includeStates=True) for name in self.profileNames])
item.Bind(wx.EVT_LISTBOX, self.onProfileListChoice)
item.Selection = self.profileNames.index(config.conf.profiles[-1].name)
changeProfilesSizer.Add(item, proportion=1.0)
changeProfilesSizer.AddSpacer(guiHelper.SPACE_BETWEEN_BUTTONS_VERTICAL)
self.changeStateButton = wx.Button(self)
self.changeStateButton.Bind(wx.EVT_BUTTON, self.onChangeState)
self.AffirmativeId = self.changeStateButton.Id
self.changeStateButton.SetDefault()
changeProfilesSizer.Add(self.changeStateButton)
profilesListGroupContents.Add(changeProfilesSizer, flag = wx.EXPAND)
profilesListGroupContents.AddSpacer(guiHelper.SPACE_BETWEEN_ASSOCIATED_CONTROL_HORIZONTAL)
buttonHelper = guiHelper.ButtonHelper(wx.VERTICAL)
# Translators: The label of a button to create a new configuration profile.
newButton = buttonHelper.addButton(self, label=_("&New"))
newButton.Bind(wx.EVT_BUTTON, self.onNew)
# Translators: The label of a button to rename a configuration profile.
self.renameButton = buttonHelper.addButton(self, label=_("&Rename"))
self.renameButton.Bind(wx.EVT_BUTTON, self.onRename)
# Translators: The label of a button to delete a configuration profile.
self.deleteButton = buttonHelper.addButton(self, label=_("&Delete"))
self.deleteButton.Bind(wx.EVT_BUTTON, self.onDelete)
profilesListGroupContents.Add(buttonHelper.sizer)
profilesListGroupSizer.Add(profilesListGroupContents, border=guiHelper.BORDER_FOR_DIALOGS, flag=wx.ALL)
sHelper.addItem(profilesListGroupSizer)
# Translators: The label of a button to manage triggers
# in the Configuration Profiles dialog.
# See the Configuration Profiles section of the User Guide for details.
triggersButton = wx.Button(self, label=_("&Triggers..."))
triggersButton.Bind(wx.EVT_BUTTON, self.onTriggers)
# Translators: The label of a checkbox in the Configuration Profiles dialog.
self.disableTriggersToggle = wx.CheckBox(self, label=_("Temporarily d&isable all triggers"))
self.disableTriggersToggle.Value = not config.conf.profileTriggersEnabled
sHelper.addItem(guiHelper.associateElements(triggersButton,self.disableTriggersToggle))
# Translators: The label of a button to close a dialog.
closeButton = wx.Button(self, wx.ID_CLOSE, label=_("&Close"))
closeButton.Bind(wx.EVT_BUTTON, lambda evt: self.Close())
sHelper.addDialogDismissButtons(closeButton)
self.Bind(wx.EVT_CLOSE, self.onClose)
self.EscapeId = wx.ID_CLOSE
if globalVars.appArgs.secure:
for item in newButton, triggersButton, self.renameButton, self.deleteButton:
item.Disable()
self.onProfileListChoice(None)
mainSizer.Add(sHelper.sizer, flag=wx.ALL, border=guiHelper.BORDER_FOR_DIALOGS)
mainSizer.Fit(self)
self.Sizer = mainSizer
self.profileList.SetFocus()
self.Center(wx.BOTH | wx.CENTER_ON_SCREEN)
def __del__(self):
ProfilesDialog._instance = None
def getProfileDisplay(self, name, includeStates=False):
# Translators: The item to select the user's normal configuration
# in the profile list in the Configuration Profiles dialog.
disp = name if name else _("(normal configuration)")
if includeStates:
disp += self.getProfileStates(name)
return disp
def getProfileStates(self, name):
try:
profile = config.conf.getProfile(name)
except KeyError:
return ""
states = []
editProfile = config.conf.profiles[-1]
if profile is editProfile:
# Translators: Reported for a profile which is being edited
# in the Configuration Profiles dialog.
states.append(_("editing"))
if name:
# This is a profile (not the normal configuration).
if profile.manual:
# Translators: Reported for a profile which has been manually activated
# in the Configuration Profiles dialog.
states.append(_("manual"))
if profile.triggered:
# Translators: Reported for a profile which is currently triggered
# in the Configuration Profiles dialog.
states.append(_("triggered"))
if states:
return " (%s)" % ", ".join(states)
return ""
def isProfileManual(self, name):
if not name:
return False
try:
profile = config.conf.getProfile(name)
except KeyError:
return False
return profile.manual
def onChangeState(self, evt):
sel = self.profileList.Selection
profile = self.profileNames[sel]
if self.isProfileManual(profile):
profile = None
try:
config.conf.manualActivateProfile(profile)
except:
# Translators: An error displayed when activating a configuration profile fails.
gui.messageBox(_("Error activating profile."),
_("Error"), wx.OK | wx.ICON_ERROR, self)
return
self.Close()
def onNew(self, evt):
self.Disable()
NewProfileDialog(self).Show()
def onDelete(self, evt):
index = self.profileList.Selection
if gui.messageBox(
# Translators: The confirmation prompt displayed when the user requests to delete a configuration profile.
_("Are you sure you want to delete this profile? This cannot be undone."),
# Translators: The title of the confirmation dialog for deletion of a configuration profile.
_("Confirm Deletion"),
wx.YES | wx.NO | wx.ICON_QUESTION, self
) == wx.NO:
return
name = self.profileNames[index]
try:
config.conf.deleteProfile(name)
except:
log.debugWarning("", exc_info=True)
# Translators: An error displayed when deleting a configuration profile fails.
gui.messageBox(_("Error deleting profile."),
_("Error"), wx.OK | wx.ICON_ERROR, self)
return
del self.profileNames[index]
self.profileList.Delete(index)
self.profileList.SetString(0, self.getProfileDisplay(None, includeStates=True))
self.profileList.Selection = 0
self.onProfileListChoice(None)
self.profileList.SetFocus()
def onProfileListChoice(self, evt):
sel = self.profileList.Selection
enable = sel > 0
name = self.profileNames[sel]
if self.isProfileManual(name):
# Translators: The label of the button to manually deactivate the selected profile
# in the Configuration Profiles dialog.
label = _("Manual deactivate")
else:
# Translators: The label of the button to manually activate the selected profile
# in the Configuration Profiles dialog.
label = _("Manual activate")
self.changeStateButton.Label = label
self.changeStateButton.Enabled = enable
if globalVars.appArgs.secure:
return
self.deleteButton.Enabled = enable
self.renameButton.Enabled = enable
def onRename(self, evt):
index = self.profileList.Selection
oldName = self.profileNames[index]
# Translators: The label of a field to enter a new name for a configuration profile.
with wx.TextEntryDialog(self, _("New name:"),
# Translators: The title of the dialog to rename a configuration profile.
_("Rename Profile"), defaultValue=oldName) as d:
if d.ShowModal() == wx.ID_CANCEL:
return
newName = api.filterFileName(d.Value)
try:
config.conf.renameProfile(oldName, newName)
except ValueError:
# Translators: An error displayed when renaming a configuration profile
# and a profile with the new name already exists.
gui.messageBox(_("That profile already exists. Please choose a different name."),
_("Error"), wx.OK | wx.ICON_ERROR, self)
return
except:
log.debugWarning("", exc_info=True)
gui.messageBox(_("Error renaming profile."),
_("Error"), wx.OK | wx.ICON_ERROR, self)
return
self.profileNames[index] = newName
self.profileList.SetString(index, self.getProfileDisplay(newName, includeStates=True))
self.profileList.Selection = index
self.profileList.SetFocus()
def onTriggers(self, evt):
self.Disable()
TriggersDialog(self).Show()
def getSimpleTriggers(self):
# Yields (spec, display, manualEdit)
yield ("app:%s" % self.currentAppName,
# Translators: Displayed for the configuration profile trigger for the current application.
# %s is replaced by the application executable name.
_("Current application (%s)") % self.currentAppName,
False)
# Translators: Displayed for the configuration profile trigger for say all.
yield "sayAll", _("Say all"), True
def onClose(self, evt):
if self.disableTriggersToggle.Value:
config.conf.disableProfileTriggers()
else:
config.conf.enableProfileTriggers()
self.Destroy()
def saveTriggers(self, parentWindow=None):
try:
config.conf.saveProfileTriggers()
except:
log.debugWarning("", exc_info=True)
# Translators: An error displayed when saving configuration profile triggers fails.
gui.messageBox(_("Error saving configuration profile triggers - probably read only file system."),
_("Error"), wx.OK | wx.ICON_ERROR, parent=parentWindow)
class TriggerInfo(object):
__slots__ = ("spec", "display", "profile")
def __init__(self, spec, display, profile):
self.spec = spec
self.display = display
self.profile = profile
class TriggersDialog(wx.Dialog):
def __init__(self, parent):
# Translators: The title of the configuration profile triggers dialog.
super(TriggersDialog, self).__init__(parent, title=_("Profile Triggers"))
mainSizer = wx.BoxSizer(wx.VERTICAL)
sHelper = guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
processed = set()
triggers = self.triggers = []
confTrigs = config.conf.triggersToProfiles
# Handle simple triggers.
for spec, disp, manualEdit in parent.getSimpleTriggers():
try:
profile = confTrigs[spec]
except KeyError:
profile = None
triggers.append(TriggerInfo(spec, disp, profile))
processed.add(spec)
# Handle all other triggers.
for spec, profile in confTrigs.iteritems():
if spec in processed:
continue
if spec.startswith("app:"):
# Translators: Displayed for a configuration profile trigger for an application.
# %s is replaced by the application executable name.
disp = _("%s application") % spec[4:]
else:
continue
triggers.append(TriggerInfo(spec, disp, profile))
# Translators: The label of the triggers list in the Configuration Profile Triggers dialog.
triggersText = _("Triggers")
triggerChoices = [trig.display for trig in triggers]
self.triggerList = sHelper.addLabeledControl(triggersText, wx.ListBox, choices=triggerChoices)
self.triggerList.Bind(wx.EVT_LISTBOX, self.onTriggerListChoice)
self.triggerList.Selection = 0
# Translators: The label of the profile list in the Configuration Profile Triggers dialog.
profileText = _("Profile")
profileChoices = [parent.getProfileDisplay(name) for name in parent.profileNames]
self.profileList = sHelper.addLabeledControl(profileText, wx.Choice, choices=profileChoices)
self.profileList.Bind(wx.EVT_CHOICE, self.onProfileListChoice)
closeButton = sHelper.addDialogDismissButtons(wx.Button(self, wx.ID_CLOSE, label=_("&Close")))
closeButton.Bind(wx.EVT_BUTTON, lambda evt: self.Close())
self.Bind(wx.EVT_CLOSE, self.onClose)
self.AffirmativeId = wx.ID_CLOSE
closeButton.SetDefault()
self.EscapeId = wx.ID_CLOSE
self.onTriggerListChoice(None)
mainSizer.Add(sHelper.sizer, border = guiHelper.BORDER_FOR_DIALOGS, flag=wx.ALL)
mainSizer.Fit(self)
self.Sizer = mainSizer
self.Center(wx.BOTH | wx.CENTER_ON_SCREEN)
def onTriggerListChoice(self, evt):
trig = self.triggers[self.triggerList.Selection]
try:
self.profileList.Selection = self.Parent.profileNames.index(trig.profile)
except ValueError:
log.error("Trigger %s: invalid profile %s"
% (trig.spec, trig.profile))
self.profileList.Selection = 0
trig.profile = None
def onProfileListChoice(self, evt):
trig = self.triggers[self.triggerList.Selection]
trig.profile = self.Parent.profileNames[evt.Selection]
def onClose(self, evt):
confTrigs = config.conf.triggersToProfiles
for trig in self.triggers:
if trig.profile:
confTrigs[trig.spec] = trig.profile
else:
try:
del confTrigs[trig.spec]
except KeyError:
pass
self.Parent.saveTriggers(parentWindow=self)
self.Parent.Enable()
self.Destroy()
class NewProfileDialog(wx.Dialog):
def __init__(self, parent):
# Translators: The title of the dialog to create a new configuration profile.
super(NewProfileDialog, self).__init__(parent, title=_("New Profile"))
mainSizer = wx.BoxSizer(wx.VERTICAL)
sHelper = guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
sizer = wx.BoxSizer(wx.HORIZONTAL)
# Translators: The label of a field to enter the name of a new configuration profile.
profileNameText = _("Profile name:")
self.profileName = sHelper.addLabeledControl(profileNameText, wx.TextCtrl)
# Translators: The label of a radio button to specify that a profile will be used for manual activation
# in the new configuration profile dialog.
self.triggers = triggers = [(None, _("Manual activation"), True)]
triggers.extend(parent.getSimpleTriggers())
self.triggerChoice = sHelper.addItem(wx.RadioBox(self, label=_("Use this profile for:"),
choices=[trig[1] for trig in triggers]))
self.triggerChoice.Bind(wx.EVT_RADIOBOX, self.onTriggerChoice)
self.autoProfileName = ""
self.onTriggerChoice(None)
sHelper.addDialogDismissButtons(self.CreateButtonSizer(wx.OK | wx.CANCEL))
self.Bind(wx.EVT_BUTTON, self.onOk, id=wx.ID_OK)
self.Bind(wx.EVT_BUTTON, self.onCancel, id=wx.ID_CANCEL)
mainSizer.Add(sHelper.sizer, border = guiHelper.BORDER_FOR_DIALOGS, flag=wx.ALL)
mainSizer.Fit(self)
self.Sizer = mainSizer
self.profileName.SetFocus()
self.Center(wx.BOTH | wx.CENTER_ON_SCREEN)
def onOk(self, evt):
confTrigs = config.conf.triggersToProfiles
spec, disp, manualEdit = self.triggers[self.triggerChoice.Selection]
if spec in confTrigs and gui.messageBox(
# Translators: The confirmation prompt presented when creating a new configuration profile
# and the selected trigger is already associated.
_("This trigger is already associated with another profile. "
"If you continue, it will be removed from that profile and associated with this one.\n"
"Are you sure you want to continue?"),
_("Warning"), wx.ICON_WARNING | wx.YES | wx.NO, self
) == wx.NO:
return
name = api.filterFileName(self.profileName.Value)
if not name:
return
try:
config.conf.createProfile(name)
except ValueError:
# Translators: An error displayed when the user attempts to create a configuration profile which already exists.
gui.messageBox(_("That profile already exists. Please choose a different name."),
_("Error"), wx.OK | wx.ICON_ERROR, self)
return
except:
log.debugWarning("", exc_info=True)
# Translators: An error displayed when creating a configuration profile fails.
gui.messageBox(_("Error creating profile - probably read only file system."),
_("Error"), wx.OK | wx.ICON_ERROR, self)
self.onCancel(evt)
return
if spec:
confTrigs[spec] = name
self.Parent.saveTriggers(parentWindow=self)
parent = self.Parent
if manualEdit:
if gui.messageBox(
# Translators: The prompt asking the user whether they wish to
# manually activate a configuration profile that has just been created.
_("To edit this profile, you will need to manually activate it. "
"Once you have finished editing, you will need to manually deactivate it to resume normal usage.\n"
"Do you wish to manually activate it now?"),
# Translators: The title of the confirmation dialog for manual activation of a created profile.
_("Manual Activation"), wx.YES | wx.NO | wx.ICON_QUESTION, self
) == wx.YES:
config.conf.manualActivateProfile(name)
else:
# Return to the Profiles dialog.
parent.profileNames.append(name)
parent.profileList.Append(name)
parent.profileList.Selection = parent.profileList.Count - 1
parent.onProfileListChoice(None)
parent.profileList.SetFocus()
parent.Enable()
self.Destroy()
return
else:
# Ensure triggers are enabled so the user can edit the profile.
config.conf.enableProfileTriggers()
# The user is done with the Profiles dialog;
# let them get on with editing the profile.
parent.Destroy()
def onCancel(self, evt):
self.Parent.Enable()
self.Destroy()
def onTriggerChoice(self, evt):
spec, disp, manualEdit = self.triggers[self.triggerChoice.Selection]
if not spec:
# Manual activation shouldn't guess a name.
name = ""
elif spec.startswith("app:"):
name = spec[4:]
else:
name = disp
if self.profileName.Value == self.autoProfileName:
# The user hasn't changed the automatically filled value.
self.profileName.Value = name
self.profileName.SelectAll()
self.autoProfileName = name
| 1 | 19,256 | Please split this into two sentences; i.e. "This profile will be permanently deleted. This action cannot be undone." | nvaccess-nvda | py |
@@ -173,9 +173,10 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
startPart = new Date();
if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) {
- lastAutosensResult = IobCobCalculatorPlugin.getPlugin().detectSensitivityWithLock(IobCobCalculatorPlugin.getPlugin().oldestDataAvailable(), System.currentTimeMillis());
+ lastAutosensResult = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin").autosensResult;
} else {
lastAutosensResult = new AutosensResult();
+ lastAutosensResult.sensResult = "autosens disabled";
}
Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart);
Profiler.log(log, "AMA data gathering", start); | 1 | package info.nightscout.androidaps.plugins.OpenAPSAMA;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.HardLimits;
import info.nightscout.utils.Profiler;
import info.nightscout.utils.Round;
/**
* Created by mike on 05.08.2016.
*/
public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
private static Logger log = LoggerFactory.getLogger(OpenAPSAMAPlugin.class);
private static OpenAPSAMAPlugin openAPSAMAPlugin;
public static OpenAPSAMAPlugin getPlugin() {
if (openAPSAMAPlugin == null) {
openAPSAMAPlugin = new OpenAPSAMAPlugin();
}
return openAPSAMAPlugin;
}
// last values
DetermineBasalAdapterAMAJS lastDetermineBasalAdapterAMAJS = null;
Date lastAPSRun = null;
DetermineBasalResultAMA lastAPSResult = null;
AutosensResult lastAutosensResult = null;
public OpenAPSAMAPlugin() {
super(new PluginDescription()
.mainType(PluginType.APS)
.fragmentClass(OpenAPSAMAFragment.class.getName())
.pluginName(R.string.openapsama)
.shortName(R.string.oaps_shortname)
.preferencesId(R.xml.pref_openapsama)
.description(R.string.description_ama)
);
}
@Override
public boolean specialEnableCondition() {
PumpInterface pump = ConfigBuilderPlugin.getActivePump();
return pump == null || pump.getPumpDescription().isTempBasalCapable;
}
@Override
public boolean specialShowInListCondition() {
PumpInterface pump = ConfigBuilderPlugin.getActivePump();
return pump == null || pump.getPumpDescription().isTempBasalCapable;
}
@Override
public APSResult getLastAPSResult() {
return lastAPSResult;
}
@Override
public Date getLastAPSRun() {
return lastAPSRun;
}
@Override
public void invoke(String initiator, boolean tempBasalFallback) {
log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
lastAPSResult = null;
DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS;
try {
determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(MainApp.instance().getBaseContext()));
} catch (IOException e) {
log.error(e.getMessage(), e);
return;
}
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
Profile profile = MainApp.getConfigBuilder().getProfile();
PumpInterface pump = ConfigBuilderPlugin.getActivePump();
if (profile == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
if (Config.logAPSResult)
log.debug(MainApp.gs(R.string.noprofileselected));
return;
}
if (!isEnabled(PluginType.APS)) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
if (Config.logAPSResult)
log.debug(MainApp.gs(R.string.openapsma_disabled));
return;
}
if (glucoseStatus == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
if (Config.logAPSResult)
log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
return;
}
String units = profile.getUnits();
double maxBasal = MainApp.getConstraintChecker().getMaxBasalAllowed(profile).value();
double minBg = Profile.toMgdl(profile.getTargetLow(), units);
double maxBg = Profile.toMgdl(profile.getTargetHigh(), units);
double targetBg = Profile.toMgdl(profile.getTarget(), units);
minBg = Round.roundTo(minBg, 0.1d);
maxBg = Round.roundTo(maxBg, 0.1d);
Date start = new Date();
Date startPart = new Date();
IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayInDia(profile);
Profiler.log(log, "calculateIobArrayInDia()", startPart);
startPart = new Date();
MealData mealData = TreatmentsPlugin.getPlugin().getMealData();
Profiler.log(log, "getMealData()", startPart);
double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value();
minBg = HardLimits.verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]);
maxBg = HardLimits.verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]);
targetBg = HardLimits.verifyHardLimits(targetBg, "targetBg", HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1]);
boolean isTempTarget = false;
TempTarget tempTarget = TreatmentsPlugin.getPlugin().getTempTargetFromHistory(System.currentTimeMillis());
if (tempTarget != null) {
isTempTarget = true;
minBg = HardLimits.verifyHardLimits(tempTarget.low, "minBg", HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1]);
maxBg = HardLimits.verifyHardLimits(tempTarget.high, "maxBg", HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1]);
targetBg = HardLimits.verifyHardLimits(tempTarget.target(), "targetBg", HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TEMP_TARGET_BG[1]);
}
if (!HardLimits.checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA))
return;
if (!HardLimits.checkOnlyHardLimits(profile.getIcTimeFromMidnight(profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC))
return;
if (!HardLimits.checkOnlyHardLimits(Profile.toMgdl(profile.getIsf(), units), "sens", HardLimits.MINISF, HardLimits.MAXISF))
return;
if (!HardLimits.checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.05, HardLimits.maxBasal()))
return;
if (!HardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
return;
startPart = new Date();
if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) {
lastAutosensResult = IobCobCalculatorPlugin.getPlugin().detectSensitivityWithLock(IobCobCalculatorPlugin.getPlugin().oldestDataAvailable(), System.currentTimeMillis());
} else {
lastAutosensResult = new AutosensResult();
}
Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart);
Profiler.log(log, "AMA data gathering", start);
start = new Date();
try {
determineBasalAdapterAMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, ConfigBuilderPlugin.getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData,
lastAutosensResult.ratio, //autosensDataRatio
isTempTarget
);
} catch (JSONException e) {
log.error("Unable to set data: " + e.toString());
}
DetermineBasalResultAMA determineBasalResultAMA = determineBasalAdapterAMAJS.invoke();
Profiler.log(log, "AMA calculation", start);
// Fix bug determine basal
if (determineBasalResultAMA.rate == 0d && determineBasalResultAMA.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress())
determineBasalResultAMA.tempBasalRequested = false;
// limit requests on openloop mode
if (!MainApp.getConstraintChecker().isClosedLoopAllowed().value()) {
long now = System.currentTimeMillis();
TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
if (activeTemp != null && determineBasalResultAMA.rate == 0 && determineBasalResultAMA.duration == 0) {
// going to cancel
} else if (activeTemp != null && Math.abs(determineBasalResultAMA.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < 0.1) {
determineBasalResultAMA.tempBasalRequested = false;
} else if (activeTemp == null && Math.abs(determineBasalResultAMA.rate - ConfigBuilderPlugin.getActivePump().getBaseBasalRate()) < 0.1)
determineBasalResultAMA.tempBasalRequested = false;
}
determineBasalResultAMA.iob = iobArray[0];
Date now = new Date();
try {
determineBasalResultAMA.json.put("timestamp", DateUtil.toISOString(now));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
lastDetermineBasalAdapterAMAJS = determineBasalAdapterAMAJS;
lastAPSResult = determineBasalResultAMA;
lastAPSRun = now;
MainApp.bus().post(new EventOpenAPSUpdateGui());
//deviceStatus.suggested = determineBasalResultAMA.json;
}
}
| 1 | 30,857 | NPE here and in other APS plugins | MilosKozak-AndroidAPS | java |
@@ -142,6 +142,9 @@ func getMsgKey(obj interface{}) (string, error) {
resourceType, _ := edgemessagelayer.GetResourceType(*msg)
resourceNamespace, _ := edgemessagelayer.GetNamespace(*msg)
resourceName, _ := edgemessagelayer.GetResourceName(*msg)
+ if msg.Router.Source == modules.DynamicControllerModuleName {
+ return strings.Join([]string{resourceType, resourceNamespace, resourceName, msg.Router.Source}, "/"), nil
+ }
return strings.Join([]string{resourceType, resourceNamespace, resourceName}, "/"), nil
}
| 1 | package channelq
import (
"fmt"
"strings"
"sync"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
"k8s.io/klog/v2"
beehiveContext "github.com/kubeedge/beehive/pkg/core/context"
beehiveModel "github.com/kubeedge/beehive/pkg/core/model"
reliablesyncslisters "github.com/kubeedge/kubeedge/cloud/pkg/client/listers/reliablesyncs/v1alpha1"
"github.com/kubeedge/kubeedge/cloud/pkg/cloudhub/common/model"
"github.com/kubeedge/kubeedge/cloud/pkg/common/modules"
"github.com/kubeedge/kubeedge/cloud/pkg/dynamiccontroller/application"
edgeconst "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/constants"
edgemessagelayer "github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/messagelayer"
"github.com/kubeedge/kubeedge/cloud/pkg/synccontroller"
commonconst "github.com/kubeedge/kubeedge/common/constants"
)
// ChannelMessageQueue is the channel implementation of MessageQueue
type ChannelMessageQueue struct {
queuePool sync.Map
storePool sync.Map
listQueuePool sync.Map
listStorePool sync.Map
objectSyncLister reliablesyncslisters.ObjectSyncLister
clusterObjectSyncLister reliablesyncslisters.ClusterObjectSyncLister
}
// NewChannelMessageQueue initializes a new ChannelMessageQueue
func NewChannelMessageQueue(objectSyncLister reliablesyncslisters.ObjectSyncLister, clusterObjectSyncLister reliablesyncslisters.ClusterObjectSyncLister) *ChannelMessageQueue {
return &ChannelMessageQueue{
objectSyncLister: objectSyncLister,
clusterObjectSyncLister: clusterObjectSyncLister,
}
}
// DispatchMessage gets the message from the cloud, extracts the
// node id from it, gets the message associated with the node
// and pushes the message to the queue
func (q *ChannelMessageQueue) DispatchMessage() {
for {
select {
case <-beehiveContext.Done():
klog.Warning("Cloudhub channel eventqueue dispatch message loop stoped")
return
default:
}
msg, err := beehiveContext.Receive(model.SrcCloudHub)
klog.V(4).Infof("[cloudhub] dispatchMessage to edge: %+v", msg)
if err != nil {
klog.Info("receive not Message format message")
continue
}
nodeID, err := GetNodeID(&msg)
if nodeID == "" || err != nil {
klog.Warning("node id is not found in the message")
continue
}
if isListResource(&msg) {
q.addListMessageToQueue(nodeID, &msg)
} else {
q.addMessageToQueue(nodeID, &msg)
}
}
}
func (q *ChannelMessageQueue) addListMessageToQueue(nodeID string, msg *beehiveModel.Message) {
nodeListQueue := q.GetNodeListQueue(nodeID)
nodeListStore := q.GetNodeListStore(nodeID)
messageKey, _ := getListMsgKey(msg)
if err := nodeListStore.Add(msg); err != nil {
klog.Errorf("failed to add msg: %s", err)
return
}
nodeListQueue.Add(messageKey)
}
func (q *ChannelMessageQueue) addMessageToQueue(nodeID string, msg *beehiveModel.Message) {
if msg.GetResourceVersion() == "" && !isDeleteMessage(msg) {
return
}
nodeQueue := q.GetNodeQueue(nodeID)
nodeStore := q.GetNodeStore(nodeID)
messageKey, err := getMsgKey(msg)
if err != nil {
klog.Errorf("fail to get message key for message: %s", msg.Header.ID)
return
}
//if the operation is delete, force to sync the resource message
//if the operation is response, force to sync the resource message, since the edgecore requests it
if !isDeleteMessage(msg) && msg.GetOperation() != beehiveModel.ResponseOperation {
item, exist, _ := nodeStore.GetByKey(messageKey)
// If the message doesn't exist in the store, then compare it with
// the version stored in the database
if !exist {
resourceNamespace, _ := edgemessagelayer.GetNamespace(*msg)
resourceUID, err := GetMessageUID(*msg)
if err != nil {
klog.Errorf("fail to get message UID for message: %s", msg.Header.ID)
return
}
objectSync, err := q.objectSyncLister.ObjectSyncs(resourceNamespace).Get(synccontroller.BuildObjectSyncName(nodeID, resourceUID))
if err == nil && objectSync.Status.ObjectResourceVersion != "" && synccontroller.CompareResourceVersion(msg.GetResourceVersion(), objectSync.Status.ObjectResourceVersion) <= 0 {
return
}
}
// Check if message is older than already in store, if it is, discard it directly
if exist {
msgInStore := item.(*beehiveModel.Message)
if isDeleteMessage(msgInStore) || synccontroller.CompareResourceVersion(msg.GetResourceVersion(), msgInStore.GetResourceVersion()) <= 0 {
return
}
}
}
if err := nodeStore.Add(msg); err != nil {
klog.Errorf("fail to add message %v nodeStore, err: %v", msg, err)
return
}
nodeQueue.Add(messageKey)
}
func getMsgKey(obj interface{}) (string, error) {
msg := obj.(*beehiveModel.Message)
if msg.GetGroup() == edgeconst.GroupResource {
resourceType, _ := edgemessagelayer.GetResourceType(*msg)
resourceNamespace, _ := edgemessagelayer.GetNamespace(*msg)
resourceName, _ := edgemessagelayer.GetResourceName(*msg)
return strings.Join([]string{resourceType, resourceNamespace, resourceName}, "/"), nil
}
return "", fmt.Errorf("failed to get message key")
}
func getListMsgKey(obj interface{}) (string, error) {
msg := obj.(*beehiveModel.Message)
return msg.Header.ID, nil
}
func isListResource(msg *beehiveModel.Message) bool {
msgResource := msg.GetResource()
if strings.Contains(msgResource, beehiveModel.ResourceTypePodlist) ||
strings.Contains(msgResource, "membership") ||
strings.Contains(msgResource, "twin/cloud_updated") ||
strings.Contains(msgResource, beehiveModel.ResourceTypeServiceAccountToken) {
return true
}
if msg.Router.Operation == application.ApplicationResp {
return true
}
if msg.GetOperation() == beehiveModel.ResponseOperation {
content, ok := msg.Content.(string)
if ok && content == commonconst.MessageSuccessfulContent {
return true
}
}
if msg.GetSource() == modules.EdgeControllerModuleName {
resourceType, _ := edgemessagelayer.GetResourceType(*msg)
if resourceType == beehiveModel.ResourceTypeNode {
return true
}
}
// user data
if msg.GetGroup() == modules.UserGroup {
return true
}
return false
}
func isDeleteMessage(msg *beehiveModel.Message) bool {
if msg.GetOperation() == beehiveModel.DeleteOperation {
return true
}
deletionTimestamp, err := GetMessageDeletionTimestamp(msg)
if err != nil {
klog.Errorf("fail to get message DeletionTimestamp for message: %s", msg.Header.ID)
return false
} else if deletionTimestamp != nil {
return true
}
return false
}
// GetNodeID from "beehive/pkg/core/model".Message.Router.Resource
func GetNodeID(msg *beehiveModel.Message) (string, error) {
resource := msg.Router.Resource
tokens := strings.Split(resource, commonconst.ResourceSep)
numOfTokens := len(tokens)
for i, token := range tokens {
if token == model.ResNode && i+1 < numOfTokens && tokens[i+1] != "" {
return tokens[i+1], nil
}
}
return "", fmt.Errorf("no nodeID in Message.Router.Resource: %s", resource)
}
// Connect allocates the queues and stores for given node
func (q *ChannelMessageQueue) Connect(info *model.HubInfo) {
_, queueExist := q.queuePool.Load(info.NodeID)
_, storeExit := q.storePool.Load(info.NodeID)
_, listQueueExist := q.listQueuePool.Load(info.NodeID)
_, listStoreExit := q.listStorePool.Load(info.NodeID)
if queueExist && storeExit && listQueueExist && listStoreExit {
klog.Infof("Message queue and store for edge node %s are already exist", info.NodeID)
return
}
if !queueExist {
nodeQueue := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), info.NodeID)
q.queuePool.Store(info.NodeID, nodeQueue)
}
if !storeExit {
nodeStore := cache.NewStore(getMsgKey)
q.storePool.Store(info.NodeID, nodeStore)
}
if !listQueueExist {
nodeListQueue := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), info.NodeID)
q.listQueuePool.Store(info.NodeID, nodeListQueue)
}
if !listStoreExit {
nodeListStore := cache.NewStore(getListMsgKey)
q.listStorePool.Store(info.NodeID, nodeListStore)
}
}
// Close closes queues and stores for given node
func (q *ChannelMessageQueue) Close(info *model.HubInfo) {
_, queueExist := q.queuePool.Load(info.NodeID)
_, storeExist := q.storePool.Load(info.NodeID)
_, listQueueExist := q.listQueuePool.Load(info.NodeID)
_, listStoreExit := q.listStorePool.Load(info.NodeID)
if !queueExist && !storeExist && !listQueueExist && !listStoreExit {
klog.Warningf("rChannel for edge node %s is already removed", info.NodeID)
return
}
if queueExist {
q.queuePool.Delete(info.NodeID)
}
if storeExist {
q.storePool.Delete(info.NodeID)
}
if listQueueExist {
q.listQueuePool.Delete(info.NodeID)
}
if listStoreExit {
q.listStorePool.Delete(info.NodeID)
}
}
// Publish sends message via the channel to Controllers
func (q *ChannelMessageQueue) Publish(msg *beehiveModel.Message) error {
switch msg.Router.Source {
case application.MetaServerSource:
beehiveContext.Send(modules.DynamicControllerModuleName, *msg)
case model.ResTwin:
beehiveContext.SendToGroup(model.SrcDeviceController, *msg)
default:
beehiveContext.SendToGroup(model.SrcEdgeController, *msg)
}
return nil
}
// GetNodeQueue returns the queue for given node
func (q *ChannelMessageQueue) GetNodeQueue(nodeID string) workqueue.RateLimitingInterface {
queue, ok := q.queuePool.Load(nodeID)
if !ok {
klog.Warningf("nodeQueue for edge node %s not found and created now", nodeID)
nodeQueue := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), nodeID)
q.queuePool.Store(nodeID, nodeQueue)
return nodeQueue
}
nodeQueue := queue.(workqueue.RateLimitingInterface)
return nodeQueue
}
// GetNodeListQueue returns the listQueue for given node
func (q *ChannelMessageQueue) GetNodeListQueue(nodeID string) workqueue.RateLimitingInterface {
queue, ok := q.listQueuePool.Load(nodeID)
if !ok {
klog.Warningf("nodeListQueue for edge node %s not found and created now", nodeID)
nodeListQueue := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), nodeID)
q.listQueuePool.Store(nodeID, nodeListQueue)
return nodeListQueue
}
nodeListQueue := queue.(workqueue.RateLimitingInterface)
return nodeListQueue
}
// GetNodeStore returns the store for given node
func (q *ChannelMessageQueue) GetNodeStore(nodeID string) cache.Store {
store, ok := q.storePool.Load(nodeID)
if !ok {
klog.Warningf("nodeStore for edge node %s not found and created now", nodeID)
nodeStore := cache.NewStore(getMsgKey)
q.storePool.Store(nodeID, nodeStore)
return nodeStore
}
nodeStore := store.(cache.Store)
return nodeStore
}
// GetNodeListStore returns the listStore for given node
func (q *ChannelMessageQueue) GetNodeListStore(nodeID string) cache.Store {
store, ok := q.listStorePool.Load(nodeID)
if !ok {
klog.Warningf("nodeListStore for edge node %s not found and created now", nodeID)
nodeListStore := cache.NewStore(getListMsgKey)
q.listStorePool.Store(nodeID, nodeListStore)
return nodeListStore
}
nodeListStore := store.(cache.Store)
return nodeListStore
}
// GetMessageUID returns the UID of the object in message
func GetMessageUID(msg beehiveModel.Message) (string, error) {
accessor, err := meta.Accessor(msg.Content)
if err != nil {
return "", err
}
return string(accessor.GetUID()), nil
}
// GetMessageDeletionTimestamp returns the deletionTimestamp of the object in message
func GetMessageDeletionTimestamp(msg *beehiveModel.Message) (*metav1.Time, error) {
accessor, err := meta.Accessor(msg.Content)
if err != nil {
return nil, err
}
return accessor.GetDeletionTimestamp(), nil
}
| 1 | 22,901 | Thanks for the fixing, and could you please provide more details for this bug? Because we have the deduplication mechanism in cloudhub, so it will has no problem. | kubeedge-kubeedge | go |
@@ -52,6 +52,10 @@ public class ViewSettings extends MainWindowView {
private static final String CAPTION_TITLE_CSS_CLASS = "captionTitle";
private static final String CONFIGURATION_PANE_CSS_CLASS = "containerConfigurationPane";
private static final String TITLE_CSS_CLASS = "title";
+ private String applicationName;
+ private String applicationVersion;
+ private String applicationGitRevision;
+ private String applicationBuildTimestamp;
private final ObservableList<String> repositories = FXCollections.observableArrayList();
private ComboBox<Theme> themes;
private Consumer<Settings> onSave; | 1 | /*
* Copyright (C) 2015-2017 PÂRIS Quentin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.phoenicis.javafx.views.mainwindow.settings;
import javafx.geometry.Insets;
import org.phoenicis.javafx.views.common.ThemeManager;
import org.phoenicis.settings.Setting;
import org.phoenicis.settings.Settings;
import org.phoenicis.javafx.views.common.TextWithStyle;
import org.phoenicis.javafx.views.common.Theme;
import org.phoenicis.javafx.views.mainwindow.MainWindowView;
import org.phoenicis.javafx.views.mainwindow.MessagePanel;
import org.phoenicis.javafx.views.mainwindow.ui.LeftGroup;
import org.phoenicis.javafx.views.mainwindow.ui.LeftToggleButton;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.VPos;
import javafx.scene.control.*;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.util.StringConverter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import static org.phoenicis.configuration.localisation.Localisation.translate;
public class ViewSettings extends MainWindowView {
private static final String CAPTION_TITLE_CSS_CLASS = "captionTitle";
private static final String CONFIGURATION_PANE_CSS_CLASS = "containerConfigurationPane";
private static final String TITLE_CSS_CLASS = "title";
private final ObservableList<String> repositories = FXCollections.observableArrayList();
private ComboBox<Theme> themes;
private Consumer<Settings> onSave;
private Settings settings = new Settings();
private MessagePanel selectSettingsPanel;
private VBox uiPanel = new VBox();
private VBox repositoriesPanel = new VBox();
private VBox fileAssociationsPanel = new VBox();
private VBox networkPanel = new VBox();
public ViewSettings(ThemeManager themeManager) {
super("Settings", themeManager);
final List<LeftToggleButton> leftButtonList = new ArrayList<>();
ToggleGroup group = new ToggleGroup();
final LeftToggleButton uiButton = new LeftToggleButton("User Interface");
final String uiButtonIcon = "icons/mainwindow/settings/userInterface.png";
uiButton.setStyle("-fx-background-image: url('" + themeManager.getResourceUrl(uiButtonIcon) + "');");
uiButton.setToggleGroup(group);
leftButtonList.add(uiButton);
uiButton.setOnMouseClicked(event -> showRightView(uiPanel));
final LeftToggleButton repositoriesButton = new LeftToggleButton("Repositories");
final String repositoriesButtonIcon = "icons/mainwindow/settings/repository.png";
repositoriesButton.setStyle("-fx-background-image: url('" + themeManager.getResourceUrl(repositoriesButtonIcon) + "');");
repositoriesButton.setToggleGroup(group);
leftButtonList.add(repositoriesButton);
repositoriesButton.setOnMouseClicked(event -> showRightView(repositoriesPanel));
final LeftToggleButton fileAssociationsButton = new LeftToggleButton("File Associations");
final String fileAssociationsButtonIcon = "icons/mainwindow/settings/settings.png";
fileAssociationsButton.setStyle("-fx-background-image: url('" + themeManager.getResourceUrl(fileAssociationsButtonIcon) + "');");
fileAssociationsButton.setToggleGroup(group);
leftButtonList.add(fileAssociationsButton);
fileAssociationsButton.setOnMouseClicked(event -> showRightView(fileAssociationsPanel));
final LeftToggleButton networkButton = new LeftToggleButton("Network");
final String networkButtonIcon = "icons/mainwindow/settings/network.png";
networkButton.setStyle("-fx-background-image: url('" + themeManager.getResourceUrl(networkButtonIcon) + "');");
networkButton.setToggleGroup(group);
leftButtonList.add(networkButton);
networkButton.setOnMouseClicked(event -> showRightView(networkPanel));
final LeftGroup leftButtons = new LeftGroup("Settings");
leftButtons.setNodes(leftButtonList);
addToSideBar(leftButtons);
super.drawSideBar();
initUiSettingsPane();
initRepositoriesSettingsPane();
initFileAssociationsPane();
initNetworkPane();
initSelectSettingsPane();
showRightView(this.selectSettingsPanel);
}
private void initUiSettingsPane() {
uiPanel = new VBox();
uiPanel.getStyleClass().add(CONFIGURATION_PANE_CSS_CLASS);
final Text title = new TextWithStyle(translate("User Interface Settings"), TITLE_CSS_CLASS);
uiPanel.getChildren().add(title);
final GridPane gridPane = new GridPane();
gridPane.getStyleClass().add("grid");
gridPane.add(new TextWithStyle(translate("Theme:"), CAPTION_TITLE_CSS_CLASS), 0, 0);
themes = new ComboBox<>();
themes.getItems().setAll(Theme.values());
themes.setOnAction(event -> {
this.handleThemeChange(event);
this.save();}
);
gridPane.add(themes, 1, 0);
gridPane.setHgap(20);
gridPane.setVgap(10);
uiPanel.getChildren().add(gridPane);
final Label restartHint = new Label(translate("If you change the theme, please restart to load the icons of the new theme."));
restartHint.setPadding(new Insets(10));
uiPanel.getChildren().add(restartHint);
}
private void initRepositoriesSettingsPane() {
repositoriesPanel = new VBox();
repositoriesPanel.getStyleClass().add(CONFIGURATION_PANE_CSS_CLASS);
final Text title = new TextWithStyle(translate("Repositories Settings"), TITLE_CSS_CLASS);
repositoriesPanel.getChildren().add(title);
final GridPane gridPane = new GridPane();
gridPane.getStyleClass().add("grid");
TextWithStyle repositoryText = new TextWithStyle(translate("Repository:"), CAPTION_TITLE_CSS_CLASS);
gridPane.add(repositoryText, 0, 0);
GridPane.setValignment(repositoryText, VPos.TOP);
VBox repositoryLayout = new VBox();
repositoryLayout.setSpacing(5);
ListView<String> repositoryListView = new ListView<>(repositories);
repositoryListView.setPrefSize(400, 100);
repositoryListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
repositoryListView.setEditable(true);
repositoryListView.setCellFactory(param -> new TextFieldListCell<>(new StringConverter<String>() {
@Override
public String toString(String object) {
return object;
}
@Override
public String fromString(String string) {
return string;
}
}));
HBox repositoryButtonLayout = new HBox();
repositoryButtonLayout.setSpacing(5);
Button addButton = new Button();
addButton.setText("Add");
addButton.setOnAction((ActionEvent event) -> {
TextInputDialog dialog = new TextInputDialog();
dialog.initOwner(getContent().getScene().getWindow());
dialog.setTitle("Add repository");
dialog.setHeaderText("Add repository");
dialog.setContentText("Please add the new repository:");
Optional<String> result = dialog.showAndWait();
result.ifPresent(repositories::add);
this.save();
});
Button removeButton = new Button();
removeButton.setText("Remove");
removeButton.setOnAction((ActionEvent event) -> {
repositories.removeAll(repositoryListView.getSelectionModel().getSelectedItems());
this.save();
});
repositoryButtonLayout.getChildren().addAll(addButton, removeButton);
repositoryLayout.getChildren().addAll(repositoryListView, repositoryButtonLayout);
gridPane.add(repositoryLayout, 1, 0);
gridPane.setHgap(20);
gridPane.setVgap(10);
repositoriesPanel.getChildren().add(gridPane);
}
private void initFileAssociationsPane() {
}
private void initNetworkPane() {
}
public void setSettings(Settings settings) {
final Theme setTheme = Theme.fromShortName(settings.get(Setting.THEME));
themes.setValue(setTheme);
repositories.addAll(settings.get(Setting.REPOSITORY).split(";"));
}
public void setOnSave(Consumer<Settings> onSave) {
this.onSave = onSave;
}
private void initSelectSettingsPane() {
this.selectSettingsPanel = new MessagePanel(translate("Please select a settings category"));
}
private void save() {
settings.set(Setting.THEME, themes.getSelectionModel().getSelectedItem().getShortName());
StringBuilder stringBuilder = new StringBuilder();
for (String repository : repositories) {
stringBuilder.append(repository).append(";");
}
settings.set(Setting.REPOSITORY, stringBuilder.toString());
onSave.accept(this.settings);
}
private void handleThemeChange(ActionEvent evt) {
final Theme theme = themes.getSelectionModel().getSelectedItem();
themeManager.setCurrentTheme(theme);
final String shortName = theme.getShortName();
final String url = String.format("/org/phoenicis/javafx/themes/%s/main.css", shortName);
final URL style = this.getClass().getResource(url);
getContent().getScene().getStylesheets().clear();
getContent().getScene().getStylesheets().add(style.toExternalForm());
}
}
| 1 | 9,070 | These could be final | PhoenicisOrg-phoenicis | java |
@@ -103,7 +103,7 @@ public abstract class AbstractRestInvocation {
@SuppressWarnings("unchecked")
Map<String, String> cseContext =
JsonUtils.readValue(strCseContext.getBytes(StandardCharsets.UTF_8), Map.class);
- invocation.setContext(cseContext);
+ invocation.addContext(cseContext);
}
public String getContext(String key) { | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicecomb.common.rest;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CompletableFuture;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.lang3.StringUtils;
import org.apache.servicecomb.common.rest.codec.produce.ProduceProcessor;
import org.apache.servicecomb.common.rest.codec.produce.ProduceProcessorManager;
import org.apache.servicecomb.common.rest.definition.RestOperationMeta;
import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
import org.apache.servicecomb.common.rest.filter.HttpServerFilterBeforeSendResponseExecutor;
import org.apache.servicecomb.common.rest.locator.OperationLocator;
import org.apache.servicecomb.common.rest.locator.ServicePathManager;
import org.apache.servicecomb.core.Const;
import org.apache.servicecomb.core.Invocation;
import org.apache.servicecomb.core.definition.MicroserviceMeta;
import org.apache.servicecomb.core.definition.OperationMeta;
import org.apache.servicecomb.foundation.common.utils.JsonUtils;
import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
import org.apache.servicecomb.foundation.vertx.http.HttpServletResponseEx;
import org.apache.servicecomb.swagger.invocation.Response;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractRestInvocation {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRestInvocation.class);
public static final String UNKNOWN_OPERATION_ID = "UNKNOWN_OPERATION";
protected long start;
protected RestOperationMeta restOperationMeta;
protected Invocation invocation;
protected HttpServletRequestEx requestEx;
protected HttpServletResponseEx responseEx;
protected ProduceProcessor produceProcessor;
protected List<HttpServerFilter> httpServerFilters = Collections.emptyList();
public AbstractRestInvocation() {
this.start = System.nanoTime();
}
public void setHttpServerFilters(List<HttpServerFilter> httpServerFilters) {
this.httpServerFilters = httpServerFilters;
}
protected void findRestOperation(MicroserviceMeta microserviceMeta) {
ServicePathManager servicePathManager = ServicePathManager.getServicePathManager(microserviceMeta);
if (servicePathManager == null) {
LOGGER.error("No schema defined for {}:{}.", microserviceMeta.getAppId(), microserviceMeta.getName());
throw new InvocationException(Status.NOT_FOUND, Status.NOT_FOUND.getReasonPhrase());
}
OperationLocator locator = locateOperation(servicePathManager);
requestEx.setAttribute(RestConst.PATH_PARAMETERS, locator.getPathVarMap());
this.restOperationMeta = locator.getOperation();
}
protected void initProduceProcessor() {
produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx);
if (produceProcessor == null) {
String msg = String.format("Accept %s is not supported", requestEx.getHeader(HttpHeaders.ACCEPT));
throw new InvocationException(Status.NOT_ACCEPTABLE, msg);
}
}
protected void setContext() throws Exception {
String strCseContext = requestEx.getHeader(Const.CSE_CONTEXT);
if (StringUtils.isEmpty(strCseContext)) {
return;
}
@SuppressWarnings("unchecked")
Map<String, String> cseContext =
JsonUtils.readValue(strCseContext.getBytes(StandardCharsets.UTF_8), Map.class);
invocation.setContext(cseContext);
}
public String getContext(String key) {
if (null == invocation || null == invocation.getContext()) {
return null;
}
return invocation.getContext(key);
}
protected void scheduleInvocation() {
try {
createInvocation();
} catch (IllegalStateException e) {
sendFailResponse(e);
return;
}
invocation.onStart(requestEx, start);
invocation.getInvocationStageTrace().startSchedule();
OperationMeta operationMeta = restOperationMeta.getOperationMeta();
operationMeta.getExecutor().execute(() -> {
synchronized (this.requestEx) {
try {
if (isInQueueTimeout()) {
throw new InvocationException(Status.INTERNAL_SERVER_ERROR, "Timeout when processing the request.");
}
if (requestEx.getAttribute(RestConst.REST_REQUEST) != requestEx) {
// already timeout
// in this time, request maybe recycled and reused by web container, do not use requestEx
LOGGER.error("Rest request already timeout, abandon execute, method {}, operation {}.",
operationMeta.getHttpMethod(),
operationMeta.getMicroserviceQualifiedName());
return;
}
runOnExecutor();
} catch (Throwable e) {
LOGGER.error("rest server onRequest error", e);
sendFailResponse(e);
}
}
});
}
private boolean isInQueueTimeout() {
return System.nanoTime() - invocation.getInvocationStageTrace().getStart() >
CommonRestConfig.getRequestWaitInPoolTimeout() * 1_000_000;
}
protected void runOnExecutor() {
invocation.onExecuteStart();
invoke();
}
protected abstract OperationLocator locateOperation(ServicePathManager servicePathManager);
// create a invocation without args setted
protected abstract void createInvocation();
public void invoke() {
try {
Response response = prepareInvoke();
if (response != null) {
sendResponseQuietly(response);
return;
}
doInvoke();
} catch (Throwable e) {
LOGGER.error("unknown rest exception.", e);
sendFailResponse(e);
}
}
protected Response prepareInvoke() throws Throwable {
this.initProduceProcessor();
this.setContext();
invocation.getHandlerContext().put(RestConst.REST_REQUEST, requestEx);
invocation.getInvocationStageTrace().startServerFiltersRequest();
for (HttpServerFilter filter : httpServerFilters) {
if (filter.enabled()) {
Response response = filter.afterReceiveRequest(invocation, requestEx);
if (response != null) {
return response;
}
}
}
return null;
}
protected void doInvoke() throws Throwable {
invocation.getInvocationStageTrace().startHandlersRequest();
invocation.next(resp -> {
sendResponseQuietly(resp);
});
}
public void sendFailResponse(Throwable throwable) {
if (produceProcessor == null) {
produceProcessor = ProduceProcessorManager.DEFAULT_PROCESSOR;
}
Response response = Response.createProducerFail(throwable);
sendResponseQuietly(response);
}
protected void sendResponseQuietly(Response response) {
if (invocation != null) {
invocation.getInvocationStageTrace().finishHandlersResponse();
}
try {
sendResponse(response);
} catch (Throwable e) {
LOGGER.error("Failed to send rest response, operation:{}, request uri:{}",
getMicroserviceQualifiedName(), requestEx.getRequestURI(), e);
}
}
@SuppressWarnings("deprecation")
protected void sendResponse(Response response) {
if (response.getHeaders().getHeaderMap() != null) {
for (Entry<String, List<Object>> entry : response.getHeaders().getHeaderMap().entrySet()) {
for (Object value : entry.getValue()) {
if (!entry.getKey().equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)
&& !entry.getKey().equalsIgnoreCase("Transfer-Encoding")) {
responseEx.addHeader(entry.getKey(), String.valueOf(value));
}
}
}
}
responseEx.setStatus(response.getStatusCode(), response.getReasonPhrase());
responseEx.setAttribute(RestConst.INVOCATION_HANDLER_RESPONSE, response);
responseEx.setAttribute(RestConst.INVOCATION_HANDLER_PROCESSOR, produceProcessor);
executeHttpServerFilters(response);
}
protected void executeHttpServerFilters(Response response) {
HttpServerFilterBeforeSendResponseExecutor exec =
new HttpServerFilterBeforeSendResponseExecutor(httpServerFilters, invocation, responseEx);
CompletableFuture<Void> future = exec.run();
future.whenComplete((v, e) -> {
if (invocation != null) {
invocation.getInvocationStageTrace().finishServerFiltersResponse();
}
onExecuteHttpServerFiltersFinish(response, e);
});
}
protected void onExecuteHttpServerFiltersFinish(Response response, Throwable e) {
if (e != null) {
LOGGER.error("Failed to execute HttpServerFilters, operation:{}, request uri:{}",
getMicroserviceQualifiedName(), requestEx.getRequestURI(), e);
}
try {
responseEx.flushBuffer();
} catch (Throwable flushException) {
LOGGER.error("Failed to flush rest response, operation:{}, request uri:{}",
getMicroserviceQualifiedName(), requestEx.getRequestURI(), flushException);
}
try {
requestEx.getAsyncContext().complete();
} catch (Throwable completeException) {
LOGGER.error("Failed to complete async rest response, operation:{}, request uri:{}",
getMicroserviceQualifiedName(), requestEx.getRequestURI(), completeException);
}
// if failed to locate path, then will not create invocation
// TODO: statistics this case
if (invocation != null) {
invocation.onFinish(response);
}
}
private String getMicroserviceQualifiedName() {
return null == invocation ? UNKNOWN_OPERATION_ID : invocation.getMicroserviceQualifiedName();
}
}
| 1 | 10,762 | highway have the same problem we can add a new method in invocation: mergeContext 1.if new context have more items, then addAll to new context, and replace old context 2.if new context have less items, then allAll to old context directly. | apache-servicecomb-java-chassis | java |
@@ -637,12 +637,15 @@ namespace GenFacades
private static void TraceDuplicateSeedTypeError(string docId, IReadOnlyList<INamedTypeDefinition> seedTypes)
{
- Trace.TraceError("The type '{0}' is defined in multiple seed assemblies. If this is intentional, specify one of the following arguments to choose the preferred seed type:", docId);
+ var sb = new StringBuilder();
+ sb.AppendFormat("The type '{0}' is defined in multiple seed assemblies. If this is intentional, specify one of the following arguments to choose the preferred seed type:", docId);
foreach (INamedTypeDefinition type in seedTypes)
{
- Trace.TraceError(" /preferSeedType:{0}={1}", docId.Substring("T:".Length), type.GetAssembly().Name.Value);
+ sb.AppendFormat(" /preferSeedType:{0}={1}", docId.Substring("T:".Length), type.GetAssembly().Name.Value);
}
+
+ Trace.TraceError(sb.ToString());
}
private void AddTypeForward(Assembly assembly, INamedTypeDefinition seedType) | 1 | // 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Cci;
using Microsoft.Cci.Extensions;
using Microsoft.Cci.MutableCodeModel;
using System.Globalization;
using Microsoft.DiaSymReader.Tools;
using System.Runtime.InteropServices;
namespace GenFacades
{
public class Generator
{
private const uint ReferenceAssemblyFlag = 0x70;
public static bool Execute(
string seeds,
string contracts,
string facadePath,
Version assemblyFileVersion = null,
bool clearBuildAndRevision = false,
bool ignoreMissingTypes = false,
bool ignoreBuildAndRevisionMismatch = false,
bool buildDesignTimeFacades = false,
string inclusionContracts = null,
ErrorTreatment seedLoadErrorTreatment = ErrorTreatment.Default,
ErrorTreatment contractLoadErrorTreatment = ErrorTreatment.Default,
string[] seedTypePreferencesUnsplit = null,
bool forceZeroVersionSeeds = false,
bool producePdb = true,
string partialFacadeAssemblyPath = null,
bool buildPartialReferenceFacade = false)
{
if (!Directory.Exists(facadePath))
Directory.CreateDirectory(facadePath);
var nameTable = new NameTable();
var internFactory = new InternFactory();
try
{
Dictionary<string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesUnsplit);
using (var contractHost = new HostEnvironment(nameTable, internFactory))
using (var seedHost = new HostEnvironment(nameTable, internFactory))
{
contractHost.LoadErrorTreatment = contractLoadErrorTreatment;
seedHost.LoadErrorTreatment = seedLoadErrorTreatment;
var contractAssemblies = LoadAssemblies(contractHost, contracts);
IReadOnlyDictionary<string, IEnumerable<string>> docIdTable = GenerateDocIdTable(contractAssemblies, inclusionContracts);
IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray();
IAssemblyReference seedCoreAssemblyRef = ((Microsoft.Cci.Immutable.PlatformType)seedHost.PlatformType).CoreAssemblyRef;
if (forceZeroVersionSeeds)
{
// Create a deep copier, copy the seed assemblies, and zero out their versions.
var copier = new MetadataDeepCopier(seedHost);
for (int i = 0; i < seedAssemblies.Length; i++)
{
var mutableSeed = copier.Copy(seedAssemblies[i]);
mutableSeed.Version = new Version(0, 0, 0, 0);
// Copy the modified seed assembly back.
seedAssemblies[i] = mutableSeed;
if (mutableSeed.Name.UniqueKey == seedCoreAssemblyRef.Name.UniqueKey)
{
seedCoreAssemblyRef = mutableSeed;
}
}
}
var typeTable = GenerateTypeTable(seedAssemblies);
var facadeGenerator = new FacadeGenerator(seedHost, contractHost, docIdTable, typeTable, seedTypePreferences, clearBuildAndRevision, buildDesignTimeFacades, assemblyFileVersion);
if (buildPartialReferenceFacade && ignoreMissingTypes)
{
throw new FacadeGenerationException(
"When buildPartialReferenceFacade is specified ignoreMissingTypes must not be specified.");
}
if (partialFacadeAssemblyPath != null)
{
if (contractAssemblies.Count() != 1)
{
throw new FacadeGenerationException(
"When partialFacadeAssemblyPath is specified, only exactly one corresponding contract assembly can be specified.");
}
if (buildPartialReferenceFacade)
{
throw new FacadeGenerationException(
"When partialFacadeAssemblyPath is specified, buildPartialReferenceFacade must not be specified.");
}
IAssembly contractAssembly = contractAssemblies.First();
IAssembly partialFacadeAssembly = seedHost.LoadAssembly(partialFacadeAssemblyPath);
if (contractAssembly.Name != partialFacadeAssembly.Name
|| contractAssembly.Version.Major != partialFacadeAssembly.Version.Major
|| contractAssembly.Version.Minor != partialFacadeAssembly.Version.Minor
|| (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Build != partialFacadeAssembly.Version.Build)
|| (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Revision != partialFacadeAssembly.Version.Revision)
|| contractAssembly.GetPublicKeyToken() != partialFacadeAssembly.GetPublicKeyToken())
{
throw new FacadeGenerationException(
string.Format("The partial facade assembly's name, version, and public key token must exactly match the contract to be filled. Contract: {0}, Facade: {1}",
contractAssembly.AssemblyIdentity,
partialFacadeAssembly.AssemblyIdentity));
}
Assembly filledPartialFacade = facadeGenerator.GenerateFacade(contractAssembly, seedCoreAssemblyRef, ignoreMissingTypes,
overrideContractAssembly: partialFacadeAssembly,
forceAssemblyReferenceVersionsToZero: forceZeroVersionSeeds);
if (filledPartialFacade == null)
{
Trace.TraceError("Errors were encountered while generating the facade.");
return false;
}
string pdbLocation = null;
if (producePdb)
{
string pdbFolder = Path.GetDirectoryName(partialFacadeAssemblyPath);
pdbLocation = Path.Combine(pdbFolder, contractAssembly.Name + ".pdb");
if (producePdb && !File.Exists(pdbLocation))
{
pdbLocation = null;
Trace.TraceWarning("No PDB file present for un-transformed partial facade. No PDB will be generated.");
}
}
OutputFacadeToFile(facadePath, seedHost, filledPartialFacade, contractAssembly, pdbLocation);
}
else
{
foreach (var contract in contractAssemblies)
{
Assembly facade = facadeGenerator.GenerateFacade(contract, seedCoreAssemblyRef, ignoreMissingTypes, buildPartialReferenceFacade: buildPartialReferenceFacade);
if (facade == null)
{
#if !COREFX
Debug.Assert(Environment.ExitCode != 0);
#endif
return false;
}
OutputFacadeToFile(facadePath, seedHost, facade, contract);
}
}
}
return true;
}
catch (FacadeGenerationException ex)
{
Trace.TraceError(ex.Message);
#if !COREFX
Debug.Assert(Environment.ExitCode != 0);
#endif
return false;
}
}
private static void OutputFacadeToFile(string facadePath, HostEnvironment seedHost, Assembly facade, IAssembly contract, string pdbLocation = null)
{
bool needsConversion = false;
string pdbOutputPath = Path.Combine(facadePath, contract.Name + ".pdb");
string finalPdbOutputPath = pdbOutputPath;
// Use the filename (including extension .dll/.winmd) so people can have some control over the output facade file name.
string facadeFileName = Path.GetFileName(contract.Location);
string facadeOutputPath = Path.Combine(facadePath, facadeFileName);
using (Stream peOutStream = File.Create(facadeOutputPath))
{
if (pdbLocation != null)
{
if (File.Exists(pdbLocation))
{
// Convert from portable to windows PDBs if necessary. If we convert
// set the pdbOutput path to a *.windows.pdb file so we can convert it back
// to 'finalPdbOutputPath'.
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
needsConversion = ConvertFromPortableIfNecessary(facade.Location, ref pdbLocation);
if (needsConversion)
{
// We want to keep the same file name for the PDB because it is used as a key when looking it up on a symbol server
string pdbOutputPathPdbDir = Path.Combine(Path.GetDirectoryName(pdbOutputPath), "WindowsPdb");
Directory.CreateDirectory(pdbOutputPathPdbDir);
pdbOutputPath = Path.Combine(pdbOutputPathPdbDir, Path.GetFileName(pdbOutputPath));
}
// do the main GenFacades logic (which today only works with windows PDBs).
using (Stream pdbReadStream = File.OpenRead(pdbLocation))
using (PdbReader pdbReader = new PdbReader(pdbReadStream, seedHost))
using (PdbWriter pdbWriter = new PdbWriter(pdbOutputPath, pdbReader))
{
PeWriter.WritePeToStream(facade, seedHost, peOutStream, pdbReader, pdbReader, pdbWriter);
}
}
else
{
throw new FacadeGenerationException("Couldn't find the pdb at the given location: " + pdbLocation);
}
}
else
{
PeWriter.WritePeToStream(facade, seedHost, peOutStream);
}
}
// If we started with Portable PDBs we need to convert the output to portable again.
// We have to do this after facadeOutputPath is closed for writing.
if (needsConversion)
{
Trace.TraceInformation("Converting PDB generated by GenFacades " + pdbOutputPath + " to portable format " + finalPdbOutputPath);
ConvertFromWindowsPdb(facadeOutputPath, pdbOutputPath, finalPdbOutputPath);
}
}
/// <summary>
/// Given dllInputPath determine if it is portable. If so convert it *\WindowsPdb\*.pdb and update 'pdbInputPath' to
/// point to this converted file.
/// Returns true if the conversion was done (that is the original file was protable).
/// 'dllInputPath' is the DLL that goes along with 'pdbInputPath'.
/// </summary>
private static bool ConvertFromPortableIfNecessary(string dllInputPath, ref string pdbInputPath)
{
string originalPdbInputPath = pdbInputPath;
using (Stream pdbReadStream = File.OpenRead(pdbInputPath))
{
// If the input is not portable, there is nothing to do, and we can early out.
if (!PdbConverter.IsPortable(pdbReadStream))
return false;
// We want to keep the same file name for the PDB because it is used as a key when looking it up on a symbol server
string pdbInputPathPdbDir = Path.Combine(Path.GetDirectoryName(pdbInputPath), "WindowsPdb");
Directory.CreateDirectory(pdbInputPathPdbDir);
pdbInputPath = Path.Combine(pdbInputPathPdbDir, Path.GetFileName(pdbInputPath));
Trace.TraceInformation("PDB " + originalPdbInputPath + " is a portable PDB, converting it to " + pdbInputPath);
PdbConverter converter = new PdbConverter(d => Trace.TraceError(d.ToString(CultureInfo.InvariantCulture)));
using (Stream peStream = File.OpenRead(dllInputPath))
using (Stream pdbWriteStream = File.OpenWrite(pdbInputPath))
{
converter.ConvertPortableToWindows(peStream, pdbReadStream, pdbWriteStream, PdbConversionOptions.SuppressSourceLinkConversion);
}
}
return true;
}
/// <summary>
/// Convert the windows PDB winPdbInputPath to portablePdbOutputPath.
/// 'dllInputPath' is the DLL that goes along with 'winPdbInputPath'.
/// </summary>
private static void ConvertFromWindowsPdb(string dllInputPath, string winPdbInputPath, string portablePdbOutputPath)
{
PdbConverter converter = new PdbConverter(d => Trace.TraceError(d.ToString(CultureInfo.InvariantCulture)));
using (Stream peStream = File.OpenRead(dllInputPath))
using (Stream pdbReadStream = File.OpenRead(winPdbInputPath))
using (Stream pdbWriteStream = File.OpenWrite(portablePdbOutputPath))
{
converter.ConvertWindowsToPortable(peStream, pdbReadStream, pdbWriteStream);
}
}
private static Dictionary<string, string> ParseSeedTypePreferences(string[] preferences)
{
var dictionary = new Dictionary<string, string>(StringComparer.Ordinal);
if (preferences != null)
{
foreach (string preference in preferences)
{
int i = preference.IndexOf('=');
if (i < 0)
{
throw new FacadeGenerationException("Invalid seed type preference. Correct usage is /preferSeedType:FullTypeName=AssemblyName");
}
string key = preference.Substring(0, i);
string value = preference.Substring(i + 1);
if (!key.StartsWith("T:", StringComparison.Ordinal))
{
key = "T:" + key;
}
string existingValue;
if (dictionary.TryGetValue(key, out existingValue))
{
Trace.TraceWarning("Overriding /preferSeedType:{0}={1} with /preferSeedType:{2}={3}.", key, existingValue, key, value);
}
dictionary[key] = value;
}
}
return dictionary;
}
private static IEnumerable<IAssembly> LoadAssemblies(HostEnvironment host, string assemblyPaths)
{
host.UnifyToLibPath = true;
string[] splitPaths = HostEnvironment.SplitPaths(assemblyPaths);
foreach (string path in splitPaths)
{
if (Directory.Exists(path))
{
host.AddLibPath(Path.GetFullPath(path));
}
else if (File.Exists(path))
{
host.AddLibPath(Path.GetDirectoryName(Path.GetFullPath(path)));
}
}
return host.LoadAssemblies(splitPaths);
}
private static IReadOnlyDictionary<string, IEnumerable<string>> GenerateDocIdTable(IEnumerable<IAssembly> contractAssemblies, string inclusionContracts)
{
Dictionary<string, HashSet<string>> mutableDocIdTable = new Dictionary<string, HashSet<string>>();
foreach (IAssembly contractAssembly in contractAssemblies)
{
string simpleName = contractAssembly.AssemblyIdentity.Name.Value;
if (mutableDocIdTable.ContainsKey(simpleName))
throw new FacadeGenerationException(string.Format("Multiple contracts named \"{0}\" specified on -contracts.", simpleName));
mutableDocIdTable[simpleName] = new HashSet<string>(EnumerateDocIdsToForward(contractAssembly));
}
if (inclusionContracts != null)
{
foreach (string inclusionContractPath in HostEnvironment.SplitPaths(inclusionContracts))
{
// Assembly identity conflicts are permitted and normal in the inclusion contract list so load each one in a throwaway host to avoid problems.
using (HostEnvironment inclusionHost = new HostEnvironment(new NameTable(), new InternFactory()))
{
IAssembly inclusionAssembly = inclusionHost.LoadAssemblyFrom(inclusionContractPath);
if (inclusionAssembly == null || inclusionAssembly is Dummy)
throw new FacadeGenerationException(string.Format("Could not load assembly \"{0}\".", inclusionContractPath));
string simpleName = inclusionAssembly.Name.Value;
HashSet<string> hashset;
if (!mutableDocIdTable.TryGetValue(simpleName, out hashset))
{
Trace.TraceWarning("An assembly named \"{0}\" was specified in the -include list but no contract was specified named \"{0}\". Ignoring.", simpleName);
}
else
{
foreach (string docId in EnumerateDocIdsToForward(inclusionAssembly))
{
hashset.Add(docId);
}
}
}
}
}
Dictionary<string, IEnumerable<string>> docIdTable = new Dictionary<string, IEnumerable<string>>();
foreach (KeyValuePair<string, HashSet<string>> kv in mutableDocIdTable)
{
string key = kv.Key;
IEnumerable<string> sortedDocIds = kv.Value.OrderBy(s => s, StringComparer.OrdinalIgnoreCase);
docIdTable.Add(key, sortedDocIds);
}
return docIdTable;
}
private static IEnumerable<string> EnumerateDocIdsToForward(IAssembly contractAssembly)
{
// Use INamedTypeReference instead of INamespaceTypeReference in order to also include nested
// class type-forwards.
var typeForwardsToForward = contractAssembly.ExportedTypes.Select(alias => alias.AliasedType)
.OfType<INamedTypeReference>();
var typesToForward = contractAssembly.GetAllTypes().Where(t => TypeHelper.IsVisibleOutsideAssembly(t))
.OfType<INamespaceTypeDefinition>();
List<string> result = typeForwardsToForward.Concat(typesToForward)
.Select(type => TypeHelper.GetTypeName(type, NameFormattingOptions.DocumentationId)).ToList();
foreach(var type in typesToForward)
{
AddNestedTypeDocIds(result, type);
}
return result;
}
private static void AddNestedTypeDocIds(List<string> docIds, INamedTypeDefinition type)
{
foreach (var nestedType in type.NestedTypes)
{
if (TypeHelper.IsVisibleOutsideAssembly(nestedType))
docIds.Add(TypeHelper.GetTypeName(nestedType, NameFormattingOptions.DocumentationId));
AddNestedTypeDocIds(docIds, nestedType);
}
}
private static IReadOnlyDictionary<string, IReadOnlyList<INamedTypeDefinition>> GenerateTypeTable(IEnumerable<IAssembly> seedAssemblies)
{
var typeTable = new Dictionary<string, IReadOnlyList<INamedTypeDefinition>>();
foreach (var assembly in seedAssemblies)
{
foreach (var type in assembly.GetAllTypes().OfType<INamedTypeDefinition>())
{
if (!TypeHelper.IsVisibleOutsideAssembly(type))
continue;
AddTypeAndNestedTypesToTable(typeTable, type);
}
}
return typeTable;
}
private static void AddTypeAndNestedTypesToTable(Dictionary<string, IReadOnlyList<INamedTypeDefinition>> typeTable, INamedTypeDefinition type)
{
if (type != null)
{
IReadOnlyList<INamedTypeDefinition> seedTypes;
string docId = TypeHelper.GetTypeName(type, NameFormattingOptions.DocumentationId);
if (!typeTable.TryGetValue(docId, out seedTypes))
{
seedTypes = new List<INamedTypeDefinition>(1);
typeTable.Add(docId, seedTypes);
}
if (!seedTypes.Contains(type))
((List<INamedTypeDefinition>)seedTypes).Add(type);
foreach (INestedTypeDefinition nestedType in type.NestedTypes)
{
if (TypeHelper.IsVisibleOutsideAssembly(nestedType))
AddTypeAndNestedTypesToTable(typeTable, nestedType);
}
}
}
private class FacadeGenerator
{
private readonly IMetadataHost _seedHost;
private readonly IMetadataHost _contractHost;
private readonly IReadOnlyDictionary<string, IEnumerable<string>> _docIdTable;
private readonly IReadOnlyDictionary<string, IReadOnlyList<INamedTypeDefinition>> _typeTable;
private readonly IReadOnlyDictionary<string, string> _seedTypePreferences;
private readonly bool _clearBuildAndRevision;
private readonly bool _buildDesignTimeFacades;
private readonly Version _assemblyFileVersion;
public FacadeGenerator(
IMetadataHost seedHost,
IMetadataHost contractHost,
IReadOnlyDictionary<string, IEnumerable<string>> docIdTable,
IReadOnlyDictionary<string, IReadOnlyList<INamedTypeDefinition>> typeTable,
IReadOnlyDictionary<string, string> seedTypePreferences,
bool clearBuildAndRevision,
bool buildDesignTimeFacades,
Version assemblyFileVersion
)
{
_seedHost = seedHost;
_contractHost = contractHost;
_docIdTable = docIdTable;
_typeTable = typeTable;
_seedTypePreferences = seedTypePreferences;
_clearBuildAndRevision = clearBuildAndRevision;
_buildDesignTimeFacades = buildDesignTimeFacades;
_assemblyFileVersion = assemblyFileVersion;
}
public Assembly GenerateFacade(IAssembly contractAssembly,
IAssemblyReference seedCoreAssemblyReference,
bool ignoreMissingTypes, IAssembly overrideContractAssembly = null,
bool buildPartialReferenceFacade = false,
bool forceAssemblyReferenceVersionsToZero = false)
{
Assembly assembly;
if (overrideContractAssembly != null)
{
MetadataDeepCopier copier = new MetadataDeepCopier(_seedHost);
assembly = copier.Copy(overrideContractAssembly); // Use non-empty partial facade if present
}
else
{
MetadataDeepCopier copier = new MetadataDeepCopier(_contractHost);
assembly = copier.Copy(contractAssembly);
// if building a reference facade don't strip the contract
if (!buildPartialReferenceFacade)
{
ReferenceAssemblyToFacadeRewriter rewriter = new ReferenceAssemblyToFacadeRewriter(_seedHost, _contractHost, seedCoreAssemblyReference, _assemblyFileVersion != null);
rewriter.Rewrite(assembly);
}
}
if (forceAssemblyReferenceVersionsToZero)
{
foreach (AssemblyReference ar in assembly.AssemblyReferences)
{
ar.Version = new Version(0, 0, 0, 0);
}
}
string contractAssemblyName = contractAssembly.AssemblyIdentity.Name.Value;
IEnumerable<string> docIds = _docIdTable[contractAssemblyName];
// Add all the type forwards
bool error = false;
Dictionary<string, INamedTypeDefinition> existingDocIds = assembly.AllTypes.ToDictionary(typeDef => typeDef.RefDocId(), typeDef => typeDef);
IEnumerable<string> docIdsToForward = buildPartialReferenceFacade ? existingDocIds.Keys : docIds.Where(id => !existingDocIds.ContainsKey(id));
Dictionary<string, INamedTypeReference> forwardedTypes = new Dictionary<string, INamedTypeReference>();
foreach (string docId in docIdsToForward)
{
IReadOnlyList<INamedTypeDefinition> seedTypes;
if (!_typeTable.TryGetValue(docId, out seedTypes))
{
if (!ignoreMissingTypes && !buildPartialReferenceFacade)
{
Trace.TraceError("Did not find type '{0}' in any of the seed assemblies.", docId);
error = true;
}
continue;
}
INamedTypeDefinition seedType = GetSeedType(docId, seedTypes);
if (seedType == null)
{
TraceDuplicateSeedTypeError(docId, seedTypes);
error = true;
continue;
}
if (buildPartialReferenceFacade)
{
// honor preferSeedType for keeping contract type
string preferredSeedAssembly;
bool keepType = _seedTypePreferences.TryGetValue(docId, out preferredSeedAssembly) &&
contractAssemblyName.Equals(preferredSeedAssembly, StringComparison.OrdinalIgnoreCase);
if (keepType)
{
continue;
}
assembly.AllTypes.Remove(existingDocIds[docId]);
forwardedTypes.Add(docId, seedType);
}
AddTypeForward(assembly, seedType);
}
if (buildPartialReferenceFacade)
{
if (forwardedTypes.Count == 0)
{
Trace.TraceError("Did not find any types in any of the seed assemblies.");
return null;
}
else
{
// for any thing that's now a typeforward, make sure typerefs point to that rather than
// the type previously inside the assembly.
TypeReferenceRewriter typeRefRewriter = new TypeReferenceRewriter(_seedHost, oldType =>
{
INamedTypeReference newType = null;
return forwardedTypes.TryGetValue(oldType.DocId(), out newType) ? newType : oldType;
});
var remainingTypes = assembly.AllTypes.Where(t => t.Name.Value != "<Module>");
if (!remainingTypes.Any())
{
Trace.TraceInformation($"Removed all types from {contractAssembly.Name} thus will remove ReferenceAssemblyAttribute.");
assembly.AssemblyAttributes.RemoveAll(ca => ca.FullName() == "System.Runtime.CompilerServices.ReferenceAssemblyAttribute");
assembly.Flags &= ~ReferenceAssemblyFlag;
}
typeRefRewriter.Rewrite(assembly);
}
}
if (error)
{
return null;
}
if (_assemblyFileVersion != null)
{
assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyFileVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyInformationalVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
}
if (_buildDesignTimeFacades)
{
assembly.AssemblyAttributes.Add(CreateAttribute("System.Runtime.CompilerServices.ReferenceAssemblyAttribute", seedCoreAssemblyReference.ResolvedAssembly));
assembly.Flags |= ReferenceAssemblyFlag;
}
if (_clearBuildAndRevision)
{
assembly.Version = new Version(assembly.Version.Major, assembly.Version.Minor, 0, 0);
}
AddWin32VersionResource(contractAssembly.Location, assembly);
return assembly;
}
private INamedTypeDefinition GetSeedType(string docId, IReadOnlyList<INamedTypeDefinition> seedTypes)
{
Debug.Assert(seedTypes.Count != 0); // we should already have checked for non-existent types.
if (seedTypes.Count == 1)
{
return seedTypes[0];
}
string preferredSeedAssembly;
if (_seedTypePreferences.TryGetValue(docId, out preferredSeedAssembly))
{
return seedTypes.SingleOrDefault(t => String.Equals(t.GetAssembly().Name.Value, preferredSeedAssembly, StringComparison.OrdinalIgnoreCase));
}
return null;
}
private static void TraceDuplicateSeedTypeError(string docId, IReadOnlyList<INamedTypeDefinition> seedTypes)
{
Trace.TraceError("The type '{0}' is defined in multiple seed assemblies. If this is intentional, specify one of the following arguments to choose the preferred seed type:", docId);
foreach (INamedTypeDefinition type in seedTypes)
{
Trace.TraceError(" /preferSeedType:{0}={1}", docId.Substring("T:".Length), type.GetAssembly().Name.Value);
}
}
private void AddTypeForward(Assembly assembly, INamedTypeDefinition seedType)
{
var alias = new NamespaceAliasForType();
alias.AliasedType = ConvertDefinitionToReferenceIfTypeIsNested(seedType, _seedHost);
alias.IsPublic = true;
if (assembly.ExportedTypes == null)
assembly.ExportedTypes = new List<IAliasForType>();
// Make sure that the typeforward doesn't already exist in the ExportedTypes
if (!assembly.ExportedTypes.Any(t => t.AliasedType.RefDocId() == alias.AliasedType.RefDocId()))
assembly.ExportedTypes.Add(alias);
else
throw new FacadeGenerationException($"{seedType.FullName()} typeforward already exists");
}
private void AddWin32VersionResource(string contractLocation, Assembly facade)
{
var versionInfo = FileVersionInfo.GetVersionInfo(contractLocation);
var versionSerializer = new VersionResourceSerializer(
true,
versionInfo.Comments,
versionInfo.CompanyName,
versionInfo.FileDescription,
_assemblyFileVersion == null ? versionInfo.FileVersion : _assemblyFileVersion.ToString(),
versionInfo.InternalName,
versionInfo.LegalCopyright,
versionInfo.LegalTrademarks,
versionInfo.OriginalFilename,
versionInfo.ProductName,
_assemblyFileVersion == null ? versionInfo.ProductVersion : _assemblyFileVersion.ToString(),
facade.Version);
using (var stream = new MemoryStream())
using (var writer = new BinaryWriter(stream, Encoding.Unicode, true))
{
versionSerializer.WriteVerResource(writer);
var resource = new Win32Resource();
resource.Id = 1;
resource.TypeId = 0x10;
resource.Data = stream.ToArray().ToList();
facade.Win32Resources.Add(resource);
}
}
// This shouldn't be necessary, but CCI is putting a nonzero TypeDefId in the ExportedTypes table
// for nested types if NamespaceAliasForType.AliasedType is set to an ITypeDefinition
// so we make an ITypeReference copy as a workaround.
private static INamedTypeReference ConvertDefinitionToReferenceIfTypeIsNested(INamedTypeDefinition typeDef, IMetadataHost host)
{
var nestedTypeDef = typeDef as INestedTypeDefinition;
if (nestedTypeDef == null)
return typeDef;
var typeRef = new NestedTypeReference();
typeRef.Copy(nestedTypeDef, host.InternFactory);
return typeRef;
}
private ICustomAttribute CreateAttribute(string typeName, IAssembly seedCoreAssembly, string argument = null)
{
var type = seedCoreAssembly.GetAllTypes().FirstOrDefault(t => t.FullName() == typeName);
if (type == null)
{
throw new FacadeGenerationException(String.Format("Cannot find {0} type in seed core assembly.", typeName));
}
IEnumerable<IMethodDefinition> constructors = type.GetMembersNamed(_seedHost.NameTable.Ctor, false).OfType<IMethodDefinition>();
IMethodDefinition constructor = null;
if (argument != null)
{
constructor = constructors.SingleOrDefault(m => m.ParameterCount == 1 && m.Parameters.First().Type.AreEquivalent("System.String"));
}
else
{
constructor = constructors.SingleOrDefault(m => m.ParameterCount == 0);
}
if (constructor == null)
{
throw new FacadeGenerationException(String.Format("Cannot find {0} constructor taking single string argument in seed core assembly.", typeName));
}
var attribute = new CustomAttribute();
attribute.Constructor = constructor;
if (argument != null)
{
var argumentExpression = new MetadataConstant();
argumentExpression.Type = _seedHost.PlatformType.SystemString;
argumentExpression.Value = argument;
attribute.Arguments = new List<IMetadataExpression>(1);
attribute.Arguments.Add(argumentExpression);
}
return attribute;
}
}
private class ReferenceAssemblyToFacadeRewriter : MetadataRewriter
{
private IMetadataHost _seedHost;
private IMetadataHost _contractHost;
private IAssemblyReference _seedCoreAssemblyReference;
private bool _stripFileVersionAttributes;
public ReferenceAssemblyToFacadeRewriter(
IMetadataHost seedHost,
IMetadataHost contractHost,
IAssemblyReference seedCoreAssemblyReference,
bool stripFileVersionAttributes)
: base(seedHost)
{
_seedHost = seedHost;
_contractHost = contractHost;
_stripFileVersionAttributes = stripFileVersionAttributes;
_seedCoreAssemblyReference = seedCoreAssemblyReference;
}
public override IAssemblyReference Rewrite(IAssemblyReference assemblyReference)
{
if (assemblyReference == null)
return assemblyReference;
if (assemblyReference.UnifiedAssemblyIdentity.Equals(_contractHost.CoreAssemblySymbolicIdentity) &&
!assemblyReference.ModuleIdentity.Equals(host.CoreAssemblySymbolicIdentity))
{
assemblyReference = _seedCoreAssemblyReference;
}
return base.Rewrite(assemblyReference);
}
public override void RewriteChildren(RootUnitNamespace rootUnitNamespace)
{
var assemblyReference = rootUnitNamespace.Unit as IAssemblyReference;
if (assemblyReference != null)
rootUnitNamespace.Unit = Rewrite(assemblyReference).ResolvedUnit;
base.RewriteChildren(rootUnitNamespace);
}
public override List<INamespaceMember> Rewrite(List<INamespaceMember> namespaceMembers)
{
// Ignore traversing or rewriting any namspace members.
return base.Rewrite(new List<INamespaceMember>());
}
public override void RewriteChildren(Assembly assembly)
{
// Clear all win32 resources. The version resource will get repopulated.
assembly.Win32Resources = new List<IWin32Resource>();
// Remove all the references they will get repopulated while outputing.
assembly.AssemblyReferences.Clear();
// Remove all the module references (aka native references)
assembly.ModuleReferences = new List<IModuleReference>();
// Remove all file references (ex: *.nlp files in mscorlib)
assembly.Files = new List<IFileReference>();
// Remove all security attributes (ex: permissionset in IL)
assembly.SecurityAttributes = new List<ISecurityAttribute>();
// Reset the core assembly symbolic identity to the seed core assembly (e.g. mscorlib, corefx)
// and not the contract core (e.g. System.Runtime).
assembly.CoreAssemblySymbolicIdentity = _seedCoreAssemblyReference.AssemblyIdentity;
// Add reference to seed core assembly up-front so that we keep the same order as the C# compiler.
assembly.AssemblyReferences.Add(_seedCoreAssemblyReference);
// Remove all type definitions except for the "<Module>" type. Remove all fields and methods from it.
NamespaceTypeDefinition moduleType = assembly.AllTypes.SingleOrDefault(t => t.Name.Value == "<Module>") as NamespaceTypeDefinition;
assembly.AllTypes.Clear();
if (moduleType != null)
{
moduleType.Fields?.Clear();
moduleType.Methods?.Clear();
assembly.AllTypes.Add(moduleType);
}
// Remove any preexisting typeforwards.
assembly.ExportedTypes = new List<IAliasForType>();
// Remove any preexisting resources.
assembly.Resources = new List<IResourceReference>();
// Clear the reference assembly flag from the contract.
// For design-time facades, it will be added back later.
assembly.Flags &= ~ReferenceAssemblyFlag;
// This flag should not be set until the delay-signed assembly we emit is actually signed.
assembly.StrongNameSigned = false;
base.RewriteChildren(assembly);
}
public override List<ICustomAttribute> Rewrite(List<ICustomAttribute> customAttributes)
{
if (customAttributes == null)
return customAttributes;
List<ICustomAttribute> newCustomAttributes = new List<ICustomAttribute>();
// Remove all of them except for the ones that begin with Assembly
// Also remove AssemblyFileVersion and AssemblyInformationVersion if stripFileVersionAttributes is set
foreach (ICustomAttribute attribute in customAttributes)
{
ITypeReference attributeType = attribute.Type;
if (attributeType is Dummy)
continue;
string typeName = TypeHelper.GetTypeName(attributeType, NameFormattingOptions.OmitContainingNamespace | NameFormattingOptions.OmitContainingType);
if (!typeName.StartsWith("Assembly"))
continue;
// We need to remove the signature key attribute otherwise we will not be able to re-sign these binaries.
if (typeName == "AssemblySignatureKeyAttribute")
continue;
if (_stripFileVersionAttributes && ((typeName == "AssemblyFileVersionAttribute" || typeName == "AssemblyInformationalVersionAttribute")))
continue;
newCustomAttributes.Add(attribute);
}
return base.Rewrite(newCustomAttributes);
}
}
}
}
| 1 | 14,852 | Created a single error so it's not interleaved in log | dotnet-buildtools | .cs |
@@ -94,11 +94,9 @@ describe('exportFile', () => {
const result = plugin._createBlob(formatter);
- if (!Handsontable.helper.isIE9()) {
- expect(formatter.export).toHaveBeenCalled();
- expect(result.size).toBe(7);
- expect(result.type).toBe('foo;charset=iso-8859-1');
- }
+ expect(formatter.export).toHaveBeenCalled();
+ expect(result.size).toBe(7);
+ expect(result.type).toBe('foo;charset=iso-8859-1');
});
});
}); | 1 | describe('exportFile', () => {
const id = 'testContainer';
beforeEach(function() {
this.$container = $(`<div id="${id}"></div>`).appendTo('body');
});
afterEach(function() {
if (this.$container) {
destroy();
this.$container.remove();
}
});
describe('export options', () => {
it('should have prepared default general options', () => {
handsontable();
const csv = getPlugin('exportFile')._createTypeFormatter('csv');
expect(csv.options.filename).toMatch(/Handsontable \d+-\d+-\d+/);
expect(csv.options.bom).toBe(true);
expect(csv.options.encoding).toBe('utf-8');
expect(csv.options.columnHeaders).toBe(false);
expect(csv.options.rowHeaders).toBe(false);
expect(csv.options.exportHiddenColumns).toBe(false);
expect(csv.options.exportHiddenRows).toBe(false);
expect(csv.options.range).toEqual([]);
});
});
describe('`exportAsString` method', () => {
it('should create formatter class and call `export` method on it', () => {
handsontable();
const plugin = getPlugin('exportFile');
const formatter = jasmine.createSpyObj('formatter', ['export']);
formatter.export.and.returnValue('foo;bar');
spyOn(plugin, '_createTypeFormatter').and.returnValue(formatter);
const result = plugin.exportAsString('csv', { columnHeaders: true });
expect(plugin._createTypeFormatter).toHaveBeenCalledWith('csv', { columnHeaders: true });
expect(formatter.export).toHaveBeenCalled();
expect(result).toBe('foo;bar');
});
});
describe('`exportAsBlob` method', () => {
it('should create formatter class and create blob object contains exported value', () => {
handsontable();
const plugin = getPlugin('exportFile');
const formatter = jasmine.createSpy('formatter');
spyOn(plugin, '_createTypeFormatter').and.returnValue(formatter);
spyOn(plugin, '_createBlob').and.returnValue('blob');
const result = plugin.exportAsBlob('csv', { columnHeaders: true });
expect(plugin._createTypeFormatter).toHaveBeenCalledWith('csv', { columnHeaders: true });
expect(plugin._createBlob).toHaveBeenCalledWith(formatter);
expect(result).toBe('blob');
});
});
describe('`_createTypeFormatter` method', () => {
it('should create formatter type object', () => {
const hot = handsontable();
const plugin = hot.getPlugin('exportFile');
const result = plugin._createTypeFormatter('csv');
expect(result).toBeDefined();
expect(result.options.fileExtension).toBeDefined('csv');
});
it('should throw exception when specified formatter type is not exist', () => {
handsontable();
const plugin = getPlugin('exportFile');
expect(() => {
plugin._createTypeFormatter('csv2');
}).toThrow();
});
});
describe('`_createBlob` method', () => {
it('should create blob object contains exported value', () => {
handsontable();
const plugin = getPlugin('exportFile');
const formatter = jasmine.createSpyObj('formatter', ['export']);
formatter.export.and.returnValue('foo;bar');
formatter.options = { mimeType: 'foo', encoding: 'iso-8859-1' };
const result = plugin._createBlob(formatter);
if (!Handsontable.helper.isIE9()) {
expect(formatter.export).toHaveBeenCalled();
expect(result.size).toBe(7);
expect(result.type).toBe('foo;charset=iso-8859-1');
}
});
});
});
| 1 | 16,394 | `isIE9` was reverted. Shouldn't this condition be reverted as well? | handsontable-handsontable | js |
@@ -504,14 +504,14 @@ int LuaScriptInterface::luaErrorHandler(lua_State* L)
return 1;
}
-bool LuaScriptInterface::callFunction(int params)
+bool LuaScriptInterface::callFunction(int params, bool defaultReturn /* = false */)
{
bool result = false;
int size = lua_gettop(luaState);
if (protectedCall(luaState, params, 1) != 0) {
LuaScriptInterface::reportError(nullptr, LuaScriptInterface::getString(luaState, -1));
} else {
- result = LuaScriptInterface::getBoolean(luaState, -1);
+ result = LuaScriptInterface::getBoolean(luaState, -1, defaultReturn);
}
lua_pop(luaState, 1); | 1 | /**
* The Forgotten Server - a free and open-source MMORPG server emulator
* Copyright (C) 2017 Mark Samman <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "otpch.h"
#include <boost/range/adaptor/reversed.hpp>
#include "luascript.h"
#include "chat.h"
#include "player.h"
#include "game.h"
#include "protocolstatus.h"
#include "spells.h"
#include "iologindata.h"
#include "configmanager.h"
#include "teleport.h"
#include "databasemanager.h"
#include "bed.h"
#include "monster.h"
#include "scheduler.h"
#include "databasetasks.h"
extern Chat* g_chat;
extern Game g_game;
extern Monsters g_monsters;
extern ConfigManager g_config;
extern Vocations g_vocations;
extern Spells* g_spells;
ScriptEnvironment::DBResultMap ScriptEnvironment::tempResults;
uint32_t ScriptEnvironment::lastResultId = 0;
std::multimap<ScriptEnvironment*, Item*> ScriptEnvironment::tempItems;
LuaEnvironment g_luaEnvironment;
ScriptEnvironment::ScriptEnvironment()
{
resetEnv();
}
ScriptEnvironment::~ScriptEnvironment()
{
resetEnv();
}
void ScriptEnvironment::resetEnv()
{
scriptId = 0;
callbackId = 0;
timerEvent = false;
interface = nullptr;
localMap.clear();
tempResults.clear();
auto pair = tempItems.equal_range(this);
auto it = pair.first;
while (it != pair.second) {
Item* item = it->second;
if (item->getParent() == VirtualCylinder::virtualCylinder) {
g_game.ReleaseItem(item);
}
it = tempItems.erase(it);
}
}
bool ScriptEnvironment::setCallbackId(int32_t callbackId, LuaScriptInterface* scriptInterface)
{
if (this->callbackId != 0) {
//nested callbacks are not allowed
if (interface) {
interface->reportErrorFunc("Nested callbacks!");
}
return false;
}
this->callbackId = callbackId;
interface = scriptInterface;
return true;
}
void ScriptEnvironment::getEventInfo(int32_t& scriptId, LuaScriptInterface*& scriptInterface, int32_t& callbackId, bool& timerEvent) const
{
scriptId = this->scriptId;
scriptInterface = interface;
callbackId = this->callbackId;
timerEvent = this->timerEvent;
}
uint32_t ScriptEnvironment::addThing(Thing* thing)
{
if (!thing || thing->isRemoved()) {
return 0;
}
Creature* creature = thing->getCreature();
if (creature) {
return creature->getID();
}
Item* item = thing->getItem();
if (item && item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) {
return item->getUniqueId();
}
for (const auto& it : localMap) {
if (it.second == item) {
return it.first;
}
}
localMap[++lastUID] = item;
return lastUID;
}
void ScriptEnvironment::insertItem(uint32_t uid, Item* item)
{
auto result = localMap.emplace(uid, item);
if (!result.second) {
std::cout << std::endl << "Lua Script Error: Thing uid already taken.";
}
}
Thing* ScriptEnvironment::getThingByUID(uint32_t uid)
{
if (uid >= 0x10000000) {
return g_game.getCreatureByID(uid);
}
if (uid <= std::numeric_limits<uint16_t>::max()) {
Item* item = g_game.getUniqueItem(uid);
if (item && !item->isRemoved()) {
return item;
}
return nullptr;
}
auto it = localMap.find(uid);
if (it != localMap.end()) {
Item* item = it->second;
if (!item->isRemoved()) {
return item;
}
}
return nullptr;
}
Item* ScriptEnvironment::getItemByUID(uint32_t uid)
{
Thing* thing = getThingByUID(uid);
if (!thing) {
return nullptr;
}
return thing->getItem();
}
Container* ScriptEnvironment::getContainerByUID(uint32_t uid)
{
Item* item = getItemByUID(uid);
if (!item) {
return nullptr;
}
return item->getContainer();
}
void ScriptEnvironment::removeItemByUID(uint32_t uid)
{
if (uid <= std::numeric_limits<uint16_t>::max()) {
g_game.removeUniqueItem(uid);
return;
}
auto it = localMap.find(uid);
if (it != localMap.end()) {
localMap.erase(it);
}
}
void ScriptEnvironment::addTempItem(Item* item)
{
tempItems.emplace(this, item);
}
void ScriptEnvironment::removeTempItem(Item* item)
{
for (auto it = tempItems.begin(), end = tempItems.end(); it != end; ++it) {
if (it->second == item) {
tempItems.erase(it);
break;
}
}
}
uint32_t ScriptEnvironment::addResult(DBResult_ptr res)
{
tempResults[++lastResultId] = res;
return lastResultId;
}
bool ScriptEnvironment::removeResult(uint32_t id)
{
auto it = tempResults.find(id);
if (it == tempResults.end()) {
return false;
}
tempResults.erase(it);
return true;
}
DBResult_ptr ScriptEnvironment::getResultByID(uint32_t id)
{
auto it = tempResults.find(id);
if (it == tempResults.end()) {
return nullptr;
}
return it->second;
}
std::string LuaScriptInterface::getErrorDesc(ErrorCode_t code)
{
switch (code) {
case LUA_ERROR_PLAYER_NOT_FOUND: return "Player not found";
case LUA_ERROR_CREATURE_NOT_FOUND: return "Creature not found";
case LUA_ERROR_ITEM_NOT_FOUND: return "Item not found";
case LUA_ERROR_THING_NOT_FOUND: return "Thing not found";
case LUA_ERROR_TILE_NOT_FOUND: return "Tile not found";
case LUA_ERROR_HOUSE_NOT_FOUND: return "House not found";
case LUA_ERROR_COMBAT_NOT_FOUND: return "Combat not found";
case LUA_ERROR_CONDITION_NOT_FOUND: return "Condition not found";
case LUA_ERROR_AREA_NOT_FOUND: return "Area not found";
case LUA_ERROR_CONTAINER_NOT_FOUND: return "Container not found";
case LUA_ERROR_VARIANT_NOT_FOUND: return "Variant not found";
case LUA_ERROR_VARIANT_UNKNOWN: return "Unknown variant type";
case LUA_ERROR_SPELL_NOT_FOUND: return "Spell not found";
default: return "Bad error code";
}
}
ScriptEnvironment LuaScriptInterface::scriptEnv[16];
int32_t LuaScriptInterface::scriptEnvIndex = -1;
LuaScriptInterface::LuaScriptInterface(std::string interfaceName) : interfaceName(std::move(interfaceName))
{
if (!g_luaEnvironment.getLuaState()) {
g_luaEnvironment.initState();
}
}
LuaScriptInterface::~LuaScriptInterface()
{
closeState();
}
bool LuaScriptInterface::reInitState()
{
g_luaEnvironment.clearCombatObjects(this);
g_luaEnvironment.clearAreaObjects(this);
closeState();
return initState();
}
/// Same as lua_pcall, but adds stack trace to error strings in called function.
int LuaScriptInterface::protectedCall(lua_State* L, int nargs, int nresults)
{
int error_index = lua_gettop(L) - nargs;
lua_pushcfunction(L, luaErrorHandler);
lua_insert(L, error_index);
int ret = lua_pcall(L, nargs, nresults, error_index);
lua_remove(L, error_index);
return ret;
}
int32_t LuaScriptInterface::loadFile(const std::string& file, Npc* npc /* = nullptr*/)
{
//loads file as a chunk at stack top
int ret = luaL_loadfile(luaState, file.c_str());
if (ret != 0) {
lastLuaError = popString(luaState);
return -1;
}
//check that it is loaded as a function
if (!isFunction(luaState, -1)) {
return -1;
}
loadingFile = file;
if (!reserveScriptEnv()) {
return -1;
}
ScriptEnvironment* env = getScriptEnv();
env->setScriptId(EVENT_ID_LOADING, this);
env->setNpc(npc);
//execute it
ret = protectedCall(luaState, 0, 0);
if (ret != 0) {
reportError(nullptr, popString(luaState));
resetScriptEnv();
return -1;
}
resetScriptEnv();
return 0;
}
int32_t LuaScriptInterface::getEvent(const std::string& eventName)
{
//get our events table
lua_rawgeti(luaState, LUA_REGISTRYINDEX, eventTableRef);
if (!isTable(luaState, -1)) {
lua_pop(luaState, 1);
return -1;
}
//get current event function pointer
lua_getglobal(luaState, eventName.c_str());
if (!isFunction(luaState, -1)) {
lua_pop(luaState, 2);
return -1;
}
//save in our events table
lua_pushvalue(luaState, -1);
lua_rawseti(luaState, -3, runningEventId);
lua_pop(luaState, 2);
//reset global value of this event
lua_pushnil(luaState);
lua_setglobal(luaState, eventName.c_str());
cacheFiles[runningEventId] = loadingFile + ":" + eventName;
return runningEventId++;
}
int32_t LuaScriptInterface::getMetaEvent(const std::string& globalName, const std::string& eventName)
{
//get our events table
lua_rawgeti(luaState, LUA_REGISTRYINDEX, eventTableRef);
if (!isTable(luaState, -1)) {
lua_pop(luaState, 1);
return -1;
}
//get current event function pointer
lua_getglobal(luaState, globalName.c_str());
lua_getfield(luaState, -1, eventName.c_str());
if (!isFunction(luaState, -1)) {
lua_pop(luaState, 3);
return -1;
}
//save in our events table
lua_pushvalue(luaState, -1);
lua_rawseti(luaState, -4, runningEventId);
lua_pop(luaState, 1);
//reset global value of this event
lua_pushnil(luaState);
lua_setfield(luaState, -2, eventName.c_str());
lua_pop(luaState, 2);
cacheFiles[runningEventId] = loadingFile + ":" + globalName + "@" + eventName;
return runningEventId++;
}
const std::string& LuaScriptInterface::getFileById(int32_t scriptId)
{
if (scriptId == EVENT_ID_LOADING) {
return loadingFile;
}
auto it = cacheFiles.find(scriptId);
if (it == cacheFiles.end()) {
static const std::string& unk = "(Unknown scriptfile)";
return unk;
}
return it->second;
}
std::string LuaScriptInterface::getStackTrace(const std::string& error_desc)
{
lua_getglobal(luaState, "debug");
if (!isTable(luaState, -1)) {
lua_pop(luaState, 1);
return error_desc;
}
lua_getfield(luaState, -1, "traceback");
if (!isFunction(luaState, -1)) {
lua_pop(luaState, 2);
return error_desc;
}
lua_replace(luaState, -2);
pushString(luaState, error_desc);
lua_call(luaState, 1, 1);
return popString(luaState);
}
void LuaScriptInterface::reportError(const char* function, const std::string& error_desc, bool stack_trace/* = false*/)
{
int32_t scriptId;
int32_t callbackId;
bool timerEvent;
LuaScriptInterface* scriptInterface;
getScriptEnv()->getEventInfo(scriptId, scriptInterface, callbackId, timerEvent);
std::cout << std::endl << "Lua Script Error: ";
if (scriptInterface) {
std::cout << '[' << scriptInterface->getInterfaceName() << "] " << std::endl;
if (timerEvent) {
std::cout << "in a timer event called from: " << std::endl;
}
if (callbackId) {
std::cout << "in callback: " << scriptInterface->getFileById(callbackId) << std::endl;
}
std::cout << scriptInterface->getFileById(scriptId) << std::endl;
}
if (function) {
std::cout << function << "(). ";
}
if (stack_trace && scriptInterface) {
std::cout << scriptInterface->getStackTrace(error_desc) << std::endl;
} else {
std::cout << error_desc << std::endl;
}
}
bool LuaScriptInterface::pushFunction(int32_t functionId)
{
lua_rawgeti(luaState, LUA_REGISTRYINDEX, eventTableRef);
if (!isTable(luaState, -1)) {
return false;
}
lua_rawgeti(luaState, -1, functionId);
lua_replace(luaState, -2);
return isFunction(luaState, -1);
}
bool LuaScriptInterface::initState()
{
luaState = g_luaEnvironment.getLuaState();
if (!luaState) {
return false;
}
lua_newtable(luaState);
eventTableRef = luaL_ref(luaState, LUA_REGISTRYINDEX);
runningEventId = EVENT_ID_USER;
return true;
}
bool LuaScriptInterface::closeState()
{
if (!g_luaEnvironment.getLuaState() || !luaState) {
return false;
}
cacheFiles.clear();
if (eventTableRef != -1) {
luaL_unref(luaState, LUA_REGISTRYINDEX, eventTableRef);
eventTableRef = -1;
}
luaState = nullptr;
return true;
}
int LuaScriptInterface::luaErrorHandler(lua_State* L)
{
const std::string& errorMessage = popString(L);
auto interface = getScriptEnv()->getScriptInterface();
assert(interface); //This fires if the ScriptEnvironment hasn't been setup
pushString(L, interface->getStackTrace(errorMessage));
return 1;
}
bool LuaScriptInterface::callFunction(int params)
{
bool result = false;
int size = lua_gettop(luaState);
if (protectedCall(luaState, params, 1) != 0) {
LuaScriptInterface::reportError(nullptr, LuaScriptInterface::getString(luaState, -1));
} else {
result = LuaScriptInterface::getBoolean(luaState, -1);
}
lua_pop(luaState, 1);
if ((lua_gettop(luaState) + params + 1) != size) {
LuaScriptInterface::reportError(nullptr, "Stack size changed!");
}
resetScriptEnv();
return result;
}
void LuaScriptInterface::callVoidFunction(int params)
{
int size = lua_gettop(luaState);
if (protectedCall(luaState, params, 0) != 0) {
LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(luaState));
}
if ((lua_gettop(luaState) + params + 1) != size) {
LuaScriptInterface::reportError(nullptr, "Stack size changed!");
}
resetScriptEnv();
}
void LuaScriptInterface::pushVariant(lua_State* L, const LuaVariant& var)
{
lua_createtable(L, 0, 2);
setField(L, "type", var.type);
switch (var.type) {
case VARIANT_NUMBER:
setField(L, "number", var.number);
break;
case VARIANT_STRING:
setField(L, "string", var.text);
break;
case VARIANT_TARGETPOSITION:
case VARIANT_POSITION: {
pushPosition(L, var.pos);
lua_setfield(L, -2, "pos");
break;
}
default:
break;
}
setMetatable(L, -1, "Variant");
}
void LuaScriptInterface::pushThing(lua_State* L, Thing* thing)
{
if (!thing) {
lua_createtable(L, 0, 4);
setField(L, "uid", 0);
setField(L, "itemid", 0);
setField(L, "actionid", 0);
setField(L, "type", 0);
return;
}
if (Item* item = thing->getItem()) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else if (Creature* creature = thing->getCreature()) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else {
lua_pushnil(L);
}
}
void LuaScriptInterface::pushCylinder(lua_State* L, Cylinder* cylinder)
{
if (Creature* creature = cylinder->getCreature()) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else if (Item* parentItem = cylinder->getItem()) {
pushUserdata<Item>(L, parentItem);
setItemMetatable(L, -1, parentItem);
} else if (Tile* tile = cylinder->getTile()) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else if (cylinder == VirtualCylinder::virtualCylinder) {
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
}
void LuaScriptInterface::pushString(lua_State* L, const std::string& value)
{
lua_pushlstring(L, value.c_str(), value.length());
}
void LuaScriptInterface::pushCallback(lua_State* L, int32_t callback)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, callback);
}
std::string LuaScriptInterface::popString(lua_State* L)
{
if (lua_gettop(L) == 0) {
return std::string();
}
std::string str(getString(L, -1));
lua_pop(L, 1);
return str;
}
int32_t LuaScriptInterface::popCallback(lua_State* L)
{
return luaL_ref(L, LUA_REGISTRYINDEX);
}
// Metatables
void LuaScriptInterface::setMetatable(lua_State* L, int32_t index, const std::string& name)
{
luaL_getmetatable(L, name.c_str());
lua_setmetatable(L, index - 1);
}
void LuaScriptInterface::setWeakMetatable(lua_State* L, int32_t index, const std::string& name)
{
static std::set<std::string> weakObjectTypes;
const std::string& weakName = name + "_weak";
auto result = weakObjectTypes.emplace(name);
if (result.second) {
luaL_getmetatable(L, name.c_str());
int childMetatable = lua_gettop(L);
luaL_newmetatable(L, weakName.c_str());
int metatable = lua_gettop(L);
static const std::vector<std::string> methodKeys = {"__index", "__metatable", "__eq"};
for (const std::string& metaKey : methodKeys) {
lua_getfield(L, childMetatable, metaKey.c_str());
lua_setfield(L, metatable, metaKey.c_str());
}
static const std::vector<int> methodIndexes = {'h', 'p', 't'};
for (int metaIndex : methodIndexes) {
lua_rawgeti(L, childMetatable, metaIndex);
lua_rawseti(L, metatable, metaIndex);
}
lua_pushnil(L);
lua_setfield(L, metatable, "__gc");
lua_remove(L, childMetatable);
} else {
luaL_getmetatable(L, weakName.c_str());
}
lua_setmetatable(L, index - 1);
}
void LuaScriptInterface::setItemMetatable(lua_State* L, int32_t index, const Item* item)
{
if (item->getContainer()) {
luaL_getmetatable(L, "Container");
} else if (item->getTeleport()) {
luaL_getmetatable(L, "Teleport");
} else {
luaL_getmetatable(L, "Item");
}
lua_setmetatable(L, index - 1);
}
void LuaScriptInterface::setCreatureMetatable(lua_State* L, int32_t index, const Creature* creature)
{
if (creature->getPlayer()) {
luaL_getmetatable(L, "Player");
} else if (creature->getMonster()) {
luaL_getmetatable(L, "Monster");
} else {
luaL_getmetatable(L, "Npc");
}
lua_setmetatable(L, index - 1);
}
// Get
std::string LuaScriptInterface::getString(lua_State* L, int32_t arg)
{
size_t len;
const char* c_str = lua_tolstring(L, arg, &len);
if (!c_str || len == 0) {
return std::string();
}
return std::string(c_str, len);
}
Position LuaScriptInterface::getPosition(lua_State* L, int32_t arg, int32_t& stackpos)
{
Position position;
position.x = getField<uint16_t>(L, arg, "x");
position.y = getField<uint16_t>(L, arg, "y");
position.z = getField<uint8_t>(L, arg, "z");
lua_getfield(L, arg, "stackpos");
if (lua_isnil(L, -1) == 1) {
stackpos = 0;
} else {
stackpos = getNumber<int32_t>(L, -1);
}
lua_pop(L, 4);
return position;
}
Position LuaScriptInterface::getPosition(lua_State* L, int32_t arg)
{
Position position;
position.x = getField<uint16_t>(L, arg, "x");
position.y = getField<uint16_t>(L, arg, "y");
position.z = getField<uint8_t>(L, arg, "z");
lua_pop(L, 3);
return position;
}
Outfit_t LuaScriptInterface::getOutfit(lua_State* L, int32_t arg)
{
Outfit_t outfit;
outfit.lookMount = getField<uint16_t>(L, arg, "lookMount");
outfit.lookAddons = getField<uint8_t>(L, arg, "lookAddons");
outfit.lookFeet = getField<uint8_t>(L, arg, "lookFeet");
outfit.lookLegs = getField<uint8_t>(L, arg, "lookLegs");
outfit.lookBody = getField<uint8_t>(L, arg, "lookBody");
outfit.lookHead = getField<uint8_t>(L, arg, "lookHead");
outfit.lookTypeEx = getField<uint16_t>(L, arg, "lookTypeEx");
outfit.lookType = getField<uint16_t>(L, arg, "lookType");
lua_pop(L, 8);
return outfit;
}
LuaVariant LuaScriptInterface::getVariant(lua_State* L, int32_t arg)
{
LuaVariant var;
switch (var.type = getField<LuaVariantType_t>(L, arg, "type")) {
case VARIANT_NUMBER: {
var.number = getField<uint32_t>(L, arg, "number");
lua_pop(L, 2);
break;
}
case VARIANT_STRING: {
var.text = getFieldString(L, arg, "string");
lua_pop(L, 2);
break;
}
case VARIANT_POSITION:
case VARIANT_TARGETPOSITION: {
lua_getfield(L, arg, "pos");
var.pos = getPosition(L, lua_gettop(L));
lua_pop(L, 2);
break;
}
default: {
var.type = VARIANT_NONE;
lua_pop(L, 1);
break;
}
}
return var;
}
Thing* LuaScriptInterface::getThing(lua_State* L, int32_t arg)
{
Thing* thing;
if (lua_getmetatable(L, arg) != 0) {
lua_rawgeti(L, -1, 't');
switch(getNumber<uint32_t>(L, -1)) {
case LuaData_Item:
thing = getUserdata<Item>(L, arg);
break;
case LuaData_Container:
thing = getUserdata<Container>(L, arg);
break;
case LuaData_Teleport:
thing = getUserdata<Teleport>(L, arg);
break;
case LuaData_Player:
thing = getUserdata<Player>(L, arg);
break;
case LuaData_Monster:
thing = getUserdata<Monster>(L, arg);
break;
case LuaData_Npc:
thing = getUserdata<Npc>(L, arg);
break;
default:
thing = nullptr;
break;
}
lua_pop(L, 2);
} else {
thing = getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, arg));
}
return thing;
}
Creature* LuaScriptInterface::getCreature(lua_State* L, int32_t arg)
{
if (isUserdata(L, arg)) {
return getUserdata<Creature>(L, arg);
}
return g_game.getCreatureByID(getNumber<uint32_t>(L, arg));
}
Player* LuaScriptInterface::getPlayer(lua_State* L, int32_t arg)
{
if (isUserdata(L, arg)) {
return getUserdata<Player>(L, arg);
}
return g_game.getPlayerByID(getNumber<uint32_t>(L, arg));
}
std::string LuaScriptInterface::getFieldString(lua_State* L, int32_t arg, const std::string& key)
{
lua_getfield(L, arg, key.c_str());
return getString(L, -1);
}
LuaDataType LuaScriptInterface::getUserdataType(lua_State* L, int32_t arg)
{
if (lua_getmetatable(L, arg) == 0) {
return LuaData_Unknown;
}
lua_rawgeti(L, -1, 't');
LuaDataType type = getNumber<LuaDataType>(L, -1);
lua_pop(L, 2);
return type;
}
// Push
void LuaScriptInterface::pushBoolean(lua_State* L, bool value)
{
lua_pushboolean(L, value ? 1 : 0);
}
void LuaScriptInterface::pushPosition(lua_State* L, const Position& position, int32_t stackpos/* = 0*/)
{
lua_createtable(L, 0, 4);
setField(L, "x", position.x);
setField(L, "y", position.y);
setField(L, "z", position.z);
setField(L, "stackpos", stackpos);
setMetatable(L, -1, "Position");
}
void LuaScriptInterface::pushOutfit(lua_State* L, const Outfit_t& outfit)
{
lua_createtable(L, 0, 8);
setField(L, "lookType", outfit.lookType);
setField(L, "lookTypeEx", outfit.lookTypeEx);
setField(L, "lookHead", outfit.lookHead);
setField(L, "lookBody", outfit.lookBody);
setField(L, "lookLegs", outfit.lookLegs);
setField(L, "lookFeet", outfit.lookFeet);
setField(L, "lookAddons", outfit.lookAddons);
setField(L, "lookMount", outfit.lookMount);
}
#define registerEnum(value) { std::string enumName = #value; registerGlobalVariable(enumName.substr(enumName.find_last_of(':') + 1), value); }
#define registerEnumIn(tableName, value) { std::string enumName = #value; registerVariable(tableName, enumName.substr(enumName.find_last_of(':') + 1), value); }
void LuaScriptInterface::registerFunctions()
{
//getPlayerFlagValue(cid, flag)
lua_register(luaState, "getPlayerFlagValue", LuaScriptInterface::luaGetPlayerFlagValue);
//getPlayerInstantSpellCount(cid)
lua_register(luaState, "getPlayerInstantSpellCount", LuaScriptInterface::luaGetPlayerInstantSpellCount);
//getPlayerInstantSpellInfo(cid, index)
lua_register(luaState, "getPlayerInstantSpellInfo", LuaScriptInterface::luaGetPlayerInstantSpellInfo);
//doPlayerAddItem(uid, itemid, <optional: default: 1> count/subtype)
//doPlayerAddItem(cid, itemid, <optional: default: 1> count, <optional: default: 1> canDropOnMap, <optional: default: 1>subtype)
//Returns uid of the created item
lua_register(luaState, "doPlayerAddItem", LuaScriptInterface::luaDoPlayerAddItem);
//doCreateItem(itemid, type/count, pos)
//Returns uid of the created item, only works on tiles.
lua_register(luaState, "doCreateItem", LuaScriptInterface::luaDoCreateItem);
//doCreateItemEx(itemid, <optional> count/subtype)
lua_register(luaState, "doCreateItemEx", LuaScriptInterface::luaDoCreateItemEx);
//doTileAddItemEx(pos, uid)
lua_register(luaState, "doTileAddItemEx", LuaScriptInterface::luaDoTileAddItemEx);
//doMoveCreature(cid, direction)
lua_register(luaState, "doMoveCreature", LuaScriptInterface::luaDoMoveCreature);
//doSetCreatureLight(cid, lightLevel, lightColor, time)
lua_register(luaState, "doSetCreatureLight", LuaScriptInterface::luaDoSetCreatureLight);
//getCreatureCondition(cid, condition[, subId])
lua_register(luaState, "getCreatureCondition", LuaScriptInterface::luaGetCreatureCondition);
//isValidUID(uid)
lua_register(luaState, "isValidUID", LuaScriptInterface::luaIsValidUID);
//isDepot(uid)
lua_register(luaState, "isDepot", LuaScriptInterface::luaIsDepot);
//isMovable(uid)
lua_register(luaState, "isMovable", LuaScriptInterface::luaIsMoveable);
//doAddContainerItem(uid, itemid, <optional> count/subtype)
lua_register(luaState, "doAddContainerItem", LuaScriptInterface::luaDoAddContainerItem);
//getDepotId(uid)
lua_register(luaState, "getDepotId", LuaScriptInterface::luaGetDepotId);
//getWorldTime()
lua_register(luaState, "getWorldTime", LuaScriptInterface::luaGetWorldTime);
//getWorldLight()
lua_register(luaState, "getWorldLight", LuaScriptInterface::luaGetWorldLight);
//getWorldUpTime()
lua_register(luaState, "getWorldUpTime", LuaScriptInterface::luaGetWorldUpTime);
//createCombatArea( {area}, <optional> {extArea} )
lua_register(luaState, "createCombatArea", LuaScriptInterface::luaCreateCombatArea);
//doAreaCombatHealth(cid, type, pos, area, min, max, effect)
lua_register(luaState, "doAreaCombatHealth", LuaScriptInterface::luaDoAreaCombatHealth);
//doTargetCombatHealth(cid, target, type, min, max, effect)
lua_register(luaState, "doTargetCombatHealth", LuaScriptInterface::luaDoTargetCombatHealth);
//doAreaCombatMana(cid, pos, area, min, max, effect)
lua_register(luaState, "doAreaCombatMana", LuaScriptInterface::luaDoAreaCombatMana);
//doTargetCombatMana(cid, target, min, max, effect)
lua_register(luaState, "doTargetCombatMana", LuaScriptInterface::luaDoTargetCombatMana);
//doAreaCombatCondition(cid, pos, area, condition, effect)
lua_register(luaState, "doAreaCombatCondition", LuaScriptInterface::luaDoAreaCombatCondition);
//doTargetCombatCondition(cid, target, condition, effect)
lua_register(luaState, "doTargetCombatCondition", LuaScriptInterface::luaDoTargetCombatCondition);
//doAreaCombatDispel(cid, pos, area, type, effect)
lua_register(luaState, "doAreaCombatDispel", LuaScriptInterface::luaDoAreaCombatDispel);
//doTargetCombatDispel(cid, target, type, effect)
lua_register(luaState, "doTargetCombatDispel", LuaScriptInterface::luaDoTargetCombatDispel);
//doChallengeCreature(cid, target)
lua_register(luaState, "doChallengeCreature", LuaScriptInterface::luaDoChallengeCreature);
//doSetMonsterOutfit(cid, name, time)
lua_register(luaState, "doSetMonsterOutfit", LuaScriptInterface::luaSetMonsterOutfit);
//doSetItemOutfit(cid, item, time)
lua_register(luaState, "doSetItemOutfit", LuaScriptInterface::luaSetItemOutfit);
//doSetCreatureOutfit(cid, outfit, time)
lua_register(luaState, "doSetCreatureOutfit", LuaScriptInterface::luaSetCreatureOutfit);
//isInArray(array, value)
lua_register(luaState, "isInArray", LuaScriptInterface::luaIsInArray);
//addEvent(callback, delay, ...)
lua_register(luaState, "addEvent", LuaScriptInterface::luaAddEvent);
//stopEvent(eventid)
lua_register(luaState, "stopEvent", LuaScriptInterface::luaStopEvent);
//saveServer()
lua_register(luaState, "saveServer", LuaScriptInterface::luaSaveServer);
//cleanMap()
lua_register(luaState, "cleanMap", LuaScriptInterface::luaCleanMap);
//debugPrint(text)
lua_register(luaState, "debugPrint", LuaScriptInterface::luaDebugPrint);
//isInWar(cid, target)
lua_register(luaState, "isInWar", LuaScriptInterface::luaIsInWar);
//getWaypointPosition(name)
lua_register(luaState, "getWaypointPositionByName", LuaScriptInterface::luaGetWaypointPositionByName);
//sendChannelMessage(channelId, type, message)
lua_register(luaState, "sendChannelMessage", LuaScriptInterface::luaSendChannelMessage);
//sendGuildChannelMessage(guildId, type, message)
lua_register(luaState, "sendGuildChannelMessage", LuaScriptInterface::luaSendGuildChannelMessage);
#ifndef LUAJIT_VERSION
//bit operations for Lua, based on bitlib project release 24
//bit.bnot, bit.band, bit.bor, bit.bxor, bit.lshift, bit.rshift
luaL_register(luaState, "bit", LuaScriptInterface::luaBitReg);
#endif
//configManager table
luaL_register(luaState, "configManager", LuaScriptInterface::luaConfigManagerTable);
//db table
luaL_register(luaState, "db", LuaScriptInterface::luaDatabaseTable);
//result table
luaL_register(luaState, "result", LuaScriptInterface::luaResultTable);
/* New functions */
//registerClass(className, baseClass, newFunction)
//registerTable(tableName)
//registerMethod(className, functionName, function)
//registerMetaMethod(className, functionName, function)
//registerGlobalMethod(functionName, function)
//registerVariable(tableName, name, value)
//registerGlobalVariable(name, value)
//registerEnum(value)
//registerEnumIn(tableName, value)
// Enums
registerEnum(ACCOUNT_TYPE_NORMAL)
registerEnum(ACCOUNT_TYPE_TUTOR)
registerEnum(ACCOUNT_TYPE_SENIORTUTOR)
registerEnum(ACCOUNT_TYPE_GAMEMASTER)
registerEnum(ACCOUNT_TYPE_GOD)
registerEnum(CALLBACK_PARAM_LEVELMAGICVALUE)
registerEnum(CALLBACK_PARAM_SKILLVALUE)
registerEnum(CALLBACK_PARAM_TARGETTILE)
registerEnum(CALLBACK_PARAM_TARGETCREATURE)
registerEnum(COMBAT_FORMULA_UNDEFINED)
registerEnum(COMBAT_FORMULA_LEVELMAGIC)
registerEnum(COMBAT_FORMULA_SKILL)
registerEnum(COMBAT_FORMULA_DAMAGE)
registerEnum(DIRECTION_NORTH)
registerEnum(DIRECTION_EAST)
registerEnum(DIRECTION_SOUTH)
registerEnum(DIRECTION_WEST)
registerEnum(DIRECTION_SOUTHWEST)
registerEnum(DIRECTION_SOUTHEAST)
registerEnum(DIRECTION_NORTHWEST)
registerEnum(DIRECTION_NORTHEAST)
registerEnum(COMBAT_NONE)
registerEnum(COMBAT_PHYSICALDAMAGE)
registerEnum(COMBAT_ENERGYDAMAGE)
registerEnum(COMBAT_EARTHDAMAGE)
registerEnum(COMBAT_FIREDAMAGE)
registerEnum(COMBAT_UNDEFINEDDAMAGE)
registerEnum(COMBAT_LIFEDRAIN)
registerEnum(COMBAT_MANADRAIN)
registerEnum(COMBAT_HEALING)
registerEnum(COMBAT_DROWNDAMAGE)
registerEnum(COMBAT_ICEDAMAGE)
registerEnum(COMBAT_HOLYDAMAGE)
registerEnum(COMBAT_DEATHDAMAGE)
registerEnum(COMBAT_PARAM_TYPE)
registerEnum(COMBAT_PARAM_EFFECT)
registerEnum(COMBAT_PARAM_DISTANCEEFFECT)
registerEnum(COMBAT_PARAM_BLOCKSHIELD)
registerEnum(COMBAT_PARAM_BLOCKARMOR)
registerEnum(COMBAT_PARAM_TARGETCASTERORTOPMOST)
registerEnum(COMBAT_PARAM_CREATEITEM)
registerEnum(COMBAT_PARAM_AGGRESSIVE)
registerEnum(COMBAT_PARAM_DISPEL)
registerEnum(COMBAT_PARAM_USECHARGES)
registerEnum(CONDITION_NONE)
registerEnum(CONDITION_POISON)
registerEnum(CONDITION_FIRE)
registerEnum(CONDITION_ENERGY)
registerEnum(CONDITION_BLEEDING)
registerEnum(CONDITION_HASTE)
registerEnum(CONDITION_PARALYZE)
registerEnum(CONDITION_OUTFIT)
registerEnum(CONDITION_INVISIBLE)
registerEnum(CONDITION_LIGHT)
registerEnum(CONDITION_MANASHIELD)
registerEnum(CONDITION_INFIGHT)
registerEnum(CONDITION_DRUNK)
registerEnum(CONDITION_EXHAUST_WEAPON)
registerEnum(CONDITION_REGENERATION)
registerEnum(CONDITION_SOUL)
registerEnum(CONDITION_DROWN)
registerEnum(CONDITION_MUTED)
registerEnum(CONDITION_CHANNELMUTEDTICKS)
registerEnum(CONDITION_YELLTICKS)
registerEnum(CONDITION_ATTRIBUTES)
registerEnum(CONDITION_FREEZING)
registerEnum(CONDITION_DAZZLED)
registerEnum(CONDITION_CURSED)
registerEnum(CONDITION_EXHAUST_COMBAT)
registerEnum(CONDITION_EXHAUST_HEAL)
registerEnum(CONDITION_PACIFIED)
registerEnum(CONDITION_SPELLCOOLDOWN)
registerEnum(CONDITION_SPELLGROUPCOOLDOWN)
registerEnum(CONDITIONID_DEFAULT)
registerEnum(CONDITIONID_COMBAT)
registerEnum(CONDITIONID_HEAD)
registerEnum(CONDITIONID_NECKLACE)
registerEnum(CONDITIONID_BACKPACK)
registerEnum(CONDITIONID_ARMOR)
registerEnum(CONDITIONID_RIGHT)
registerEnum(CONDITIONID_LEFT)
registerEnum(CONDITIONID_LEGS)
registerEnum(CONDITIONID_FEET)
registerEnum(CONDITIONID_RING)
registerEnum(CONDITIONID_AMMO)
registerEnum(CONDITION_PARAM_OWNER)
registerEnum(CONDITION_PARAM_TICKS)
registerEnum(CONDITION_PARAM_HEALTHGAIN)
registerEnum(CONDITION_PARAM_HEALTHTICKS)
registerEnum(CONDITION_PARAM_MANAGAIN)
registerEnum(CONDITION_PARAM_MANATICKS)
registerEnum(CONDITION_PARAM_DELAYED)
registerEnum(CONDITION_PARAM_SPEED)
registerEnum(CONDITION_PARAM_LIGHT_LEVEL)
registerEnum(CONDITION_PARAM_LIGHT_COLOR)
registerEnum(CONDITION_PARAM_SOULGAIN)
registerEnum(CONDITION_PARAM_SOULTICKS)
registerEnum(CONDITION_PARAM_MINVALUE)
registerEnum(CONDITION_PARAM_MAXVALUE)
registerEnum(CONDITION_PARAM_STARTVALUE)
registerEnum(CONDITION_PARAM_TICKINTERVAL)
registerEnum(CONDITION_PARAM_FORCEUPDATE)
registerEnum(CONDITION_PARAM_SKILL_MELEE)
registerEnum(CONDITION_PARAM_SKILL_FIST)
registerEnum(CONDITION_PARAM_SKILL_CLUB)
registerEnum(CONDITION_PARAM_SKILL_SWORD)
registerEnum(CONDITION_PARAM_SKILL_AXE)
registerEnum(CONDITION_PARAM_SKILL_DISTANCE)
registerEnum(CONDITION_PARAM_SKILL_SHIELD)
registerEnum(CONDITION_PARAM_SKILL_FISHING)
registerEnum(CONDITION_PARAM_STAT_MAXHITPOINTS)
registerEnum(CONDITION_PARAM_STAT_MAXMANAPOINTS)
registerEnum(CONDITION_PARAM_STAT_MAGICPOINTS)
registerEnum(CONDITION_PARAM_STAT_MAXHITPOINTSPERCENT)
registerEnum(CONDITION_PARAM_STAT_MAXMANAPOINTSPERCENT)
registerEnum(CONDITION_PARAM_STAT_MAGICPOINTSPERCENT)
registerEnum(CONDITION_PARAM_PERIODICDAMAGE)
registerEnum(CONDITION_PARAM_SKILL_MELEEPERCENT)
registerEnum(CONDITION_PARAM_SKILL_FISTPERCENT)
registerEnum(CONDITION_PARAM_SKILL_CLUBPERCENT)
registerEnum(CONDITION_PARAM_SKILL_SWORDPERCENT)
registerEnum(CONDITION_PARAM_SKILL_AXEPERCENT)
registerEnum(CONDITION_PARAM_SKILL_DISTANCEPERCENT)
registerEnum(CONDITION_PARAM_SKILL_SHIELDPERCENT)
registerEnum(CONDITION_PARAM_SKILL_FISHINGPERCENT)
registerEnum(CONDITION_PARAM_BUFF_SPELL)
registerEnum(CONDITION_PARAM_SUBID)
registerEnum(CONDITION_PARAM_FIELD)
registerEnum(CONST_ME_NONE)
registerEnum(CONST_ME_DRAWBLOOD)
registerEnum(CONST_ME_LOSEENERGY)
registerEnum(CONST_ME_POFF)
registerEnum(CONST_ME_BLOCKHIT)
registerEnum(CONST_ME_EXPLOSIONAREA)
registerEnum(CONST_ME_EXPLOSIONHIT)
registerEnum(CONST_ME_FIREAREA)
registerEnum(CONST_ME_YELLOW_RINGS)
registerEnum(CONST_ME_GREEN_RINGS)
registerEnum(CONST_ME_HITAREA)
registerEnum(CONST_ME_TELEPORT)
registerEnum(CONST_ME_ENERGYHIT)
registerEnum(CONST_ME_MAGIC_BLUE)
registerEnum(CONST_ME_MAGIC_RED)
registerEnum(CONST_ME_MAGIC_GREEN)
registerEnum(CONST_ME_HITBYFIRE)
registerEnum(CONST_ME_HITBYPOISON)
registerEnum(CONST_ME_MORTAREA)
registerEnum(CONST_ME_SOUND_GREEN)
registerEnum(CONST_ME_SOUND_RED)
registerEnum(CONST_ME_POISONAREA)
registerEnum(CONST_ME_SOUND_YELLOW)
registerEnum(CONST_ME_SOUND_PURPLE)
registerEnum(CONST_ME_SOUND_BLUE)
registerEnum(CONST_ME_SOUND_WHITE)
registerEnum(CONST_ME_BUBBLES)
registerEnum(CONST_ME_CRAPS)
registerEnum(CONST_ME_GIFT_WRAPS)
registerEnum(CONST_ME_FIREWORK_YELLOW)
registerEnum(CONST_ME_FIREWORK_RED)
registerEnum(CONST_ME_FIREWORK_BLUE)
registerEnum(CONST_ME_STUN)
registerEnum(CONST_ME_SLEEP)
registerEnum(CONST_ME_WATERCREATURE)
registerEnum(CONST_ME_GROUNDSHAKER)
registerEnum(CONST_ME_HEARTS)
registerEnum(CONST_ME_FIREATTACK)
registerEnum(CONST_ME_ENERGYAREA)
registerEnum(CONST_ME_SMALLCLOUDS)
registerEnum(CONST_ME_HOLYDAMAGE)
registerEnum(CONST_ME_BIGCLOUDS)
registerEnum(CONST_ME_ICEAREA)
registerEnum(CONST_ME_ICETORNADO)
registerEnum(CONST_ME_ICEATTACK)
registerEnum(CONST_ME_STONES)
registerEnum(CONST_ME_SMALLPLANTS)
registerEnum(CONST_ME_CARNIPHILA)
registerEnum(CONST_ME_PURPLEENERGY)
registerEnum(CONST_ME_YELLOWENERGY)
registerEnum(CONST_ME_HOLYAREA)
registerEnum(CONST_ME_BIGPLANTS)
registerEnum(CONST_ME_CAKE)
registerEnum(CONST_ME_GIANTICE)
registerEnum(CONST_ME_WATERSPLASH)
registerEnum(CONST_ME_PLANTATTACK)
registerEnum(CONST_ME_TUTORIALARROW)
registerEnum(CONST_ME_TUTORIALSQUARE)
registerEnum(CONST_ME_MIRRORHORIZONTAL)
registerEnum(CONST_ME_MIRRORVERTICAL)
registerEnum(CONST_ME_SKULLHORIZONTAL)
registerEnum(CONST_ME_SKULLVERTICAL)
registerEnum(CONST_ME_ASSASSIN)
registerEnum(CONST_ME_STEPSHORIZONTAL)
registerEnum(CONST_ME_BLOODYSTEPS)
registerEnum(CONST_ME_STEPSVERTICAL)
registerEnum(CONST_ME_YALAHARIGHOST)
registerEnum(CONST_ME_BATS)
registerEnum(CONST_ME_SMOKE)
registerEnum(CONST_ME_INSECTS)
registerEnum(CONST_ME_DRAGONHEAD)
registerEnum(CONST_ME_ORCSHAMAN)
registerEnum(CONST_ME_ORCSHAMAN_FIRE)
registerEnum(CONST_ME_THUNDER)
registerEnum(CONST_ME_FERUMBRAS)
registerEnum(CONST_ME_CONFETTI_HORIZONTAL)
registerEnum(CONST_ME_CONFETTI_VERTICAL)
registerEnum(CONST_ME_BLACKSMOKE)
registerEnum(CONST_ME_REDSMOKE)
registerEnum(CONST_ME_YELLOWSMOKE)
registerEnum(CONST_ME_GREENSMOKE)
registerEnum(CONST_ME_PURPLESMOKE)
registerEnum(CONST_ANI_NONE)
registerEnum(CONST_ANI_SPEAR)
registerEnum(CONST_ANI_BOLT)
registerEnum(CONST_ANI_ARROW)
registerEnum(CONST_ANI_FIRE)
registerEnum(CONST_ANI_ENERGY)
registerEnum(CONST_ANI_POISONARROW)
registerEnum(CONST_ANI_BURSTARROW)
registerEnum(CONST_ANI_THROWINGSTAR)
registerEnum(CONST_ANI_THROWINGKNIFE)
registerEnum(CONST_ANI_SMALLSTONE)
registerEnum(CONST_ANI_DEATH)
registerEnum(CONST_ANI_LARGEROCK)
registerEnum(CONST_ANI_SNOWBALL)
registerEnum(CONST_ANI_POWERBOLT)
registerEnum(CONST_ANI_POISON)
registerEnum(CONST_ANI_INFERNALBOLT)
registerEnum(CONST_ANI_HUNTINGSPEAR)
registerEnum(CONST_ANI_ENCHANTEDSPEAR)
registerEnum(CONST_ANI_REDSTAR)
registerEnum(CONST_ANI_GREENSTAR)
registerEnum(CONST_ANI_ROYALSPEAR)
registerEnum(CONST_ANI_SNIPERARROW)
registerEnum(CONST_ANI_ONYXARROW)
registerEnum(CONST_ANI_PIERCINGBOLT)
registerEnum(CONST_ANI_WHIRLWINDSWORD)
registerEnum(CONST_ANI_WHIRLWINDAXE)
registerEnum(CONST_ANI_WHIRLWINDCLUB)
registerEnum(CONST_ANI_ETHEREALSPEAR)
registerEnum(CONST_ANI_ICE)
registerEnum(CONST_ANI_EARTH)
registerEnum(CONST_ANI_HOLY)
registerEnum(CONST_ANI_SUDDENDEATH)
registerEnum(CONST_ANI_FLASHARROW)
registerEnum(CONST_ANI_FLAMMINGARROW)
registerEnum(CONST_ANI_SHIVERARROW)
registerEnum(CONST_ANI_ENERGYBALL)
registerEnum(CONST_ANI_SMALLICE)
registerEnum(CONST_ANI_SMALLHOLY)
registerEnum(CONST_ANI_SMALLEARTH)
registerEnum(CONST_ANI_EARTHARROW)
registerEnum(CONST_ANI_EXPLOSION)
registerEnum(CONST_ANI_CAKE)
registerEnum(CONST_ANI_TARSALARROW)
registerEnum(CONST_ANI_VORTEXBOLT)
registerEnum(CONST_ANI_PRISMATICBOLT)
registerEnum(CONST_ANI_CRYSTALLINEARROW)
registerEnum(CONST_ANI_DRILLBOLT)
registerEnum(CONST_ANI_ENVENOMEDARROW)
registerEnum(CONST_ANI_GLOOTHSPEAR)
registerEnum(CONST_ANI_SIMPLEARROW)
registerEnum(CONST_ANI_WEAPONTYPE)
registerEnum(CONST_PROP_BLOCKSOLID)
registerEnum(CONST_PROP_HASHEIGHT)
registerEnum(CONST_PROP_BLOCKPROJECTILE)
registerEnum(CONST_PROP_BLOCKPATH)
registerEnum(CONST_PROP_ISVERTICAL)
registerEnum(CONST_PROP_ISHORIZONTAL)
registerEnum(CONST_PROP_MOVEABLE)
registerEnum(CONST_PROP_IMMOVABLEBLOCKSOLID)
registerEnum(CONST_PROP_IMMOVABLEBLOCKPATH)
registerEnum(CONST_PROP_IMMOVABLENOFIELDBLOCKPATH)
registerEnum(CONST_PROP_NOFIELDBLOCKPATH)
registerEnum(CONST_PROP_SUPPORTHANGABLE)
registerEnum(CONST_SLOT_HEAD)
registerEnum(CONST_SLOT_NECKLACE)
registerEnum(CONST_SLOT_BACKPACK)
registerEnum(CONST_SLOT_ARMOR)
registerEnum(CONST_SLOT_RIGHT)
registerEnum(CONST_SLOT_LEFT)
registerEnum(CONST_SLOT_LEGS)
registerEnum(CONST_SLOT_FEET)
registerEnum(CONST_SLOT_RING)
registerEnum(CONST_SLOT_AMMO)
registerEnum(CREATURE_EVENT_NONE)
registerEnum(CREATURE_EVENT_LOGIN)
registerEnum(CREATURE_EVENT_LOGOUT)
registerEnum(CREATURE_EVENT_THINK)
registerEnum(CREATURE_EVENT_PREPAREDEATH)
registerEnum(CREATURE_EVENT_DEATH)
registerEnum(CREATURE_EVENT_KILL)
registerEnum(CREATURE_EVENT_ADVANCE)
registerEnum(CREATURE_EVENT_MODALWINDOW)
registerEnum(CREATURE_EVENT_TEXTEDIT)
registerEnum(CREATURE_EVENT_HEALTHCHANGE)
registerEnum(CREATURE_EVENT_MANACHANGE)
registerEnum(CREATURE_EVENT_EXTENDED_OPCODE)
registerEnum(GAME_STATE_STARTUP)
registerEnum(GAME_STATE_INIT)
registerEnum(GAME_STATE_NORMAL)
registerEnum(GAME_STATE_CLOSED)
registerEnum(GAME_STATE_SHUTDOWN)
registerEnum(GAME_STATE_CLOSING)
registerEnum(GAME_STATE_MAINTAIN)
registerEnum(MESSAGE_STATUS_CONSOLE_BLUE)
registerEnum(MESSAGE_STATUS_CONSOLE_RED)
registerEnum(MESSAGE_STATUS_DEFAULT)
registerEnum(MESSAGE_STATUS_WARNING)
registerEnum(MESSAGE_EVENT_ADVANCE)
registerEnum(MESSAGE_STATUS_SMALL)
registerEnum(MESSAGE_INFO_DESCR)
registerEnum(MESSAGE_DAMAGE_DEALT)
registerEnum(MESSAGE_DAMAGE_RECEIVED)
registerEnum(MESSAGE_HEALED)
registerEnum(MESSAGE_EXPERIENCE)
registerEnum(MESSAGE_DAMAGE_OTHERS)
registerEnum(MESSAGE_HEALED_OTHERS)
registerEnum(MESSAGE_EXPERIENCE_OTHERS)
registerEnum(MESSAGE_EVENT_DEFAULT)
registerEnum(MESSAGE_EVENT_ORANGE)
registerEnum(MESSAGE_STATUS_CONSOLE_ORANGE)
registerEnum(CREATURETYPE_PLAYER)
registerEnum(CREATURETYPE_MONSTER)
registerEnum(CREATURETYPE_NPC)
registerEnum(CREATURETYPE_SUMMON_OWN)
registerEnum(CREATURETYPE_SUMMON_OTHERS)
registerEnum(CLIENTOS_LINUX)
registerEnum(CLIENTOS_WINDOWS)
registerEnum(CLIENTOS_FLASH)
registerEnum(CLIENTOS_OTCLIENT_LINUX)
registerEnum(CLIENTOS_OTCLIENT_WINDOWS)
registerEnum(CLIENTOS_OTCLIENT_MAC)
registerEnum(ITEM_ATTRIBUTE_NONE)
registerEnum(ITEM_ATTRIBUTE_ACTIONID)
registerEnum(ITEM_ATTRIBUTE_UNIQUEID)
registerEnum(ITEM_ATTRIBUTE_DESCRIPTION)
registerEnum(ITEM_ATTRIBUTE_TEXT)
registerEnum(ITEM_ATTRIBUTE_DATE)
registerEnum(ITEM_ATTRIBUTE_WRITER)
registerEnum(ITEM_ATTRIBUTE_NAME)
registerEnum(ITEM_ATTRIBUTE_ARTICLE)
registerEnum(ITEM_ATTRIBUTE_PLURALNAME)
registerEnum(ITEM_ATTRIBUTE_WEIGHT)
registerEnum(ITEM_ATTRIBUTE_ATTACK)
registerEnum(ITEM_ATTRIBUTE_DEFENSE)
registerEnum(ITEM_ATTRIBUTE_EXTRADEFENSE)
registerEnum(ITEM_ATTRIBUTE_ARMOR)
registerEnum(ITEM_ATTRIBUTE_HITCHANCE)
registerEnum(ITEM_ATTRIBUTE_SHOOTRANGE)
registerEnum(ITEM_ATTRIBUTE_OWNER)
registerEnum(ITEM_ATTRIBUTE_DURATION)
registerEnum(ITEM_ATTRIBUTE_DECAYSTATE)
registerEnum(ITEM_ATTRIBUTE_CORPSEOWNER)
registerEnum(ITEM_ATTRIBUTE_CHARGES)
registerEnum(ITEM_ATTRIBUTE_FLUIDTYPE)
registerEnum(ITEM_ATTRIBUTE_DOORID)
registerEnum(ITEM_TYPE_DEPOT)
registerEnum(ITEM_TYPE_MAILBOX)
registerEnum(ITEM_TYPE_TRASHHOLDER)
registerEnum(ITEM_TYPE_CONTAINER)
registerEnum(ITEM_TYPE_DOOR)
registerEnum(ITEM_TYPE_MAGICFIELD)
registerEnum(ITEM_TYPE_TELEPORT)
registerEnum(ITEM_TYPE_BED)
registerEnum(ITEM_TYPE_KEY)
registerEnum(ITEM_TYPE_RUNE)
registerEnum(ITEM_BAG)
registerEnum(ITEM_GOLD_COIN)
registerEnum(ITEM_PLATINUM_COIN)
registerEnum(ITEM_CRYSTAL_COIN)
registerEnum(ITEM_AMULETOFLOSS)
registerEnum(ITEM_PARCEL)
registerEnum(ITEM_LABEL)
registerEnum(ITEM_FIREFIELD_PVP_FULL)
registerEnum(ITEM_FIREFIELD_PVP_MEDIUM)
registerEnum(ITEM_FIREFIELD_PVP_SMALL)
registerEnum(ITEM_FIREFIELD_PERSISTENT_FULL)
registerEnum(ITEM_FIREFIELD_PERSISTENT_MEDIUM)
registerEnum(ITEM_FIREFIELD_PERSISTENT_SMALL)
registerEnum(ITEM_FIREFIELD_NOPVP)
registerEnum(ITEM_POISONFIELD_PVP)
registerEnum(ITEM_POISONFIELD_PERSISTENT)
registerEnum(ITEM_POISONFIELD_NOPVP)
registerEnum(ITEM_ENERGYFIELD_PVP)
registerEnum(ITEM_ENERGYFIELD_PERSISTENT)
registerEnum(ITEM_ENERGYFIELD_NOPVP)
registerEnum(ITEM_MAGICWALL)
registerEnum(ITEM_MAGICWALL_PERSISTENT)
registerEnum(ITEM_MAGICWALL_SAFE)
registerEnum(ITEM_WILDGROWTH)
registerEnum(ITEM_WILDGROWTH_PERSISTENT)
registerEnum(ITEM_WILDGROWTH_SAFE)
registerEnum(PlayerFlag_CannotUseCombat)
registerEnum(PlayerFlag_CannotAttackPlayer)
registerEnum(PlayerFlag_CannotAttackMonster)
registerEnum(PlayerFlag_CannotBeAttacked)
registerEnum(PlayerFlag_CanConvinceAll)
registerEnum(PlayerFlag_CanSummonAll)
registerEnum(PlayerFlag_CanIllusionAll)
registerEnum(PlayerFlag_CanSenseInvisibility)
registerEnum(PlayerFlag_IgnoredByMonsters)
registerEnum(PlayerFlag_NotGainInFight)
registerEnum(PlayerFlag_HasInfiniteMana)
registerEnum(PlayerFlag_HasInfiniteSoul)
registerEnum(PlayerFlag_HasNoExhaustion)
registerEnum(PlayerFlag_CannotUseSpells)
registerEnum(PlayerFlag_CannotPickupItem)
registerEnum(PlayerFlag_CanAlwaysLogin)
registerEnum(PlayerFlag_CanBroadcast)
registerEnum(PlayerFlag_CanEditHouses)
registerEnum(PlayerFlag_CannotBeBanned)
registerEnum(PlayerFlag_CannotBePushed)
registerEnum(PlayerFlag_HasInfiniteCapacity)
registerEnum(PlayerFlag_CanPushAllCreatures)
registerEnum(PlayerFlag_CanTalkRedPrivate)
registerEnum(PlayerFlag_CanTalkRedChannel)
registerEnum(PlayerFlag_TalkOrangeHelpChannel)
registerEnum(PlayerFlag_NotGainExperience)
registerEnum(PlayerFlag_NotGainMana)
registerEnum(PlayerFlag_NotGainHealth)
registerEnum(PlayerFlag_NotGainSkill)
registerEnum(PlayerFlag_SetMaxSpeed)
registerEnum(PlayerFlag_SpecialVIP)
registerEnum(PlayerFlag_NotGenerateLoot)
registerEnum(PlayerFlag_CanTalkRedChannelAnonymous)
registerEnum(PlayerFlag_IgnoreProtectionZone)
registerEnum(PlayerFlag_IgnoreSpellCheck)
registerEnum(PlayerFlag_IgnoreWeaponCheck)
registerEnum(PlayerFlag_CannotBeMuted)
registerEnum(PlayerFlag_IsAlwaysPremium)
registerEnum(PLAYERSEX_FEMALE)
registerEnum(PLAYERSEX_MALE)
registerEnum(VOCATION_NONE)
registerEnum(SKILL_FIST)
registerEnum(SKILL_CLUB)
registerEnum(SKILL_SWORD)
registerEnum(SKILL_AXE)
registerEnum(SKILL_DISTANCE)
registerEnum(SKILL_SHIELD)
registerEnum(SKILL_FISHING)
registerEnum(SKILL_MAGLEVEL)
registerEnum(SKILL_LEVEL)
registerEnum(SKULL_NONE)
registerEnum(SKULL_YELLOW)
registerEnum(SKULL_GREEN)
registerEnum(SKULL_WHITE)
registerEnum(SKULL_RED)
registerEnum(SKULL_BLACK)
registerEnum(SKULL_ORANGE)
registerEnum(TALKTYPE_SAY)
registerEnum(TALKTYPE_WHISPER)
registerEnum(TALKTYPE_YELL)
registerEnum(TALKTYPE_PRIVATE_FROM)
registerEnum(TALKTYPE_PRIVATE_TO)
registerEnum(TALKTYPE_CHANNEL_Y)
registerEnum(TALKTYPE_CHANNEL_O)
registerEnum(TALKTYPE_PRIVATE_NP)
registerEnum(TALKTYPE_PRIVATE_PN)
registerEnum(TALKTYPE_BROADCAST)
registerEnum(TALKTYPE_CHANNEL_R1)
registerEnum(TALKTYPE_PRIVATE_RED_FROM)
registerEnum(TALKTYPE_PRIVATE_RED_TO)
registerEnum(TALKTYPE_MONSTER_SAY)
registerEnum(TALKTYPE_MONSTER_YELL)
registerEnum(TALKTYPE_CHANNEL_R2)
registerEnum(TEXTCOLOR_BLUE)
registerEnum(TEXTCOLOR_LIGHTGREEN)
registerEnum(TEXTCOLOR_LIGHTBLUE)
registerEnum(TEXTCOLOR_MAYABLUE)
registerEnum(TEXTCOLOR_DARKRED)
registerEnum(TEXTCOLOR_LIGHTGREY)
registerEnum(TEXTCOLOR_SKYBLUE)
registerEnum(TEXTCOLOR_PURPLE)
registerEnum(TEXTCOLOR_RED)
registerEnum(TEXTCOLOR_ORANGE)
registerEnum(TEXTCOLOR_YELLOW)
registerEnum(TEXTCOLOR_WHITE_EXP)
registerEnum(TEXTCOLOR_NONE)
registerEnum(TILESTATE_NONE)
registerEnum(TILESTATE_PROTECTIONZONE)
registerEnum(TILESTATE_NOPVPZONE)
registerEnum(TILESTATE_NOLOGOUT)
registerEnum(TILESTATE_PVPZONE)
registerEnum(TILESTATE_FLOORCHANGE)
registerEnum(TILESTATE_FLOORCHANGE_DOWN)
registerEnum(TILESTATE_FLOORCHANGE_NORTH)
registerEnum(TILESTATE_FLOORCHANGE_SOUTH)
registerEnum(TILESTATE_FLOORCHANGE_EAST)
registerEnum(TILESTATE_FLOORCHANGE_WEST)
registerEnum(TILESTATE_TELEPORT)
registerEnum(TILESTATE_MAGICFIELD)
registerEnum(TILESTATE_MAILBOX)
registerEnum(TILESTATE_TRASHHOLDER)
registerEnum(TILESTATE_BED)
registerEnum(TILESTATE_DEPOT)
registerEnum(TILESTATE_BLOCKSOLID)
registerEnum(TILESTATE_BLOCKPATH)
registerEnum(TILESTATE_IMMOVABLEBLOCKSOLID)
registerEnum(TILESTATE_IMMOVABLEBLOCKPATH)
registerEnum(TILESTATE_IMMOVABLENOFIELDBLOCKPATH)
registerEnum(TILESTATE_NOFIELDBLOCKPATH)
registerEnum(TILESTATE_FLOORCHANGE_SOUTH_ALT)
registerEnum(TILESTATE_FLOORCHANGE_EAST_ALT)
registerEnum(TILESTATE_SUPPORTS_HANGABLE)
registerEnum(WEAPON_NONE)
registerEnum(WEAPON_SWORD)
registerEnum(WEAPON_CLUB)
registerEnum(WEAPON_AXE)
registerEnum(WEAPON_SHIELD)
registerEnum(WEAPON_DISTANCE)
registerEnum(WEAPON_WAND)
registerEnum(WEAPON_AMMO)
registerEnum(WORLD_TYPE_NO_PVP)
registerEnum(WORLD_TYPE_PVP)
registerEnum(WORLD_TYPE_PVP_ENFORCED)
// Use with container:addItem, container:addItemEx and possibly other functions.
registerEnum(FLAG_NOLIMIT)
registerEnum(FLAG_IGNOREBLOCKITEM)
registerEnum(FLAG_IGNOREBLOCKCREATURE)
registerEnum(FLAG_CHILDISOWNER)
registerEnum(FLAG_PATHFINDING)
registerEnum(FLAG_IGNOREFIELDDAMAGE)
registerEnum(FLAG_IGNORENOTMOVEABLE)
registerEnum(FLAG_IGNOREAUTOSTACK)
// Use with itemType:getSlotPosition
registerEnum(SLOTP_WHEREEVER)
registerEnum(SLOTP_HEAD)
registerEnum(SLOTP_NECKLACE)
registerEnum(SLOTP_BACKPACK)
registerEnum(SLOTP_ARMOR)
registerEnum(SLOTP_RIGHT)
registerEnum(SLOTP_LEFT)
registerEnum(SLOTP_LEGS)
registerEnum(SLOTP_FEET)
registerEnum(SLOTP_RING)
registerEnum(SLOTP_AMMO)
registerEnum(SLOTP_DEPOT)
registerEnum(SLOTP_TWO_HAND)
// Use with combat functions
registerEnum(ORIGIN_NONE)
registerEnum(ORIGIN_CONDITION)
registerEnum(ORIGIN_SPELL)
registerEnum(ORIGIN_MELEE)
registerEnum(ORIGIN_RANGED)
// Use with house:getAccessList, house:setAccessList
registerEnum(GUEST_LIST)
registerEnum(SUBOWNER_LIST)
// Use with npc:setSpeechBubble
registerEnum(SPEECHBUBBLE_NONE)
registerEnum(SPEECHBUBBLE_NORMAL)
registerEnum(SPEECHBUBBLE_TRADE)
registerEnum(SPEECHBUBBLE_QUEST)
registerEnum(SPEECHBUBBLE_QUESTTRADER)
// Use with player:addMapMark
registerEnum(MAPMARK_TICK)
registerEnum(MAPMARK_QUESTION)
registerEnum(MAPMARK_EXCLAMATION)
registerEnum(MAPMARK_STAR)
registerEnum(MAPMARK_CROSS)
registerEnum(MAPMARK_TEMPLE)
registerEnum(MAPMARK_KISS)
registerEnum(MAPMARK_SHOVEL)
registerEnum(MAPMARK_SWORD)
registerEnum(MAPMARK_FLAG)
registerEnum(MAPMARK_LOCK)
registerEnum(MAPMARK_BAG)
registerEnum(MAPMARK_SKULL)
registerEnum(MAPMARK_DOLLAR)
registerEnum(MAPMARK_REDNORTH)
registerEnum(MAPMARK_REDSOUTH)
registerEnum(MAPMARK_REDEAST)
registerEnum(MAPMARK_REDWEST)
registerEnum(MAPMARK_GREENNORTH)
registerEnum(MAPMARK_GREENSOUTH)
// Use with Game.getReturnMessage
registerEnum(RETURNVALUE_NOERROR)
registerEnum(RETURNVALUE_NOTPOSSIBLE)
registerEnum(RETURNVALUE_NOTENOUGHROOM)
registerEnum(RETURNVALUE_PLAYERISPZLOCKED)
registerEnum(RETURNVALUE_PLAYERISNOTINVITED)
registerEnum(RETURNVALUE_CANNOTTHROW)
registerEnum(RETURNVALUE_THEREISNOWAY)
registerEnum(RETURNVALUE_DESTINATIONOUTOFREACH)
registerEnum(RETURNVALUE_CREATUREBLOCK)
registerEnum(RETURNVALUE_NOTMOVEABLE)
registerEnum(RETURNVALUE_DROPTWOHANDEDITEM)
registerEnum(RETURNVALUE_BOTHHANDSNEEDTOBEFREE)
registerEnum(RETURNVALUE_CANONLYUSEONEWEAPON)
registerEnum(RETURNVALUE_NEEDEXCHANGE)
registerEnum(RETURNVALUE_CANNOTBEDRESSED)
registerEnum(RETURNVALUE_PUTTHISOBJECTINYOURHAND)
registerEnum(RETURNVALUE_PUTTHISOBJECTINBOTHHANDS)
registerEnum(RETURNVALUE_TOOFARAWAY)
registerEnum(RETURNVALUE_FIRSTGODOWNSTAIRS)
registerEnum(RETURNVALUE_FIRSTGOUPSTAIRS)
registerEnum(RETURNVALUE_CONTAINERNOTENOUGHROOM)
registerEnum(RETURNVALUE_NOTENOUGHCAPACITY)
registerEnum(RETURNVALUE_CANNOTPICKUP)
registerEnum(RETURNVALUE_THISISIMPOSSIBLE)
registerEnum(RETURNVALUE_DEPOTISFULL)
registerEnum(RETURNVALUE_CREATUREDOESNOTEXIST)
registerEnum(RETURNVALUE_CANNOTUSETHISOBJECT)
registerEnum(RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE)
registerEnum(RETURNVALUE_NOTREQUIREDLEVELTOUSERUNE)
registerEnum(RETURNVALUE_YOUAREALREADYTRADING)
registerEnum(RETURNVALUE_THISPLAYERISALREADYTRADING)
registerEnum(RETURNVALUE_YOUMAYNOTLOGOUTDURINGAFIGHT)
registerEnum(RETURNVALUE_DIRECTPLAYERSHOOT)
registerEnum(RETURNVALUE_NOTENOUGHLEVEL)
registerEnum(RETURNVALUE_NOTENOUGHMAGICLEVEL)
registerEnum(RETURNVALUE_NOTENOUGHMANA)
registerEnum(RETURNVALUE_NOTENOUGHSOUL)
registerEnum(RETURNVALUE_YOUAREEXHAUSTED)
registerEnum(RETURNVALUE_PLAYERISNOTREACHABLE)
registerEnum(RETURNVALUE_CANONLYUSETHISRUNEONCREATURES)
registerEnum(RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE)
registerEnum(RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER)
registerEnum(RETURNVALUE_YOUMAYNOTATTACKAPERSONINPROTECTIONZONE)
registerEnum(RETURNVALUE_YOUMAYNOTATTACKAPERSONWHILEINPROTECTIONZONE)
registerEnum(RETURNVALUE_YOUMAYNOTATTACKTHISCREATURE)
registerEnum(RETURNVALUE_YOUCANONLYUSEITONCREATURES)
registerEnum(RETURNVALUE_CREATUREISNOTREACHABLE)
registerEnum(RETURNVALUE_TURNSECUREMODETOATTACKUNMARKEDPLAYERS)
registerEnum(RETURNVALUE_YOUNEEDPREMIUMACCOUNT)
registerEnum(RETURNVALUE_YOUNEEDTOLEARNTHISSPELL)
registerEnum(RETURNVALUE_YOURVOCATIONCANNOTUSETHISSPELL)
registerEnum(RETURNVALUE_YOUNEEDAWEAPONTOUSETHISSPELL)
registerEnum(RETURNVALUE_PLAYERISPZLOCKEDLEAVEPVPZONE)
registerEnum(RETURNVALUE_PLAYERISPZLOCKEDENTERPVPZONE)
registerEnum(RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE)
registerEnum(RETURNVALUE_YOUCANNOTLOGOUTHERE)
registerEnum(RETURNVALUE_YOUNEEDAMAGICITEMTOCASTSPELL)
registerEnum(RETURNVALUE_CANNOTCONJUREITEMHERE)
registerEnum(RETURNVALUE_YOUNEEDTOSPLITYOURSPEARS)
registerEnum(RETURNVALUE_NAMEISTOOAMBIGUOUS)
registerEnum(RETURNVALUE_CANONLYUSEONESHIELD)
registerEnum(RETURNVALUE_NOPARTYMEMBERSINRANGE)
registerEnum(RETURNVALUE_YOUARENOTTHEOWNER)
// _G
registerGlobalVariable("INDEX_WHEREEVER", INDEX_WHEREEVER);
registerGlobalBoolean("VIRTUAL_PARENT", true);
registerGlobalMethod("isType", LuaScriptInterface::luaIsType);
registerGlobalMethod("rawgetmetatable", LuaScriptInterface::luaRawGetMetatable);
// configKeys
registerTable("configKeys");
registerEnumIn("configKeys", ConfigManager::ALLOW_CHANGEOUTFIT)
registerEnumIn("configKeys", ConfigManager::ONE_PLAYER_ON_ACCOUNT)
registerEnumIn("configKeys", ConfigManager::AIMBOT_HOTKEY_ENABLED)
registerEnumIn("configKeys", ConfigManager::REMOVE_RUNE_CHARGES)
registerEnumIn("configKeys", ConfigManager::EXPERIENCE_FROM_PLAYERS)
registerEnumIn("configKeys", ConfigManager::FREE_PREMIUM)
registerEnumIn("configKeys", ConfigManager::REPLACE_KICK_ON_LOGIN)
registerEnumIn("configKeys", ConfigManager::ALLOW_CLONES)
registerEnumIn("configKeys", ConfigManager::BIND_ONLY_GLOBAL_ADDRESS)
registerEnumIn("configKeys", ConfigManager::OPTIMIZE_DATABASE)
registerEnumIn("configKeys", ConfigManager::MARKET_PREMIUM)
registerEnumIn("configKeys", ConfigManager::EMOTE_SPELLS)
registerEnumIn("configKeys", ConfigManager::STAMINA_SYSTEM)
registerEnumIn("configKeys", ConfigManager::WARN_UNSAFE_SCRIPTS)
registerEnumIn("configKeys", ConfigManager::CONVERT_UNSAFE_SCRIPTS)
registerEnumIn("configKeys", ConfigManager::CLASSIC_EQUIPMENT_SLOTS)
registerEnumIn("configKeys", ConfigManager::MAP_NAME)
registerEnumIn("configKeys", ConfigManager::HOUSE_RENT_PERIOD)
registerEnumIn("configKeys", ConfigManager::SERVER_NAME)
registerEnumIn("configKeys", ConfigManager::OWNER_NAME)
registerEnumIn("configKeys", ConfigManager::OWNER_EMAIL)
registerEnumIn("configKeys", ConfigManager::URL)
registerEnumIn("configKeys", ConfigManager::LOCATION)
registerEnumIn("configKeys", ConfigManager::IP)
registerEnumIn("configKeys", ConfigManager::MOTD)
registerEnumIn("configKeys", ConfigManager::WORLD_TYPE)
registerEnumIn("configKeys", ConfigManager::MYSQL_HOST)
registerEnumIn("configKeys", ConfigManager::MYSQL_USER)
registerEnumIn("configKeys", ConfigManager::MYSQL_PASS)
registerEnumIn("configKeys", ConfigManager::MYSQL_DB)
registerEnumIn("configKeys", ConfigManager::MYSQL_SOCK)
registerEnumIn("configKeys", ConfigManager::DEFAULT_PRIORITY)
registerEnumIn("configKeys", ConfigManager::MAP_AUTHOR)
registerEnumIn("configKeys", ConfigManager::SQL_PORT)
registerEnumIn("configKeys", ConfigManager::MAX_PLAYERS)
registerEnumIn("configKeys", ConfigManager::PZ_LOCKED)
registerEnumIn("configKeys", ConfigManager::DEFAULT_DESPAWNRANGE)
registerEnumIn("configKeys", ConfigManager::DEFAULT_DESPAWNRADIUS)
registerEnumIn("configKeys", ConfigManager::RATE_EXPERIENCE)
registerEnumIn("configKeys", ConfigManager::RATE_SKILL)
registerEnumIn("configKeys", ConfigManager::RATE_LOOT)
registerEnumIn("configKeys", ConfigManager::RATE_MAGIC)
registerEnumIn("configKeys", ConfigManager::RATE_SPAWN)
registerEnumIn("configKeys", ConfigManager::HOUSE_PRICE)
registerEnumIn("configKeys", ConfigManager::KILLS_TO_RED)
registerEnumIn("configKeys", ConfigManager::KILLS_TO_BLACK)
registerEnumIn("configKeys", ConfigManager::MAX_MESSAGEBUFFER)
registerEnumIn("configKeys", ConfigManager::ACTIONS_DELAY_INTERVAL)
registerEnumIn("configKeys", ConfigManager::EX_ACTIONS_DELAY_INTERVAL)
registerEnumIn("configKeys", ConfigManager::KICK_AFTER_MINUTES)
registerEnumIn("configKeys", ConfigManager::PROTECTION_LEVEL)
registerEnumIn("configKeys", ConfigManager::DEATH_LOSE_PERCENT)
registerEnumIn("configKeys", ConfigManager::STATUSQUERY_TIMEOUT)
registerEnumIn("configKeys", ConfigManager::FRAG_TIME)
registerEnumIn("configKeys", ConfigManager::WHITE_SKULL_TIME)
registerEnumIn("configKeys", ConfigManager::GAME_PORT)
registerEnumIn("configKeys", ConfigManager::LOGIN_PORT)
registerEnumIn("configKeys", ConfigManager::STATUS_PORT)
registerEnumIn("configKeys", ConfigManager::STAIRHOP_DELAY)
registerEnumIn("configKeys", ConfigManager::MARKET_OFFER_DURATION)
registerEnumIn("configKeys", ConfigManager::CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES)
registerEnumIn("configKeys", ConfigManager::MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER)
registerEnumIn("configKeys", ConfigManager::EXP_FROM_PLAYERS_LEVEL_RANGE)
registerEnumIn("configKeys", ConfigManager::MAX_PACKETS_PER_SECOND)
// os
registerMethod("os", "mtime", LuaScriptInterface::luaSystemTime);
// table
registerMethod("table", "create", LuaScriptInterface::luaTableCreate);
// Game
registerTable("Game");
registerMethod("Game", "getSpectators", LuaScriptInterface::luaGameGetSpectators);
registerMethod("Game", "getPlayers", LuaScriptInterface::luaGameGetPlayers);
registerMethod("Game", "loadMap", LuaScriptInterface::luaGameLoadMap);
registerMethod("Game", "getExperienceStage", LuaScriptInterface::luaGameGetExperienceStage);
registerMethod("Game", "getMonsterCount", LuaScriptInterface::luaGameGetMonsterCount);
registerMethod("Game", "getPlayerCount", LuaScriptInterface::luaGameGetPlayerCount);
registerMethod("Game", "getNpcCount", LuaScriptInterface::luaGameGetNpcCount);
registerMethod("Game", "getTowns", LuaScriptInterface::luaGameGetTowns);
registerMethod("Game", "getHouses", LuaScriptInterface::luaGameGetHouses);
registerMethod("Game", "getGameState", LuaScriptInterface::luaGameGetGameState);
registerMethod("Game", "setGameState", LuaScriptInterface::luaGameSetGameState);
registerMethod("Game", "getWorldType", LuaScriptInterface::luaGameGetWorldType);
registerMethod("Game", "setWorldType", LuaScriptInterface::luaGameSetWorldType);
registerMethod("Game", "getReturnMessage", LuaScriptInterface::luaGameGetReturnMessage);
registerMethod("Game", "createItem", LuaScriptInterface::luaGameCreateItem);
registerMethod("Game", "createContainer", LuaScriptInterface::luaGameCreateContainer);
registerMethod("Game", "createMonster", LuaScriptInterface::luaGameCreateMonster);
registerMethod("Game", "createNpc", LuaScriptInterface::luaGameCreateNpc);
registerMethod("Game", "createTile", LuaScriptInterface::luaGameCreateTile);
registerMethod("Game", "startRaid", LuaScriptInterface::luaGameStartRaid);
// Variant
registerClass("Variant", "", LuaScriptInterface::luaVariantCreate);
registerMethod("Variant", "getNumber", LuaScriptInterface::luaVariantGetNumber);
registerMethod("Variant", "getString", LuaScriptInterface::luaVariantGetString);
registerMethod("Variant", "getPosition", LuaScriptInterface::luaVariantGetPosition);
// Position
registerClass("Position", "", LuaScriptInterface::luaPositionCreate);
registerMetaMethod("Position", "__add", LuaScriptInterface::luaPositionAdd);
registerMetaMethod("Position", "__sub", LuaScriptInterface::luaPositionSub);
registerMetaMethod("Position", "__eq", LuaScriptInterface::luaPositionCompare);
registerMethod("Position", "getDistance", LuaScriptInterface::luaPositionGetDistance);
registerMethod("Position", "isSightClear", LuaScriptInterface::luaPositionIsSightClear);
registerMethod("Position", "sendMagicEffect", LuaScriptInterface::luaPositionSendMagicEffect);
registerMethod("Position", "sendDistanceEffect", LuaScriptInterface::luaPositionSendDistanceEffect);
// Tile
registerClass("Tile", "", LuaScriptInterface::luaTileCreate);
registerMetaMethod("Tile", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Tile", "getPosition", LuaScriptInterface::luaTileGetPosition);
registerMethod("Tile", "getGround", LuaScriptInterface::luaTileGetGround);
registerMethod("Tile", "getThing", LuaScriptInterface::luaTileGetThing);
registerMethod("Tile", "getThingCount", LuaScriptInterface::luaTileGetThingCount);
registerMethod("Tile", "getTopVisibleThing", LuaScriptInterface::luaTileGetTopVisibleThing);
registerMethod("Tile", "getTopTopItem", LuaScriptInterface::luaTileGetTopTopItem);
registerMethod("Tile", "getTopDownItem", LuaScriptInterface::luaTileGetTopDownItem);
registerMethod("Tile", "getFieldItem", LuaScriptInterface::luaTileGetFieldItem);
registerMethod("Tile", "getItemById", LuaScriptInterface::luaTileGetItemById);
registerMethod("Tile", "getItemByType", LuaScriptInterface::luaTileGetItemByType);
registerMethod("Tile", "getItemByTopOrder", LuaScriptInterface::luaTileGetItemByTopOrder);
registerMethod("Tile", "getItemCountById", LuaScriptInterface::luaTileGetItemCountById);
registerMethod("Tile", "getBottomCreature", LuaScriptInterface::luaTileGetBottomCreature);
registerMethod("Tile", "getTopCreature", LuaScriptInterface::luaTileGetTopCreature);
registerMethod("Tile", "getBottomVisibleCreature", LuaScriptInterface::luaTileGetBottomVisibleCreature);
registerMethod("Tile", "getTopVisibleCreature", LuaScriptInterface::luaTileGetTopVisibleCreature);
registerMethod("Tile", "getItems", LuaScriptInterface::luaTileGetItems);
registerMethod("Tile", "getItemCount", LuaScriptInterface::luaTileGetItemCount);
registerMethod("Tile", "getDownItemCount", LuaScriptInterface::luaTileGetDownItemCount);
registerMethod("Tile", "getTopItemCount", LuaScriptInterface::luaTileGetTopItemCount);
registerMethod("Tile", "getCreatures", LuaScriptInterface::luaTileGetCreatures);
registerMethod("Tile", "getCreatureCount", LuaScriptInterface::luaTileGetCreatureCount);
registerMethod("Tile", "getThingIndex", LuaScriptInterface::luaTileGetThingIndex);
registerMethod("Tile", "hasProperty", LuaScriptInterface::luaTileHasProperty);
registerMethod("Tile", "hasFlag", LuaScriptInterface::luaTileHasFlag);
registerMethod("Tile", "queryAdd", LuaScriptInterface::luaTileQueryAdd);
registerMethod("Tile", "getHouse", LuaScriptInterface::luaTileGetHouse);
// NetworkMessage
registerClass("NetworkMessage", "", LuaScriptInterface::luaNetworkMessageCreate);
registerMetaMethod("NetworkMessage", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMetaMethod("NetworkMessage", "__gc", LuaScriptInterface::luaNetworkMessageDelete);
registerMethod("NetworkMessage", "delete", LuaScriptInterface::luaNetworkMessageDelete);
registerMethod("NetworkMessage", "getByte", LuaScriptInterface::luaNetworkMessageGetByte);
registerMethod("NetworkMessage", "getU16", LuaScriptInterface::luaNetworkMessageGetU16);
registerMethod("NetworkMessage", "getU32", LuaScriptInterface::luaNetworkMessageGetU32);
registerMethod("NetworkMessage", "getU64", LuaScriptInterface::luaNetworkMessageGetU64);
registerMethod("NetworkMessage", "getString", LuaScriptInterface::luaNetworkMessageGetString);
registerMethod("NetworkMessage", "getPosition", LuaScriptInterface::luaNetworkMessageGetPosition);
registerMethod("NetworkMessage", "addByte", LuaScriptInterface::luaNetworkMessageAddByte);
registerMethod("NetworkMessage", "addU16", LuaScriptInterface::luaNetworkMessageAddU16);
registerMethod("NetworkMessage", "addU32", LuaScriptInterface::luaNetworkMessageAddU32);
registerMethod("NetworkMessage", "addU64", LuaScriptInterface::luaNetworkMessageAddU64);
registerMethod("NetworkMessage", "addString", LuaScriptInterface::luaNetworkMessageAddString);
registerMethod("NetworkMessage", "addPosition", LuaScriptInterface::luaNetworkMessageAddPosition);
registerMethod("NetworkMessage", "addDouble", LuaScriptInterface::luaNetworkMessageAddDouble);
registerMethod("NetworkMessage", "addItem", LuaScriptInterface::luaNetworkMessageAddItem);
registerMethod("NetworkMessage", "addItemId", LuaScriptInterface::luaNetworkMessageAddItemId);
registerMethod("NetworkMessage", "reset", LuaScriptInterface::luaNetworkMessageReset);
registerMethod("NetworkMessage", "skipBytes", LuaScriptInterface::luaNetworkMessageSkipBytes);
registerMethod("NetworkMessage", "sendToPlayer", LuaScriptInterface::luaNetworkMessageSendToPlayer);
// ModalWindow
registerClass("ModalWindow", "", LuaScriptInterface::luaModalWindowCreate);
registerMetaMethod("ModalWindow", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMetaMethod("ModalWindow", "__gc", LuaScriptInterface::luaModalWindowDelete);
registerMethod("ModalWindow", "delete", LuaScriptInterface::luaModalWindowDelete);
registerMethod("ModalWindow", "getId", LuaScriptInterface::luaModalWindowGetId);
registerMethod("ModalWindow", "getTitle", LuaScriptInterface::luaModalWindowGetTitle);
registerMethod("ModalWindow", "getMessage", LuaScriptInterface::luaModalWindowGetMessage);
registerMethod("ModalWindow", "setTitle", LuaScriptInterface::luaModalWindowSetTitle);
registerMethod("ModalWindow", "setMessage", LuaScriptInterface::luaModalWindowSetMessage);
registerMethod("ModalWindow", "getButtonCount", LuaScriptInterface::luaModalWindowGetButtonCount);
registerMethod("ModalWindow", "getChoiceCount", LuaScriptInterface::luaModalWindowGetChoiceCount);
registerMethod("ModalWindow", "addButton", LuaScriptInterface::luaModalWindowAddButton);
registerMethod("ModalWindow", "addChoice", LuaScriptInterface::luaModalWindowAddChoice);
registerMethod("ModalWindow", "getDefaultEnterButton", LuaScriptInterface::luaModalWindowGetDefaultEnterButton);
registerMethod("ModalWindow", "setDefaultEnterButton", LuaScriptInterface::luaModalWindowSetDefaultEnterButton);
registerMethod("ModalWindow", "getDefaultEscapeButton", LuaScriptInterface::luaModalWindowGetDefaultEscapeButton);
registerMethod("ModalWindow", "setDefaultEscapeButton", LuaScriptInterface::luaModalWindowSetDefaultEscapeButton);
registerMethod("ModalWindow", "hasPriority", LuaScriptInterface::luaModalWindowHasPriority);
registerMethod("ModalWindow", "setPriority", LuaScriptInterface::luaModalWindowSetPriority);
registerMethod("ModalWindow", "sendToPlayer", LuaScriptInterface::luaModalWindowSendToPlayer);
// Item
registerClass("Item", "", LuaScriptInterface::luaItemCreate);
registerMetaMethod("Item", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Item", "isItem", LuaScriptInterface::luaItemIsItem);
registerMethod("Item", "getParent", LuaScriptInterface::luaItemGetParent);
registerMethod("Item", "getTopParent", LuaScriptInterface::luaItemGetTopParent);
registerMethod("Item", "getId", LuaScriptInterface::luaItemGetId);
registerMethod("Item", "clone", LuaScriptInterface::luaItemClone);
registerMethod("Item", "split", LuaScriptInterface::luaItemSplit);
registerMethod("Item", "remove", LuaScriptInterface::luaItemRemove);
registerMethod("Item", "getUniqueId", LuaScriptInterface::luaItemGetUniqueId);
registerMethod("Item", "getActionId", LuaScriptInterface::luaItemGetActionId);
registerMethod("Item", "setActionId", LuaScriptInterface::luaItemSetActionId);
registerMethod("Item", "getCount", LuaScriptInterface::luaItemGetCount);
registerMethod("Item", "getCharges", LuaScriptInterface::luaItemGetCharges);
registerMethod("Item", "getFluidType", LuaScriptInterface::luaItemGetFluidType);
registerMethod("Item", "getWeight", LuaScriptInterface::luaItemGetWeight);
registerMethod("Item", "getSubType", LuaScriptInterface::luaItemGetSubType);
registerMethod("Item", "getName", LuaScriptInterface::luaItemGetName);
registerMethod("Item", "getPluralName", LuaScriptInterface::luaItemGetPluralName);
registerMethod("Item", "getArticle", LuaScriptInterface::luaItemGetArticle);
registerMethod("Item", "getPosition", LuaScriptInterface::luaItemGetPosition);
registerMethod("Item", "getTile", LuaScriptInterface::luaItemGetTile);
registerMethod("Item", "hasAttribute", LuaScriptInterface::luaItemHasAttribute);
registerMethod("Item", "getAttribute", LuaScriptInterface::luaItemGetAttribute);
registerMethod("Item", "setAttribute", LuaScriptInterface::luaItemSetAttribute);
registerMethod("Item", "removeAttribute", LuaScriptInterface::luaItemRemoveAttribute);
registerMethod("Item", "moveTo", LuaScriptInterface::luaItemMoveTo);
registerMethod("Item", "transform", LuaScriptInterface::luaItemTransform);
registerMethod("Item", "decay", LuaScriptInterface::luaItemDecay);
registerMethod("Item", "getDescription", LuaScriptInterface::luaItemGetDescription);
registerMethod("Item", "hasProperty", LuaScriptInterface::luaItemHasProperty);
// Container
registerClass("Container", "Item", LuaScriptInterface::luaContainerCreate);
registerMetaMethod("Container", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Container", "getSize", LuaScriptInterface::luaContainerGetSize);
registerMethod("Container", "getCapacity", LuaScriptInterface::luaContainerGetCapacity);
registerMethod("Container", "getEmptySlots", LuaScriptInterface::luaContainerGetEmptySlots);
registerMethod("Container", "getItemHoldingCount", LuaScriptInterface::luaContainerGetItemHoldingCount);
registerMethod("Container", "getItemCountById", LuaScriptInterface::luaContainerGetItemCountById);
registerMethod("Container", "getItem", LuaScriptInterface::luaContainerGetItem);
registerMethod("Container", "hasItem", LuaScriptInterface::luaContainerHasItem);
registerMethod("Container", "addItem", LuaScriptInterface::luaContainerAddItem);
registerMethod("Container", "addItemEx", LuaScriptInterface::luaContainerAddItemEx);
// Teleport
registerClass("Teleport", "Item", LuaScriptInterface::luaTeleportCreate);
registerMetaMethod("Teleport", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Teleport", "getDestination", LuaScriptInterface::luaTeleportGetDestination);
registerMethod("Teleport", "setDestination", LuaScriptInterface::luaTeleportSetDestination);
// Creature
registerClass("Creature", "", LuaScriptInterface::luaCreatureCreate);
registerMetaMethod("Creature", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Creature", "getEvents", LuaScriptInterface::luaCreatureGetEvents);
registerMethod("Creature", "registerEvent", LuaScriptInterface::luaCreatureRegisterEvent);
registerMethod("Creature", "unregisterEvent", LuaScriptInterface::luaCreatureUnregisterEvent);
registerMethod("Creature", "isRemoved", LuaScriptInterface::luaCreatureIsRemoved);
registerMethod("Creature", "isCreature", LuaScriptInterface::luaCreatureIsCreature);
registerMethod("Creature", "isInGhostMode", LuaScriptInterface::luaCreatureIsInGhostMode);
registerMethod("Creature", "isHealthHidden", LuaScriptInterface::luaCreatureIsHealthHidden);
registerMethod("Creature", "canSee", LuaScriptInterface::luaCreatureCanSee);
registerMethod("Creature", "canSeeCreature", LuaScriptInterface::luaCreatureCanSeeCreature);
registerMethod("Creature", "getParent", LuaScriptInterface::luaCreatureGetParent);
registerMethod("Creature", "getId", LuaScriptInterface::luaCreatureGetId);
registerMethod("Creature", "getName", LuaScriptInterface::luaCreatureGetName);
registerMethod("Creature", "getTarget", LuaScriptInterface::luaCreatureGetTarget);
registerMethod("Creature", "setTarget", LuaScriptInterface::luaCreatureSetTarget);
registerMethod("Creature", "getFollowCreature", LuaScriptInterface::luaCreatureGetFollowCreature);
registerMethod("Creature", "setFollowCreature", LuaScriptInterface::luaCreatureSetFollowCreature);
registerMethod("Creature", "getMaster", LuaScriptInterface::luaCreatureGetMaster);
registerMethod("Creature", "setMaster", LuaScriptInterface::luaCreatureSetMaster);
registerMethod("Creature", "getLight", LuaScriptInterface::luaCreatureGetLight);
registerMethod("Creature", "setLight", LuaScriptInterface::luaCreatureSetLight);
registerMethod("Creature", "getSpeed", LuaScriptInterface::luaCreatureGetSpeed);
registerMethod("Creature", "getBaseSpeed", LuaScriptInterface::luaCreatureGetBaseSpeed);
registerMethod("Creature", "changeSpeed", LuaScriptInterface::luaCreatureChangeSpeed);
registerMethod("Creature", "setDropLoot", LuaScriptInterface::luaCreatureSetDropLoot);
registerMethod("Creature", "getPosition", LuaScriptInterface::luaCreatureGetPosition);
registerMethod("Creature", "getTile", LuaScriptInterface::luaCreatureGetTile);
registerMethod("Creature", "getDirection", LuaScriptInterface::luaCreatureGetDirection);
registerMethod("Creature", "setDirection", LuaScriptInterface::luaCreatureSetDirection);
registerMethod("Creature", "getHealth", LuaScriptInterface::luaCreatureGetHealth);
registerMethod("Creature", "addHealth", LuaScriptInterface::luaCreatureAddHealth);
registerMethod("Creature", "getMaxHealth", LuaScriptInterface::luaCreatureGetMaxHealth);
registerMethod("Creature", "setMaxHealth", LuaScriptInterface::luaCreatureSetMaxHealth);
registerMethod("Creature", "setHiddenHealth", LuaScriptInterface::luaCreatureSetHiddenHealth);
registerMethod("Creature", "getMana", LuaScriptInterface::luaCreatureGetMana);
registerMethod("Creature", "addMana", LuaScriptInterface::luaCreatureAddMana);
registerMethod("Creature", "getMaxMana", LuaScriptInterface::luaCreatureGetMaxMana);
registerMethod("Creature", "getSkull", LuaScriptInterface::luaCreatureGetSkull);
registerMethod("Creature", "setSkull", LuaScriptInterface::luaCreatureSetSkull);
registerMethod("Creature", "getOutfit", LuaScriptInterface::luaCreatureGetOutfit);
registerMethod("Creature", "setOutfit", LuaScriptInterface::luaCreatureSetOutfit);
registerMethod("Creature", "getCondition", LuaScriptInterface::luaCreatureGetCondition);
registerMethod("Creature", "addCondition", LuaScriptInterface::luaCreatureAddCondition);
registerMethod("Creature", "removeCondition", LuaScriptInterface::luaCreatureRemoveCondition);
registerMethod("Creature", "remove", LuaScriptInterface::luaCreatureRemove);
registerMethod("Creature", "teleportTo", LuaScriptInterface::luaCreatureTeleportTo);
registerMethod("Creature", "say", LuaScriptInterface::luaCreatureSay);
registerMethod("Creature", "getDamageMap", LuaScriptInterface::luaCreatureGetDamageMap);
registerMethod("Creature", "getSummons", LuaScriptInterface::luaCreatureGetSummons);
registerMethod("Creature", "getDescription", LuaScriptInterface::luaCreatureGetDescription);
registerMethod("Creature", "getPathTo", LuaScriptInterface::luaCreatureGetPathTo);
// Player
registerClass("Player", "Creature", LuaScriptInterface::luaPlayerCreate);
registerMetaMethod("Player", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Player", "isPlayer", LuaScriptInterface::luaPlayerIsPlayer);
registerMethod("Player", "getGuid", LuaScriptInterface::luaPlayerGetGuid);
registerMethod("Player", "getIp", LuaScriptInterface::luaPlayerGetIp);
registerMethod("Player", "getAccountId", LuaScriptInterface::luaPlayerGetAccountId);
registerMethod("Player", "getLastLoginSaved", LuaScriptInterface::luaPlayerGetLastLoginSaved);
registerMethod("Player", "getLastLogout", LuaScriptInterface::luaPlayerGetLastLogout);
registerMethod("Player", "getAccountType", LuaScriptInterface::luaPlayerGetAccountType);
registerMethod("Player", "setAccountType", LuaScriptInterface::luaPlayerSetAccountType);
registerMethod("Player", "getCapacity", LuaScriptInterface::luaPlayerGetCapacity);
registerMethod("Player", "setCapacity", LuaScriptInterface::luaPlayerSetCapacity);
registerMethod("Player", "getFreeCapacity", LuaScriptInterface::luaPlayerGetFreeCapacity);
registerMethod("Player", "getDepotChest", LuaScriptInterface::luaPlayerGetDepotChest);
registerMethod("Player", "getInbox", LuaScriptInterface::luaPlayerGetInbox);
registerMethod("Player", "getSkullTime", LuaScriptInterface::luaPlayerGetSkullTime);
registerMethod("Player", "setSkullTime", LuaScriptInterface::luaPlayerSetSkullTime);
registerMethod("Player", "getDeathPenalty", LuaScriptInterface::luaPlayerGetDeathPenalty);
registerMethod("Player", "getExperience", LuaScriptInterface::luaPlayerGetExperience);
registerMethod("Player", "addExperience", LuaScriptInterface::luaPlayerAddExperience);
registerMethod("Player", "removeExperience", LuaScriptInterface::luaPlayerRemoveExperience);
registerMethod("Player", "getLevel", LuaScriptInterface::luaPlayerGetLevel);
registerMethod("Player", "getMagicLevel", LuaScriptInterface::luaPlayerGetMagicLevel);
registerMethod("Player", "getBaseMagicLevel", LuaScriptInterface::luaPlayerGetBaseMagicLevel);
registerMethod("Player", "setMaxMana", LuaScriptInterface::luaPlayerSetMaxMana);
registerMethod("Player", "getManaSpent", LuaScriptInterface::luaPlayerGetManaSpent);
registerMethod("Player", "addManaSpent", LuaScriptInterface::luaPlayerAddManaSpent);
registerMethod("Player", "getBaseMaxHealth", LuaScriptInterface::luaPlayerGetBaseMaxHealth);
registerMethod("Player", "getBaseMaxMana", LuaScriptInterface::luaPlayerGetBaseMaxMana);
registerMethod("Player", "getSkillLevel", LuaScriptInterface::luaPlayerGetSkillLevel);
registerMethod("Player", "getEffectiveSkillLevel", LuaScriptInterface::luaPlayerGetEffectiveSkillLevel);
registerMethod("Player", "getSkillPercent", LuaScriptInterface::luaPlayerGetSkillPercent);
registerMethod("Player", "getSkillTries", LuaScriptInterface::luaPlayerGetSkillTries);
registerMethod("Player", "addSkillTries", LuaScriptInterface::luaPlayerAddSkillTries);
registerMethod("Player", "addOfflineTrainingTime", LuaScriptInterface::luaPlayerAddOfflineTrainingTime);
registerMethod("Player", "getOfflineTrainingTime", LuaScriptInterface::luaPlayerGetOfflineTrainingTime);
registerMethod("Player", "removeOfflineTrainingTime", LuaScriptInterface::luaPlayerRemoveOfflineTrainingTime);
registerMethod("Player", "addOfflineTrainingTries", LuaScriptInterface::luaPlayerAddOfflineTrainingTries);
registerMethod("Player", "getOfflineTrainingSkill", LuaScriptInterface::luaPlayerGetOfflineTrainingSkill);
registerMethod("Player", "setOfflineTrainingSkill", LuaScriptInterface::luaPlayerSetOfflineTrainingSkill);
registerMethod("Player", "getItemCount", LuaScriptInterface::luaPlayerGetItemCount);
registerMethod("Player", "getItemById", LuaScriptInterface::luaPlayerGetItemById);
registerMethod("Player", "getVocation", LuaScriptInterface::luaPlayerGetVocation);
registerMethod("Player", "setVocation", LuaScriptInterface::luaPlayerSetVocation);
registerMethod("Player", "getSex", LuaScriptInterface::luaPlayerGetSex);
registerMethod("Player", "setSex", LuaScriptInterface::luaPlayerSetSex);
registerMethod("Player", "getTown", LuaScriptInterface::luaPlayerGetTown);
registerMethod("Player", "setTown", LuaScriptInterface::luaPlayerSetTown);
registerMethod("Player", "getGuild", LuaScriptInterface::luaPlayerGetGuild);
registerMethod("Player", "setGuild", LuaScriptInterface::luaPlayerSetGuild);
registerMethod("Player", "getGuildLevel", LuaScriptInterface::luaPlayerGetGuildLevel);
registerMethod("Player", "setGuildLevel", LuaScriptInterface::luaPlayerSetGuildLevel);
registerMethod("Player", "getGuildNick", LuaScriptInterface::luaPlayerGetGuildNick);
registerMethod("Player", "setGuildNick", LuaScriptInterface::luaPlayerSetGuildNick);
registerMethod("Player", "getGroup", LuaScriptInterface::luaPlayerGetGroup);
registerMethod("Player", "setGroup", LuaScriptInterface::luaPlayerSetGroup);
registerMethod("Player", "getStamina", LuaScriptInterface::luaPlayerGetStamina);
registerMethod("Player", "setStamina", LuaScriptInterface::luaPlayerSetStamina);
registerMethod("Player", "getSoul", LuaScriptInterface::luaPlayerGetSoul);
registerMethod("Player", "addSoul", LuaScriptInterface::luaPlayerAddSoul);
registerMethod("Player", "getMaxSoul", LuaScriptInterface::luaPlayerGetMaxSoul);
registerMethod("Player", "getBankBalance", LuaScriptInterface::luaPlayerGetBankBalance);
registerMethod("Player", "setBankBalance", LuaScriptInterface::luaPlayerSetBankBalance);
registerMethod("Player", "getStorageValue", LuaScriptInterface::luaPlayerGetStorageValue);
registerMethod("Player", "setStorageValue", LuaScriptInterface::luaPlayerSetStorageValue);
registerMethod("Player", "addItem", LuaScriptInterface::luaPlayerAddItem);
registerMethod("Player", "addItemEx", LuaScriptInterface::luaPlayerAddItemEx);
registerMethod("Player", "removeItem", LuaScriptInterface::luaPlayerRemoveItem);
registerMethod("Player", "getMoney", LuaScriptInterface::luaPlayerGetMoney);
registerMethod("Player", "addMoney", LuaScriptInterface::luaPlayerAddMoney);
registerMethod("Player", "removeMoney", LuaScriptInterface::luaPlayerRemoveMoney);
registerMethod("Player", "showTextDialog", LuaScriptInterface::luaPlayerShowTextDialog);
registerMethod("Player", "sendTextMessage", LuaScriptInterface::luaPlayerSendTextMessage);
registerMethod("Player", "sendChannelMessage", LuaScriptInterface::luaPlayerSendChannelMessage);
registerMethod("Player", "sendPrivateMessage", LuaScriptInterface::luaPlayerSendPrivateMessage);
registerMethod("Player", "channelSay", LuaScriptInterface::luaPlayerChannelSay);
registerMethod("Player", "openChannel", LuaScriptInterface::luaPlayerOpenChannel);
registerMethod("Player", "getSlotItem", LuaScriptInterface::luaPlayerGetSlotItem);
registerMethod("Player", "getParty", LuaScriptInterface::luaPlayerGetParty);
registerMethod("Player", "addOutfit", LuaScriptInterface::luaPlayerAddOutfit);
registerMethod("Player", "addOutfitAddon", LuaScriptInterface::luaPlayerAddOutfitAddon);
registerMethod("Player", "removeOutfit", LuaScriptInterface::luaPlayerRemoveOutfit);
registerMethod("Player", "removeOutfitAddon", LuaScriptInterface::luaPlayerRemoveOutfitAddon);
registerMethod("Player", "hasOutfit", LuaScriptInterface::luaPlayerHasOutfit);
registerMethod("Player", "sendOutfitWindow", LuaScriptInterface::luaPlayerSendOutfitWindow);
registerMethod("Player", "addMount", LuaScriptInterface::luaPlayerAddMount);
registerMethod("Player", "removeMount", LuaScriptInterface::luaPlayerRemoveMount);
registerMethod("Player", "hasMount", LuaScriptInterface::luaPlayerHasMount);
registerMethod("Player", "getPremiumDays", LuaScriptInterface::luaPlayerGetPremiumDays);
registerMethod("Player", "addPremiumDays", LuaScriptInterface::luaPlayerAddPremiumDays);
registerMethod("Player", "removePremiumDays", LuaScriptInterface::luaPlayerRemovePremiumDays);
registerMethod("Player", "hasBlessing", LuaScriptInterface::luaPlayerHasBlessing);
registerMethod("Player", "addBlessing", LuaScriptInterface::luaPlayerAddBlessing);
registerMethod("Player", "removeBlessing", LuaScriptInterface::luaPlayerRemoveBlessing);
registerMethod("Player", "canLearnSpell", LuaScriptInterface::luaPlayerCanLearnSpell);
registerMethod("Player", "learnSpell", LuaScriptInterface::luaPlayerLearnSpell);
registerMethod("Player", "forgetSpell", LuaScriptInterface::luaPlayerForgetSpell);
registerMethod("Player", "hasLearnedSpell", LuaScriptInterface::luaPlayerHasLearnedSpell);
registerMethod("Player", "sendTutorial", LuaScriptInterface::luaPlayerSendTutorial);
registerMethod("Player", "addMapMark", LuaScriptInterface::luaPlayerAddMapMark);
registerMethod("Player", "save", LuaScriptInterface::luaPlayerSave);
registerMethod("Player", "popupFYI", LuaScriptInterface::luaPlayerPopupFYI);
registerMethod("Player", "isPzLocked", LuaScriptInterface::luaPlayerIsPzLocked);
registerMethod("Player", "getClient", LuaScriptInterface::luaPlayerGetClient);
registerMethod("Player", "getHouse", LuaScriptInterface::luaPlayerGetHouse);
registerMethod("Player", "setGhostMode", LuaScriptInterface::luaPlayerSetGhostMode);
registerMethod("Player", "getContainerId", LuaScriptInterface::luaPlayerGetContainerId);
registerMethod("Player", "getContainerById", LuaScriptInterface::luaPlayerGetContainerById);
registerMethod("Player", "getContainerIndex", LuaScriptInterface::luaPlayerGetContainerIndex);
// Monster
registerClass("Monster", "Creature", LuaScriptInterface::luaMonsterCreate);
registerMetaMethod("Monster", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Monster", "isMonster", LuaScriptInterface::luaMonsterIsMonster);
registerMethod("Monster", "getType", LuaScriptInterface::luaMonsterGetType);
registerMethod("Monster", "getSpawnPosition", LuaScriptInterface::luaMonsterGetSpawnPosition);
registerMethod("Monster", "isInSpawnRange", LuaScriptInterface::luaMonsterIsInSpawnRange);
registerMethod("Monster", "isIdle", LuaScriptInterface::luaMonsterIsIdle);
registerMethod("Monster", "setIdle", LuaScriptInterface::luaMonsterSetIdle);
registerMethod("Monster", "isTarget", LuaScriptInterface::luaMonsterIsTarget);
registerMethod("Monster", "isOpponent", LuaScriptInterface::luaMonsterIsOpponent);
registerMethod("Monster", "isFriend", LuaScriptInterface::luaMonsterIsFriend);
registerMethod("Monster", "addFriend", LuaScriptInterface::luaMonsterAddFriend);
registerMethod("Monster", "removeFriend", LuaScriptInterface::luaMonsterRemoveFriend);
registerMethod("Monster", "getFriendList", LuaScriptInterface::luaMonsterGetFriendList);
registerMethod("Monster", "getFriendCount", LuaScriptInterface::luaMonsterGetFriendCount);
registerMethod("Monster", "addTarget", LuaScriptInterface::luaMonsterAddTarget);
registerMethod("Monster", "removeTarget", LuaScriptInterface::luaMonsterRemoveTarget);
registerMethod("Monster", "getTargetList", LuaScriptInterface::luaMonsterGetTargetList);
registerMethod("Monster", "getTargetCount", LuaScriptInterface::luaMonsterGetTargetCount);
registerMethod("Monster", "selectTarget", LuaScriptInterface::luaMonsterSelectTarget);
registerMethod("Monster", "searchTarget", LuaScriptInterface::luaMonsterSearchTarget);
// Npc
registerClass("Npc", "Creature", LuaScriptInterface::luaNpcCreate);
registerMetaMethod("Npc", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Npc", "isNpc", LuaScriptInterface::luaNpcIsNpc);
registerMethod("Npc", "setMasterPos", LuaScriptInterface::luaNpcSetMasterPos);
registerMethod("Npc", "getSpeechBubble", LuaScriptInterface::luaNpcGetSpeechBubble);
registerMethod("Npc", "setSpeechBubble", LuaScriptInterface::luaNpcSetSpeechBubble);
// Guild
registerClass("Guild", "", LuaScriptInterface::luaGuildCreate);
registerMetaMethod("Guild", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Guild", "getId", LuaScriptInterface::luaGuildGetId);
registerMethod("Guild", "getName", LuaScriptInterface::luaGuildGetName);
registerMethod("Guild", "getMembersOnline", LuaScriptInterface::luaGuildGetMembersOnline);
registerMethod("Guild", "addRank", LuaScriptInterface::luaGuildAddRank);
registerMethod("Guild", "getRankById", LuaScriptInterface::luaGuildGetRankById);
registerMethod("Guild", "getRankByLevel", LuaScriptInterface::luaGuildGetRankByLevel);
registerMethod("Guild", "getMotd", LuaScriptInterface::luaGuildGetMotd);
registerMethod("Guild", "setMotd", LuaScriptInterface::luaGuildSetMotd);
// Group
registerClass("Group", "", LuaScriptInterface::luaGroupCreate);
registerMetaMethod("Group", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Group", "getId", LuaScriptInterface::luaGroupGetId);
registerMethod("Group", "getName", LuaScriptInterface::luaGroupGetName);
registerMethod("Group", "getFlags", LuaScriptInterface::luaGroupGetFlags);
registerMethod("Group", "getAccess", LuaScriptInterface::luaGroupGetAccess);
registerMethod("Group", "getMaxDepotItems", LuaScriptInterface::luaGroupGetMaxDepotItems);
registerMethod("Group", "getMaxVipEntries", LuaScriptInterface::luaGroupGetMaxVipEntries);
// Vocation
registerClass("Vocation", "", LuaScriptInterface::luaVocationCreate);
registerMetaMethod("Vocation", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Vocation", "getId", LuaScriptInterface::luaVocationGetId);
registerMethod("Vocation", "getClientId", LuaScriptInterface::luaVocationGetClientId);
registerMethod("Vocation", "getName", LuaScriptInterface::luaVocationGetName);
registerMethod("Vocation", "getDescription", LuaScriptInterface::luaVocationGetDescription);
registerMethod("Vocation", "getRequiredSkillTries", LuaScriptInterface::luaVocationGetRequiredSkillTries);
registerMethod("Vocation", "getRequiredManaSpent", LuaScriptInterface::luaVocationGetRequiredManaSpent);
registerMethod("Vocation", "getCapacityGain", LuaScriptInterface::luaVocationGetCapacityGain);
registerMethod("Vocation", "getHealthGain", LuaScriptInterface::luaVocationGetHealthGain);
registerMethod("Vocation", "getHealthGainTicks", LuaScriptInterface::luaVocationGetHealthGainTicks);
registerMethod("Vocation", "getHealthGainAmount", LuaScriptInterface::luaVocationGetHealthGainAmount);
registerMethod("Vocation", "getManaGain", LuaScriptInterface::luaVocationGetManaGain);
registerMethod("Vocation", "getManaGainTicks", LuaScriptInterface::luaVocationGetManaGainTicks);
registerMethod("Vocation", "getManaGainAmount", LuaScriptInterface::luaVocationGetManaGainAmount);
registerMethod("Vocation", "getMaxSoul", LuaScriptInterface::luaVocationGetMaxSoul);
registerMethod("Vocation", "getSoulGainTicks", LuaScriptInterface::luaVocationGetSoulGainTicks);
registerMethod("Vocation", "getAttackSpeed", LuaScriptInterface::luaVocationGetAttackSpeed);
registerMethod("Vocation", "getBaseSpeed", LuaScriptInterface::luaVocationGetBaseSpeed);
registerMethod("Vocation", "getDemotion", LuaScriptInterface::luaVocationGetDemotion);
registerMethod("Vocation", "getPromotion", LuaScriptInterface::luaVocationGetPromotion);
// Town
registerClass("Town", "", LuaScriptInterface::luaTownCreate);
registerMetaMethod("Town", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Town", "getId", LuaScriptInterface::luaTownGetId);
registerMethod("Town", "getName", LuaScriptInterface::luaTownGetName);
registerMethod("Town", "getTemplePosition", LuaScriptInterface::luaTownGetTemplePosition);
// House
registerClass("House", "", LuaScriptInterface::luaHouseCreate);
registerMetaMethod("House", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("House", "getId", LuaScriptInterface::luaHouseGetId);
registerMethod("House", "getName", LuaScriptInterface::luaHouseGetName);
registerMethod("House", "getTown", LuaScriptInterface::luaHouseGetTown);
registerMethod("House", "getExitPosition", LuaScriptInterface::luaHouseGetExitPosition);
registerMethod("House", "getRent", LuaScriptInterface::luaHouseGetRent);
registerMethod("House", "getOwnerGuid", LuaScriptInterface::luaHouseGetOwnerGuid);
registerMethod("House", "setOwnerGuid", LuaScriptInterface::luaHouseSetOwnerGuid);
registerMethod("House", "getBeds", LuaScriptInterface::luaHouseGetBeds);
registerMethod("House", "getBedCount", LuaScriptInterface::luaHouseGetBedCount);
registerMethod("House", "getDoors", LuaScriptInterface::luaHouseGetDoors);
registerMethod("House", "getDoorCount", LuaScriptInterface::luaHouseGetDoorCount);
registerMethod("House", "getTiles", LuaScriptInterface::luaHouseGetTiles);
registerMethod("House", "getTileCount", LuaScriptInterface::luaHouseGetTileCount);
registerMethod("House", "getAccessList", LuaScriptInterface::luaHouseGetAccessList);
registerMethod("House", "setAccessList", LuaScriptInterface::luaHouseSetAccessList);
// ItemType
registerClass("ItemType", "", LuaScriptInterface::luaItemTypeCreate);
registerMetaMethod("ItemType", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("ItemType", "isCorpse", LuaScriptInterface::luaItemTypeIsCorpse);
registerMethod("ItemType", "isDoor", LuaScriptInterface::luaItemTypeIsDoor);
registerMethod("ItemType", "isContainer", LuaScriptInterface::luaItemTypeIsContainer);
registerMethod("ItemType", "isFluidContainer", LuaScriptInterface::luaItemTypeIsFluidContainer);
registerMethod("ItemType", "isMovable", LuaScriptInterface::luaItemTypeIsMovable);
registerMethod("ItemType", "isRune", LuaScriptInterface::luaItemTypeIsRune);
registerMethod("ItemType", "isStackable", LuaScriptInterface::luaItemTypeIsStackable);
registerMethod("ItemType", "isReadable", LuaScriptInterface::luaItemTypeIsReadable);
registerMethod("ItemType", "isWritable", LuaScriptInterface::luaItemTypeIsWritable);
registerMethod("ItemType", "getType", LuaScriptInterface::luaItemTypeGetType);
registerMethod("ItemType", "getId", LuaScriptInterface::luaItemTypeGetId);
registerMethod("ItemType", "getClientId", LuaScriptInterface::luaItemTypeGetClientId);
registerMethod("ItemType", "getName", LuaScriptInterface::luaItemTypeGetName);
registerMethod("ItemType", "getPluralName", LuaScriptInterface::luaItemTypeGetPluralName);
registerMethod("ItemType", "getArticle", LuaScriptInterface::luaItemTypeGetArticle);
registerMethod("ItemType", "getDescription", LuaScriptInterface::luaItemTypeGetDescription);
registerMethod("ItemType", "getSlotPosition", LuaScriptInterface::luaItemTypeGetSlotPosition);
registerMethod("ItemType", "getCharges", LuaScriptInterface::luaItemTypeGetCharges);
registerMethod("ItemType", "getFluidSource", LuaScriptInterface::luaItemTypeGetFluidSource);
registerMethod("ItemType", "getCapacity", LuaScriptInterface::luaItemTypeGetCapacity);
registerMethod("ItemType", "getWeight", LuaScriptInterface::luaItemTypeGetWeight);
registerMethod("ItemType", "getHitChance", LuaScriptInterface::luaItemTypeGetHitChance);
registerMethod("ItemType", "getShootRange", LuaScriptInterface::luaItemTypeGetShootRange);
registerMethod("ItemType", "getAttack", LuaScriptInterface::luaItemTypeGetAttack);
registerMethod("ItemType", "getDefense", LuaScriptInterface::luaItemTypeGetDefense);
registerMethod("ItemType", "getExtraDefense", LuaScriptInterface::luaItemTypeGetExtraDefense);
registerMethod("ItemType", "getArmor", LuaScriptInterface::luaItemTypeGetArmor);
registerMethod("ItemType", "getWeaponType", LuaScriptInterface::luaItemTypeGetWeaponType);
registerMethod("ItemType", "getElementType", LuaScriptInterface::luaItemTypeGetElementType);
registerMethod("ItemType", "getElementDamage", LuaScriptInterface::luaItemTypeGetElementDamage);
registerMethod("ItemType", "getTransformEquipId", LuaScriptInterface::luaItemTypeGetTransformEquipId);
registerMethod("ItemType", "getTransformDeEquipId", LuaScriptInterface::luaItemTypeGetTransformDeEquipId);
registerMethod("ItemType", "getDestroyId", LuaScriptInterface::luaItemTypeGetDestroyId);
registerMethod("ItemType", "getDecayId", LuaScriptInterface::luaItemTypeGetDecayId);
registerMethod("ItemType", "getRequiredLevel", LuaScriptInterface::luaItemTypeGetRequiredLevel);
registerMethod("ItemType", "hasSubType", LuaScriptInterface::luaItemTypeHasSubType);
// Combat
registerClass("Combat", "", LuaScriptInterface::luaCombatCreate);
registerMetaMethod("Combat", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Combat", "setParameter", LuaScriptInterface::luaCombatSetParameter);
registerMethod("Combat", "setFormula", LuaScriptInterface::luaCombatSetFormula);
registerMethod("Combat", "setArea", LuaScriptInterface::luaCombatSetArea);
registerMethod("Combat", "setCondition", LuaScriptInterface::luaCombatSetCondition);
registerMethod("Combat", "setCallback", LuaScriptInterface::luaCombatSetCallback);
registerMethod("Combat", "setOrigin", LuaScriptInterface::luaCombatSetOrigin);
registerMethod("Combat", "execute", LuaScriptInterface::luaCombatExecute);
// Condition
registerClass("Condition", "", LuaScriptInterface::luaConditionCreate);
registerMetaMethod("Condition", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMetaMethod("Condition", "__gc", LuaScriptInterface::luaConditionDelete);
registerMethod("Condition", "delete", LuaScriptInterface::luaConditionDelete);
registerMethod("Condition", "getId", LuaScriptInterface::luaConditionGetId);
registerMethod("Condition", "getSubId", LuaScriptInterface::luaConditionGetSubId);
registerMethod("Condition", "getType", LuaScriptInterface::luaConditionGetType);
registerMethod("Condition", "getIcons", LuaScriptInterface::luaConditionGetIcons);
registerMethod("Condition", "getEndTime", LuaScriptInterface::luaConditionGetEndTime);
registerMethod("Condition", "clone", LuaScriptInterface::luaConditionClone);
registerMethod("Condition", "getTicks", LuaScriptInterface::luaConditionGetTicks);
registerMethod("Condition", "setTicks", LuaScriptInterface::luaConditionSetTicks);
registerMethod("Condition", "setParameter", LuaScriptInterface::luaConditionSetParameter);
registerMethod("Condition", "setFormula", LuaScriptInterface::luaConditionSetFormula);
registerMethod("Condition", "setOutfit", LuaScriptInterface::luaConditionSetOutfit);
registerMethod("Condition", "addDamage", LuaScriptInterface::luaConditionAddDamage);
// MonsterType
registerClass("MonsterType", "", LuaScriptInterface::luaMonsterTypeCreate);
registerMetaMethod("MonsterType", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("MonsterType", "isAttackable", LuaScriptInterface::luaMonsterTypeIsAttackable);
registerMethod("MonsterType", "isConvinceable", LuaScriptInterface::luaMonsterTypeIsConvinceable);
registerMethod("MonsterType", "isSummonable", LuaScriptInterface::luaMonsterTypeIsSummonable);
registerMethod("MonsterType", "isIllusionable", LuaScriptInterface::luaMonsterTypeIsIllusionable);
registerMethod("MonsterType", "isHostile", LuaScriptInterface::luaMonsterTypeIsHostile);
registerMethod("MonsterType", "isPushable", LuaScriptInterface::luaMonsterTypeIsPushable);
registerMethod("MonsterType", "isHealthShown", LuaScriptInterface::luaMonsterTypeIsHealthShown);
registerMethod("MonsterType", "canPushItems", LuaScriptInterface::luaMonsterTypeCanPushItems);
registerMethod("MonsterType", "canPushCreatures", LuaScriptInterface::luaMonsterTypeCanPushCreatures);
registerMethod("MonsterType", "getName", LuaScriptInterface::luaMonsterTypeGetName);
registerMethod("MonsterType", "getNameDescription", LuaScriptInterface::luaMonsterTypeGetNameDescription);
registerMethod("MonsterType", "getHealth", LuaScriptInterface::luaMonsterTypeGetHealth);
registerMethod("MonsterType", "getMaxHealth", LuaScriptInterface::luaMonsterTypeGetMaxHealth);
registerMethod("MonsterType", "getRunHealth", LuaScriptInterface::luaMonsterTypeGetRunHealth);
registerMethod("MonsterType", "getExperience", LuaScriptInterface::luaMonsterTypeGetExperience);
registerMethod("MonsterType", "getCombatImmunities", LuaScriptInterface::luaMonsterTypeGetCombatImmunities);
registerMethod("MonsterType", "getConditionImmunities", LuaScriptInterface::luaMonsterTypeGetConditionImmunities);
registerMethod("MonsterType", "getAttackList", LuaScriptInterface::luaMonsterTypeGetAttackList);
registerMethod("MonsterType", "getDefenseList", LuaScriptInterface::luaMonsterTypeGetDefenseList);
registerMethod("MonsterType", "getElementList", LuaScriptInterface::luaMonsterTypeGetElementList);
registerMethod("MonsterType", "getVoices", LuaScriptInterface::luaMonsterTypeGetVoices);
registerMethod("MonsterType", "getLoot", LuaScriptInterface::luaMonsterTypeGetLoot);
registerMethod("MonsterType", "getCreatureEvents", LuaScriptInterface::luaMonsterTypeGetCreatureEvents);
registerMethod("MonsterType", "getSummonList", LuaScriptInterface::luaMonsterTypeGetSummonList);
registerMethod("MonsterType", "getMaxSummons", LuaScriptInterface::luaMonsterTypeGetMaxSummons);
registerMethod("MonsterType", "getArmor", LuaScriptInterface::luaMonsterTypeGetArmor);
registerMethod("MonsterType", "getDefense", LuaScriptInterface::luaMonsterTypeGetDefense);
registerMethod("MonsterType", "getOutfit", LuaScriptInterface::luaMonsterTypeGetOutfit);
registerMethod("MonsterType", "getRace", LuaScriptInterface::luaMonsterTypeGetRace);
registerMethod("MonsterType", "getCorpseId", LuaScriptInterface::luaMonsterTypeGetCorpseId);
registerMethod("MonsterType", "getManaCost", LuaScriptInterface::luaMonsterTypeGetManaCost);
registerMethod("MonsterType", "getBaseSpeed", LuaScriptInterface::luaMonsterTypeGetBaseSpeed);
registerMethod("MonsterType", "getLight", LuaScriptInterface::luaMonsterTypeGetLight);
registerMethod("MonsterType", "getStaticAttackChance", LuaScriptInterface::luaMonsterTypeGetStaticAttackChance);
registerMethod("MonsterType", "getTargetDistance", LuaScriptInterface::luaMonsterTypeGetTargetDistance);
registerMethod("MonsterType", "getYellChance", LuaScriptInterface::luaMonsterTypeGetYellChance);
registerMethod("MonsterType", "getYellSpeedTicks", LuaScriptInterface::luaMonsterTypeGetYellSpeedTicks);
registerMethod("MonsterType", "getChangeTargetChance", LuaScriptInterface::luaMonsterTypeGetChangeTargetChance);
registerMethod("MonsterType", "getChangeTargetSpeed", LuaScriptInterface::luaMonsterTypeGetChangeTargetSpeed);
// Party
registerClass("Party", "", nullptr);
registerMetaMethod("Party", "__eq", LuaScriptInterface::luaUserdataCompare);
registerMethod("Party", "disband", LuaScriptInterface::luaPartyDisband);
registerMethod("Party", "getLeader", LuaScriptInterface::luaPartyGetLeader);
registerMethod("Party", "setLeader", LuaScriptInterface::luaPartySetLeader);
registerMethod("Party", "getMembers", LuaScriptInterface::luaPartyGetMembers);
registerMethod("Party", "getMemberCount", LuaScriptInterface::luaPartyGetMemberCount);
registerMethod("Party", "getInvitees", LuaScriptInterface::luaPartyGetInvitees);
registerMethod("Party", "getInviteeCount", LuaScriptInterface::luaPartyGetInviteeCount);
registerMethod("Party", "addInvite", LuaScriptInterface::luaPartyAddInvite);
registerMethod("Party", "removeInvite", LuaScriptInterface::luaPartyRemoveInvite);
registerMethod("Party", "addMember", LuaScriptInterface::luaPartyAddMember);
registerMethod("Party", "removeMember", LuaScriptInterface::luaPartyRemoveMember);
registerMethod("Party", "isSharedExperienceActive", LuaScriptInterface::luaPartyIsSharedExperienceActive);
registerMethod("Party", "isSharedExperienceEnabled", LuaScriptInterface::luaPartyIsSharedExperienceEnabled);
registerMethod("Party", "shareExperience", LuaScriptInterface::luaPartyShareExperience);
registerMethod("Party", "setSharedExperience", LuaScriptInterface::luaPartySetSharedExperience);
}
#undef registerEnum
#undef registerEnumIn
void LuaScriptInterface::registerClass(const std::string& className, const std::string& baseClass, lua_CFunction newFunction/* = nullptr*/)
{
// className = {}
lua_newtable(luaState);
lua_pushvalue(luaState, -1);
lua_setglobal(luaState, className.c_str());
int methods = lua_gettop(luaState);
// methodsTable = {}
lua_newtable(luaState);
int methodsTable = lua_gettop(luaState);
if (newFunction) {
// className.__call = newFunction
lua_pushcfunction(luaState, newFunction);
lua_setfield(luaState, methodsTable, "__call");
}
uint32_t parents = 0;
if (!baseClass.empty()) {
lua_getglobal(luaState, baseClass.c_str());
lua_rawgeti(luaState, -1, 'p');
parents = getNumber<uint32_t>(luaState, -1) + 1;
lua_pop(luaState, 1);
lua_setfield(luaState, methodsTable, "__index");
}
// setmetatable(className, methodsTable)
lua_setmetatable(luaState, methods);
// className.metatable = {}
luaL_newmetatable(luaState, className.c_str());
int metatable = lua_gettop(luaState);
// className.metatable.__metatable = className
lua_pushvalue(luaState, methods);
lua_setfield(luaState, metatable, "__metatable");
// className.metatable.__index = className
lua_pushvalue(luaState, methods);
lua_setfield(luaState, metatable, "__index");
// className.metatable['h'] = hash
lua_pushnumber(luaState, std::hash<std::string>()(className));
lua_rawseti(luaState, metatable, 'h');
// className.metatable['p'] = parents
lua_pushnumber(luaState, parents);
lua_rawseti(luaState, metatable, 'p');
// className.metatable['t'] = type
if (className == "Item") {
lua_pushnumber(luaState, LuaData_Item);
} else if (className == "Container") {
lua_pushnumber(luaState, LuaData_Container);
} else if (className == "Teleport") {
lua_pushnumber(luaState, LuaData_Teleport);
} else if (className == "Player") {
lua_pushnumber(luaState, LuaData_Player);
} else if (className == "Monster") {
lua_pushnumber(luaState, LuaData_Monster);
} else if (className == "Npc") {
lua_pushnumber(luaState, LuaData_Npc);
} else if (className == "Tile") {
lua_pushnumber(luaState, LuaData_Tile);
} else {
lua_pushnumber(luaState, LuaData_Unknown);
}
lua_rawseti(luaState, metatable, 't');
// pop className, className.metatable
lua_pop(luaState, 2);
}
void LuaScriptInterface::registerTable(const std::string& tableName)
{
// _G[tableName] = {}
lua_newtable(luaState);
lua_setglobal(luaState, tableName.c_str());
}
void LuaScriptInterface::registerMethod(const std::string& globalName, const std::string& methodName, lua_CFunction func)
{
// globalName.methodName = func
lua_getglobal(luaState, globalName.c_str());
lua_pushcfunction(luaState, func);
lua_setfield(luaState, -2, methodName.c_str());
// pop globalName
lua_pop(luaState, 1);
}
void LuaScriptInterface::registerMetaMethod(const std::string& className, const std::string& methodName, lua_CFunction func)
{
// className.metatable.methodName = func
luaL_getmetatable(luaState, className.c_str());
lua_pushcfunction(luaState, func);
lua_setfield(luaState, -2, methodName.c_str());
// pop className.metatable
lua_pop(luaState, 1);
}
void LuaScriptInterface::registerGlobalMethod(const std::string& functionName, lua_CFunction func)
{
// _G[functionName] = func
lua_pushcfunction(luaState, func);
lua_setglobal(luaState, functionName.c_str());
}
void LuaScriptInterface::registerVariable(const std::string& tableName, const std::string& name, lua_Number value)
{
// tableName.name = value
lua_getglobal(luaState, tableName.c_str());
setField(luaState, name.c_str(), value);
// pop tableName
lua_pop(luaState, 1);
}
void LuaScriptInterface::registerGlobalVariable(const std::string& name, lua_Number value)
{
// _G[name] = value
lua_pushnumber(luaState, value);
lua_setglobal(luaState, name.c_str());
}
void LuaScriptInterface::registerGlobalBoolean(const std::string& name, bool value)
{
// _G[name] = value
pushBoolean(luaState, value);
lua_setglobal(luaState, name.c_str());
}
int LuaScriptInterface::luaGetPlayerFlagValue(lua_State* L)
{
//getPlayerFlagValue(cid, flag)
Player* player = getPlayer(L, 1);
if (player) {
PlayerFlags flag = getNumber<PlayerFlags>(L, 2);
pushBoolean(L, player->hasFlag(flag));
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaGetPlayerInstantSpellCount(lua_State* L)
{
//getPlayerInstantSpellCount(cid)
Player* player = getPlayer(L, 1);
if (player) {
lua_pushnumber(L, g_spells->getInstantSpellCount(player));
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaGetPlayerInstantSpellInfo(lua_State* L)
{
//getPlayerInstantSpellInfo(cid, index)
Player* player = getPlayer(L, 1);
if (!player) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t index = getNumber<uint32_t>(L, 2);
InstantSpell* spell = g_spells->getInstantSpellByIndex(player, index);
if (!spell) {
reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
lua_createtable(L, 0, 6);
setField(L, "name", spell->getName());
setField(L, "words", spell->getWords());
setField(L, "level", spell->getLevel());
setField(L, "mlevel", spell->getMagicLevel());
setField(L, "mana", spell->getManaCost(player));
setField(L, "manapercent", spell->getManaPercent());
return 1;
}
int LuaScriptInterface::luaDoPlayerAddItem(lua_State* L)
{
//doPlayerAddItem(cid, itemid, <optional: default: 1> count/subtype, <optional: default: 1> canDropOnMap)
//doPlayerAddItem(cid, itemid, <optional: default: 1> count, <optional: default: 1> canDropOnMap, <optional: default: 1>subtype)
Player* player = getPlayer(L, 1);
if (!player) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint16_t itemId = getNumber<uint16_t>(L, 2);
int32_t count = getNumber<int32_t>(L, 3, 1);
bool canDropOnMap = getBoolean(L, 4, true);
uint16_t subType = getNumber<uint16_t>(L, 5, 1);
const ItemType& it = Item::items[itemId];
int32_t itemCount;
auto parameters = lua_gettop(L);
if (parameters > 4) {
//subtype already supplied, count then is the amount
itemCount = std::max<int32_t>(1, count);
} else if (it.hasSubType()) {
if (it.stackable) {
itemCount = static_cast<int32_t>(std::ceil(static_cast<float>(count) / 100));
} else {
itemCount = 1;
}
subType = count;
} else {
itemCount = std::max<int32_t>(1, count);
}
while (itemCount > 0) {
uint16_t stackCount = subType;
if (it.stackable && stackCount > 100) {
stackCount = 100;
}
Item* newItem = Item::CreateItem(itemId, stackCount);
if (!newItem) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (it.stackable) {
subType -= stackCount;
}
ReturnValue ret = g_game.internalPlayerAddItem(player, newItem, canDropOnMap);
if (ret != RETURNVALUE_NOERROR) {
delete newItem;
pushBoolean(L, false);
return 1;
}
if (--itemCount == 0) {
if (newItem->getParent()) {
uint32_t uid = getScriptEnv()->addThing(newItem);
lua_pushnumber(L, uid);
return 1;
} else {
//stackable item stacked with existing object, newItem will be released
pushBoolean(L, false);
return 1;
}
}
}
pushBoolean(L, false);
return 1;
}
int LuaScriptInterface::luaDoTileAddItemEx(lua_State* L)
{
//doTileAddItemEx(pos, uid)
const Position& pos = getPosition(L, 1);
Tile* tile = g_game.map.getTile(pos);
if (!tile) {
std::ostringstream ss;
ss << pos << ' ' << getErrorDesc(LUA_ERROR_TILE_NOT_FOUND);
reportErrorFunc(ss.str());
pushBoolean(L, false);
return 1;
}
uint32_t uid = getNumber<uint32_t>(L, 2);
Item* item = getScriptEnv()->getItemByUID(uid);
if (!item) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (item->getParent() != VirtualCylinder::virtualCylinder) {
reportErrorFunc("Item already has a parent");
pushBoolean(L, false);
return 1;
}
lua_pushnumber(L, g_game.internalAddItem(tile, item));
return 1;
}
int LuaScriptInterface::luaDoCreateItem(lua_State* L)
{
//doCreateItem(itemid, <optional> type/count, pos)
//Returns uid of the created item, only works on tiles.
const Position& pos = getPosition(L, 3);
Tile* tile = g_game.map.getTile(pos);
if (!tile) {
std::ostringstream ss;
ss << pos << ' ' << getErrorDesc(LUA_ERROR_TILE_NOT_FOUND);
reportErrorFunc(ss.str());
pushBoolean(L, false);
return 1;
}
ScriptEnvironment* env = getScriptEnv();
int32_t itemCount = 1;
int32_t subType = 1;
uint16_t itemId = getNumber<uint16_t>(L, 1);
uint32_t count = getNumber<uint32_t>(L, 2, 1);
const ItemType& it = Item::items[itemId];
if (it.hasSubType()) {
if (it.stackable) {
itemCount = static_cast<int32_t>(std::ceil(static_cast<float>(count) / 100));
}
subType = count;
} else {
itemCount = std::max<int32_t>(1, count);
}
while (itemCount > 0) {
int32_t stackCount = std::min<int32_t>(100, subType);
Item* newItem = Item::CreateItem(itemId, stackCount);
if (!newItem) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (it.stackable) {
subType -= stackCount;
}
ReturnValue ret = g_game.internalAddItem(tile, newItem, INDEX_WHEREEVER, FLAG_NOLIMIT);
if (ret != RETURNVALUE_NOERROR) {
delete newItem;
pushBoolean(L, false);
return 1;
}
if (--itemCount == 0) {
if (newItem->getParent()) {
uint32_t uid = env->addThing(newItem);
lua_pushnumber(L, uid);
return 1;
} else {
//stackable item stacked with existing object, newItem will be released
pushBoolean(L, false);
return 1;
}
}
}
pushBoolean(L, false);
return 1;
}
int LuaScriptInterface::luaDoCreateItemEx(lua_State* L)
{
//doCreateItemEx(itemid, <optional> count/subtype)
//Returns uid of the created item
uint16_t itemId = getNumber<uint16_t>(L, 1);
uint32_t count = getNumber<uint32_t>(L, 2, 1);
const ItemType& it = Item::items[itemId];
if (it.stackable && count > 100) {
reportErrorFunc("Stack count cannot be higher than 100.");
count = 100;
}
Item* newItem = Item::CreateItem(itemId, count);
if (!newItem) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
newItem->setParent(VirtualCylinder::virtualCylinder);
ScriptEnvironment* env = getScriptEnv();
env->addTempItem(newItem);
uint32_t uid = env->addThing(newItem);
lua_pushnumber(L, uid);
return 1;
}
int LuaScriptInterface::luaDebugPrint(lua_State* L)
{
//debugPrint(text)
reportErrorFunc(getString(L, -1));
return 0;
}
int LuaScriptInterface::luaGetWorldTime(lua_State* L)
{
//getWorldTime()
uint32_t time = g_game.getLightHour();
lua_pushnumber(L, time);
return 1;
}
int LuaScriptInterface::luaGetWorldLight(lua_State* L)
{
//getWorldLight()
LightInfo lightInfo;
g_game.getWorldLightInfo(lightInfo);
lua_pushnumber(L, lightInfo.level);
lua_pushnumber(L, lightInfo.color);
return 2;
}
int LuaScriptInterface::luaGetWorldUpTime(lua_State* L)
{
//getWorldUpTime()
uint64_t uptime = (OTSYS_TIME() - ProtocolStatus::start) / 1000;
lua_pushnumber(L, uptime);
return 1;
}
bool LuaScriptInterface::getArea(lua_State* L, std::list<uint32_t>& list, uint32_t& rows)
{
lua_pushnil(L);
for (rows = 0; lua_next(L, -2) != 0; ++rows) {
if (!isTable(L, -1)) {
return false;
}
lua_pushnil(L);
while (lua_next(L, -2) != 0) {
if (!isNumber(L, -1)) {
return false;
}
list.push_back(getNumber<uint32_t>(L, -1));
lua_pop(L, 1);
}
lua_pop(L, 1);
}
lua_pop(L, 1);
return (rows != 0);
}
int LuaScriptInterface::luaCreateCombatArea(lua_State* L)
{
//createCombatArea( {area}, <optional> {extArea} )
ScriptEnvironment* env = getScriptEnv();
if (env->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
pushBoolean(L, false);
return 1;
}
uint32_t areaId = g_luaEnvironment.createAreaObject(env->getScriptInterface());
AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
int parameters = lua_gettop(L);
if (parameters >= 2) {
uint32_t rowsExtArea;
std::list<uint32_t> listExtArea;
if (!isTable(L, 2) || !getArea(L, listExtArea, rowsExtArea)) {
reportErrorFunc("Invalid extended area table.");
pushBoolean(L, false);
return 1;
}
area->setupExtArea(listExtArea, rowsExtArea);
}
uint32_t rowsArea = 0;
std::list<uint32_t> listArea;
if (!isTable(L, 1) || !getArea(L, listArea, rowsArea)) {
reportErrorFunc("Invalid area table.");
pushBoolean(L, false);
return 1;
}
area->setupArea(listArea, rowsArea);
lua_pushnumber(L, areaId);
return 1;
}
int LuaScriptInterface::luaDoAreaCombatHealth(lua_State* L)
{
//doAreaCombatHealth(cid, type, pos, area, min, max, effect[, origin = ORIGIN_SPELL])
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 4);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (area || areaId == 0) {
CombatType_t combatType = getNumber<CombatType_t>(L, 2);
CombatParams params;
params.combatType = combatType;
params.impactEffect = getNumber<uint8_t>(L, 7);
CombatDamage damage;
damage.origin = getNumber<CombatOrigin>(L, 8, ORIGIN_SPELL);
damage.primary.type = combatType;
damage.primary.value = normal_random(getNumber<int32_t>(L, 6), getNumber<int32_t>(L, 5));
Combat::doCombatHealth(creature, getPosition(L, 3), area, damage, params);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoTargetCombatHealth(lua_State* L)
{
//doTargetCombatHealth(cid, target, type, min, max, effect[, origin = ORIGIN_SPELL])
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CombatType_t combatType = getNumber<CombatType_t>(L, 3);
CombatParams params;
params.combatType = combatType;
params.impactEffect = getNumber<uint8_t>(L, 6);
CombatDamage damage;
damage.origin = getNumber<CombatOrigin>(L, 7, ORIGIN_SPELL);
damage.primary.type = combatType;
damage.primary.value = normal_random(getNumber<int32_t>(L, 4), getNumber<int32_t>(L, 5));
Combat::doCombatHealth(creature, target, damage, params);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoAreaCombatMana(lua_State* L)
{
//doAreaCombatMana(cid, pos, area, min, max, effect[, origin = ORIGIN_SPELL])
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 3);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (area || areaId == 0) {
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 6);
CombatDamage damage;
damage.origin = getNumber<CombatOrigin>(L, 7, ORIGIN_SPELL);
damage.primary.type = COMBAT_MANADRAIN;
damage.primary.value = normal_random(getNumber<int32_t>(L, 4), getNumber<int32_t>(L, 5));
Position pos = getPosition(L, 2);
Combat::doCombatMana(creature, pos, area, damage, params);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoTargetCombatMana(lua_State* L)
{
//doTargetCombatMana(cid, target, min, max, effect[, origin = ORIGIN_SPELL)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 5);
CombatDamage damage;
damage.origin = getNumber<CombatOrigin>(L, 6, ORIGIN_SPELL);
damage.primary.type = COMBAT_MANADRAIN;
damage.primary.value = normal_random(getNumber<int32_t>(L, 3), getNumber<int32_t>(L, 4));
Combat::doCombatMana(creature, target, damage, params);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoAreaCombatCondition(lua_State* L)
{
//doAreaCombatCondition(cid, pos, area, condition, effect)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
const Condition* condition = getUserdata<Condition>(L, 4);
if (!condition) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 3);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (area || areaId == 0) {
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 5);
params.conditionList.emplace_front(condition);
Combat::doCombatCondition(creature, getPosition(L, 2), area, params);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoTargetCombatCondition(lua_State* L)
{
//doTargetCombatCondition(cid, target, condition, effect)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
const Condition* condition = getUserdata<Condition>(L, 3);
if (!condition) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 4);
params.conditionList.emplace_front(condition);
Combat::doCombatCondition(creature, target, params);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoAreaCombatDispel(lua_State* L)
{
//doAreaCombatDispel(cid, pos, area, type, effect)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t areaId = getNumber<uint32_t>(L, 3);
const AreaCombat* area = g_luaEnvironment.getAreaObject(areaId);
if (area || areaId == 0) {
CombatParams params;
params.impactEffect = getNumber<uint8_t>(L, 5);
params.dispelType = getNumber<ConditionType_t>(L, 4);
Combat::doCombatDispel(creature, getPosition(L, 2), area, params);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDoTargetCombatDispel(lua_State* L)
{
//doTargetCombatDispel(cid, target, type, effect)
Creature* creature = getCreature(L, 1);
if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
CombatParams params;
params.dispelType = getNumber<ConditionType_t>(L, 3);
params.impactEffect = getNumber<uint8_t>(L, 4);
Combat::doCombatDispel(creature, target, params);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaDoChallengeCreature(lua_State* L)
{
//doChallengeCreature(cid, target)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Creature* target = getCreature(L, 2);
if (!target) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
target->challengeCreature(creature);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaSetCreatureOutfit(lua_State* L)
{
//doSetCreatureOutfit(cid, outfit, time)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Outfit_t outfit = getOutfit(L, 2);
int32_t time = getNumber<int32_t>(L, 3);
pushBoolean(L, Spell::CreateIllusion(creature, outfit, time) == RETURNVALUE_NOERROR);
return 1;
}
int LuaScriptInterface::luaSetMonsterOutfit(lua_State* L)
{
//doSetMonsterOutfit(cid, name, time)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
std::string name = getString(L, 2);
int32_t time = getNumber<int32_t>(L, 3);
pushBoolean(L, Spell::CreateIllusion(creature, name, time) == RETURNVALUE_NOERROR);
return 1;
}
int LuaScriptInterface::luaSetItemOutfit(lua_State* L)
{
//doSetItemOutfit(cid, item, time)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint32_t item = getNumber<uint32_t>(L, 2);
int32_t time = getNumber<int32_t>(L, 3);
pushBoolean(L, Spell::CreateIllusion(creature, item, time) == RETURNVALUE_NOERROR);
return 1;
}
int LuaScriptInterface::luaDoMoveCreature(lua_State* L)
{
//doMoveCreature(cid, direction)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Direction direction = getNumber<Direction>(L, 2);
if (direction > DIRECTION_LAST) {
reportErrorFunc("No valid direction");
pushBoolean(L, false);
return 1;
}
ReturnValue ret = g_game.internalMoveCreature(creature, direction, FLAG_NOLIMIT);
lua_pushnumber(L, ret);
return 1;
}
int LuaScriptInterface::luaIsValidUID(lua_State* L)
{
//isValidUID(uid)
pushBoolean(L, getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, -1)) != nullptr);
return 1;
}
int LuaScriptInterface::luaIsDepot(lua_State* L)
{
//isDepot(uid)
Container* container = getScriptEnv()->getContainerByUID(getNumber<uint32_t>(L, -1));
pushBoolean(L, container && container->getDepotLocker());
return 1;
}
int LuaScriptInterface::luaIsMoveable(lua_State* L)
{
//isMoveable(uid)
//isMovable(uid)
Thing* thing = getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, -1));
pushBoolean(L, thing && thing->isPushable());
return 1;
}
int LuaScriptInterface::luaDoAddContainerItem(lua_State* L)
{
//doAddContainerItem(uid, itemid, <optional> count/subtype)
uint32_t uid = getNumber<uint32_t>(L, 1);
ScriptEnvironment* env = getScriptEnv();
Container* container = env->getContainerByUID(uid);
if (!container) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONTAINER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint16_t itemId = getNumber<uint16_t>(L, 2);
const ItemType& it = Item::items[itemId];
int32_t itemCount = 1;
int32_t subType = 1;
uint32_t count = getNumber<uint32_t>(L, 3, 1);
if (it.hasSubType()) {
if (it.stackable) {
itemCount = static_cast<int32_t>(std::ceil(static_cast<float>(count) / 100));
}
subType = count;
} else {
itemCount = std::max<int32_t>(1, count);
}
while (itemCount > 0) {
int32_t stackCount = std::min<int32_t>(100, subType);
Item* newItem = Item::CreateItem(itemId, stackCount);
if (!newItem) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (it.stackable) {
subType -= stackCount;
}
ReturnValue ret = g_game.internalAddItem(container, newItem);
if (ret != RETURNVALUE_NOERROR) {
delete newItem;
pushBoolean(L, false);
return 1;
}
if (--itemCount == 0) {
if (newItem->getParent()) {
lua_pushnumber(L, env->addThing(newItem));
} else {
//stackable item stacked with existing object, newItem will be released
pushBoolean(L, false);
}
return 1;
}
}
pushBoolean(L, false);
return 1;
}
int LuaScriptInterface::luaGetDepotId(lua_State* L)
{
//getDepotId(uid)
uint32_t uid = getNumber<uint32_t>(L, -1);
Container* container = getScriptEnv()->getContainerByUID(uid);
if (!container) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CONTAINER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
DepotLocker* depotLocker = container->getDepotLocker();
if (!depotLocker) {
reportErrorFunc("Depot not found");
pushBoolean(L, false);
return 1;
}
lua_pushnumber(L, depotLocker->getDepotId());
return 1;
}
int LuaScriptInterface::luaIsInArray(lua_State* L)
{
//isInArray(array, value)
if (!isTable(L, 1)) {
pushBoolean(L, false);
return 1;
}
lua_pushnil(L);
while (lua_next(L, 1)) {
if (lua_equal(L, 2, -1) != 0) {
pushBoolean(L, true);
return 1;
}
lua_pop(L, 1);
}
pushBoolean(L, false);
return 1;
}
int LuaScriptInterface::luaDoSetCreatureLight(lua_State* L)
{
//doSetCreatureLight(cid, lightLevel, lightColor, time)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
uint16_t level = getNumber<uint16_t>(L, 2);
uint16_t color = getNumber<uint16_t>(L, 3);
uint32_t time = getNumber<uint32_t>(L, 4);
Condition* condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_LIGHT, time, level | (color << 8));
creature->addCondition(condition);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaAddEvent(lua_State* L)
{
//addEvent(callback, delay, ...)
lua_State* globalState = g_luaEnvironment.getLuaState();
if (!globalState) {
reportErrorFunc("No valid script interface!");
pushBoolean(L, false);
return 1;
} else if (globalState != L) {
lua_xmove(L, globalState, lua_gettop(L));
}
int parameters = lua_gettop(globalState);
if (!isFunction(globalState, -parameters)) { //-parameters means the first parameter from left to right
reportErrorFunc("callback parameter should be a function.");
pushBoolean(L, false);
return 1;
}
if (g_config.getBoolean(ConfigManager::WARN_UNSAFE_SCRIPTS) || g_config.getBoolean(ConfigManager::CONVERT_UNSAFE_SCRIPTS)) {
std::vector<std::pair<int32_t, LuaDataType>> indexes;
for (int i = 3; i <= parameters; ++i) {
if (lua_getmetatable(globalState, i) == 0) {
continue;
}
lua_rawgeti(L, -1, 't');
LuaDataType type = getNumber<LuaDataType>(L, -1);
if (type != LuaData_Unknown && type != LuaData_Tile) {
indexes.push_back({i, type});
}
lua_pop(globalState, 2);
}
if (!indexes.empty()) {
if (g_config.getBoolean(ConfigManager::WARN_UNSAFE_SCRIPTS)) {
bool plural = indexes.size() > 1;
std::string warningString = "Argument";
if (plural) {
warningString += 's';
}
for (const auto& entry : indexes) {
if (entry == indexes.front()) {
warningString += ' ';
} else if (entry == indexes.back()) {
warningString += " and ";
} else {
warningString += ", ";
}
warningString += '#';
warningString += std::to_string(entry.first);
}
if (plural) {
warningString += " are unsafe";
} else {
warningString += " is unsafe";
}
reportErrorFunc(warningString);
}
if (g_config.getBoolean(ConfigManager::CONVERT_UNSAFE_SCRIPTS)) {
for (const auto& entry : indexes) {
switch (entry.second) {
case LuaData_Item:
case LuaData_Container:
case LuaData_Teleport: {
lua_getglobal(globalState, "Item");
lua_getfield(globalState, -1, "getUniqueId");
break;
}
case LuaData_Player:
case LuaData_Monster:
case LuaData_Npc: {
lua_getglobal(globalState, "Creature");
lua_getfield(globalState, -1, "getId");
break;
}
default:
break;
}
lua_replace(globalState, -2);
lua_pushvalue(globalState, entry.first);
lua_call(globalState, 1, 1);
lua_replace(globalState, entry.first);
}
}
}
}
LuaTimerEventDesc eventDesc;
for (int i = 0; i < parameters - 2; ++i) { //-2 because addEvent needs at least two parameters
eventDesc.parameters.push_back(luaL_ref(globalState, LUA_REGISTRYINDEX));
}
uint32_t delay = std::max<uint32_t>(100, getNumber<uint32_t>(globalState, 2));
lua_pop(globalState, 1);
eventDesc.function = luaL_ref(globalState, LUA_REGISTRYINDEX);
eventDesc.scriptId = getScriptEnv()->getScriptId();
auto& lastTimerEventId = g_luaEnvironment.lastEventTimerId;
eventDesc.eventId = g_scheduler.addEvent(createSchedulerTask(
delay, std::bind(&LuaEnvironment::executeTimerEvent, &g_luaEnvironment, lastTimerEventId)
));
g_luaEnvironment.timerEvents.emplace(lastTimerEventId, std::move(eventDesc));
lua_pushnumber(L, lastTimerEventId++);
return 1;
}
int LuaScriptInterface::luaStopEvent(lua_State* L)
{
//stopEvent(eventid)
lua_State* globalState = g_luaEnvironment.getLuaState();
if (!globalState) {
reportErrorFunc("No valid script interface!");
pushBoolean(L, false);
return 1;
}
uint32_t eventId = getNumber<uint32_t>(L, 1);
auto& timerEvents = g_luaEnvironment.timerEvents;
auto it = timerEvents.find(eventId);
if (it == timerEvents.end()) {
pushBoolean(L, false);
return 1;
}
LuaTimerEventDesc timerEventDesc = std::move(it->second);
timerEvents.erase(it);
g_scheduler.stopEvent(timerEventDesc.eventId);
luaL_unref(globalState, LUA_REGISTRYINDEX, timerEventDesc.function);
for (auto parameter : timerEventDesc.parameters) {
luaL_unref(globalState, LUA_REGISTRYINDEX, parameter);
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaGetCreatureCondition(lua_State* L)
{
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
ConditionType_t condition = getNumber<ConditionType_t>(L, 2);
uint32_t subId = getNumber<uint32_t>(L, 3, 0);
pushBoolean(L, creature->hasCondition(condition, subId));
return 1;
}
int LuaScriptInterface::luaSaveServer(lua_State* L)
{
g_game.saveGameState();
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCleanMap(lua_State* L)
{
lua_pushnumber(L, g_game.map.clean());
return 1;
}
int LuaScriptInterface::luaIsInWar(lua_State* L)
{
//isInWar(cid, target)
Player* player = getPlayer(L, 1);
if (!player) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Player* targetPlayer = getPlayer(L, 2);
if (!targetPlayer) {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
pushBoolean(L, player->isInWar(targetPlayer));
return 1;
}
int LuaScriptInterface::luaGetWaypointPositionByName(lua_State* L)
{
//getWaypointPositionByName(name)
auto& waypoints = g_game.map.waypoints;
auto it = waypoints.find(getString(L, -1));
if (it != waypoints.end()) {
pushPosition(L, it->second);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaSendChannelMessage(lua_State* L)
{
//sendChannelMessage(channelId, type, message)
uint32_t channelId = getNumber<uint32_t>(L, 1);
ChatChannel* channel = g_chat->getChannelById(channelId);
if (!channel) {
pushBoolean(L, false);
return 1;
}
SpeakClasses type = getNumber<SpeakClasses>(L, 2);
std::string message = getString(L, 3);
channel->sendToAll(message, type);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaSendGuildChannelMessage(lua_State* L)
{
//sendGuildChannelMessage(guildId, type, message)
uint32_t guildId = getNumber<uint32_t>(L, 1);
ChatChannel* channel = g_chat->getGuildChannelById(guildId);
if (!channel) {
pushBoolean(L, false);
return 1;
}
SpeakClasses type = getNumber<SpeakClasses>(L, 2);
std::string message = getString(L, 3);
channel->sendToAll(message, type);
pushBoolean(L, true);
return 1;
}
std::string LuaScriptInterface::escapeString(const std::string& string)
{
std::string s = string;
replaceString(s, "\\", "\\\\");
replaceString(s, "\"", "\\\"");
replaceString(s, "'", "\\'");
replaceString(s, "[[", "\\[[");
return s;
}
#ifndef LUAJIT_VERSION
const luaL_Reg LuaScriptInterface::luaBitReg[] = {
//{"tobit", LuaScriptInterface::luaBitToBit},
{"bnot", LuaScriptInterface::luaBitNot},
{"band", LuaScriptInterface::luaBitAnd},
{"bor", LuaScriptInterface::luaBitOr},
{"bxor", LuaScriptInterface::luaBitXor},
{"lshift", LuaScriptInterface::luaBitLeftShift},
{"rshift", LuaScriptInterface::luaBitRightShift},
//{"arshift", LuaScriptInterface::luaBitArithmeticalRightShift},
//{"rol", LuaScriptInterface::luaBitRotateLeft},
//{"ror", LuaScriptInterface::luaBitRotateRight},
//{"bswap", LuaScriptInterface::luaBitSwapEndian},
//{"tohex", LuaScriptInterface::luaBitToHex},
{nullptr, nullptr}
};
int LuaScriptInterface::luaBitNot(lua_State* L)
{
lua_pushnumber(L, ~getNumber<uint32_t>(L, -1));
return 1;
}
#define MULTIOP(name, op) \
int LuaScriptInterface::luaBit##name(lua_State* L) \
{ \
int n = lua_gettop(L); \
uint32_t w = getNumber<uint32_t>(L, -1); \
for (int i = 1; i < n; ++i) \
w op getNumber<uint32_t>(L, i); \
lua_pushnumber(L, w); \
return 1; \
}
MULTIOP(And, &= )
MULTIOP(Or, |= )
MULTIOP(Xor, ^= )
#define SHIFTOP(name, op) \
int LuaScriptInterface::luaBit##name(lua_State* L) \
{ \
uint32_t n1 = getNumber<uint32_t>(L, 1), n2 = getNumber<uint32_t>(L, 2); \
lua_pushnumber(L, (n1 op n2)); \
return 1; \
}
SHIFTOP(LeftShift, << )
SHIFTOP(RightShift, >> )
#endif
const luaL_Reg LuaScriptInterface::luaConfigManagerTable[] = {
{"getString", LuaScriptInterface::luaConfigManagerGetString},
{"getNumber", LuaScriptInterface::luaConfigManagerGetNumber},
{"getBoolean", LuaScriptInterface::luaConfigManagerGetBoolean},
{nullptr, nullptr}
};
int LuaScriptInterface::luaConfigManagerGetString(lua_State* L)
{
pushString(L, g_config.getString(getNumber<ConfigManager::string_config_t>(L, -1)));
return 1;
}
int LuaScriptInterface::luaConfigManagerGetNumber(lua_State* L)
{
lua_pushnumber(L, g_config.getNumber(getNumber<ConfigManager::integer_config_t>(L, -1)));
return 1;
}
int LuaScriptInterface::luaConfigManagerGetBoolean(lua_State* L)
{
pushBoolean(L, g_config.getBoolean(getNumber<ConfigManager::boolean_config_t>(L, -1)));
return 1;
}
const luaL_Reg LuaScriptInterface::luaDatabaseTable[] = {
{"query", LuaScriptInterface::luaDatabaseExecute},
{"asyncQuery", LuaScriptInterface::luaDatabaseAsyncExecute},
{"storeQuery", LuaScriptInterface::luaDatabaseStoreQuery},
{"asyncStoreQuery", LuaScriptInterface::luaDatabaseAsyncStoreQuery},
{"escapeString", LuaScriptInterface::luaDatabaseEscapeString},
{"escapeBlob", LuaScriptInterface::luaDatabaseEscapeBlob},
{"lastInsertId", LuaScriptInterface::luaDatabaseLastInsertId},
{"tableExists", LuaScriptInterface::luaDatabaseTableExists},
{nullptr, nullptr}
};
int LuaScriptInterface::luaDatabaseExecute(lua_State* L)
{
pushBoolean(L, Database::getInstance().executeQuery(getString(L, -1)));
return 1;
}
int LuaScriptInterface::luaDatabaseAsyncExecute(lua_State* L)
{
std::function<void(DBResult_ptr, bool)> callback;
if (lua_gettop(L) > 1) {
int32_t ref = luaL_ref(L, LUA_REGISTRYINDEX);
auto scriptId = getScriptEnv()->getScriptId();
callback = [ref, scriptId](DBResult_ptr, bool success) {
lua_State* luaState = g_luaEnvironment.getLuaState();
if (!luaState) {
return;
}
if (!LuaScriptInterface::reserveScriptEnv()) {
luaL_unref(luaState, LUA_REGISTRYINDEX, ref);
return;
}
lua_rawgeti(luaState, LUA_REGISTRYINDEX, ref);
pushBoolean(luaState, success);
auto env = getScriptEnv();
env->setScriptId(scriptId, &g_luaEnvironment);
g_luaEnvironment.callFunction(1);
luaL_unref(luaState, LUA_REGISTRYINDEX, ref);
};
}
g_databaseTasks.addTask(getString(L, -1), callback);
return 0;
}
int LuaScriptInterface::luaDatabaseStoreQuery(lua_State* L)
{
if (DBResult_ptr res = Database::getInstance().storeQuery(getString(L, -1))) {
lua_pushnumber(L, ScriptEnvironment::addResult(res));
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaDatabaseAsyncStoreQuery(lua_State* L)
{
std::function<void(DBResult_ptr, bool)> callback;
if (lua_gettop(L) > 1) {
int32_t ref = luaL_ref(L, LUA_REGISTRYINDEX);
auto scriptId = getScriptEnv()->getScriptId();
callback = [ref, scriptId](DBResult_ptr result, bool) {
lua_State* luaState = g_luaEnvironment.getLuaState();
if (!luaState) {
return;
}
if (!LuaScriptInterface::reserveScriptEnv()) {
luaL_unref(luaState, LUA_REGISTRYINDEX, ref);
return;
}
lua_rawgeti(luaState, LUA_REGISTRYINDEX, ref);
if (result) {
lua_pushnumber(luaState, ScriptEnvironment::addResult(result));
} else {
pushBoolean(luaState, false);
}
auto env = getScriptEnv();
env->setScriptId(scriptId, &g_luaEnvironment);
g_luaEnvironment.callFunction(1);
luaL_unref(luaState, LUA_REGISTRYINDEX, ref);
};
}
g_databaseTasks.addTask(getString(L, -1), callback, true);
return 0;
}
int LuaScriptInterface::luaDatabaseEscapeString(lua_State* L)
{
pushString(L, Database::getInstance().escapeString(getString(L, -1)));
return 1;
}
int LuaScriptInterface::luaDatabaseEscapeBlob(lua_State* L)
{
uint32_t length = getNumber<uint32_t>(L, 2);
pushString(L, Database::getInstance().escapeBlob(getString(L, 1).c_str(), length));
return 1;
}
int LuaScriptInterface::luaDatabaseLastInsertId(lua_State* L)
{
lua_pushnumber(L, Database::getInstance().getLastInsertId());
return 1;
}
int LuaScriptInterface::luaDatabaseTableExists(lua_State* L)
{
pushBoolean(L, DatabaseManager::tableExists(getString(L, -1)));
return 1;
}
const luaL_Reg LuaScriptInterface::luaResultTable[] = {
{"getNumber", LuaScriptInterface::luaResultGetNumber},
{"getString", LuaScriptInterface::luaResultGetString},
{"getStream", LuaScriptInterface::luaResultGetStream},
{"next", LuaScriptInterface::luaResultNext},
{"free", LuaScriptInterface::luaResultFree},
{nullptr, nullptr}
};
int LuaScriptInterface::luaResultGetNumber(lua_State* L)
{
DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1));
if (!res) {
pushBoolean(L, false);
return 1;
}
const std::string& s = getString(L, 2);
lua_pushnumber(L, res->getNumber<int64_t>(s));
return 1;
}
int LuaScriptInterface::luaResultGetString(lua_State* L)
{
DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1));
if (!res) {
pushBoolean(L, false);
return 1;
}
const std::string& s = getString(L, 2);
pushString(L, res->getString(s));
return 1;
}
int LuaScriptInterface::luaResultGetStream(lua_State* L)
{
DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1));
if (!res) {
pushBoolean(L, false);
return 1;
}
unsigned long length;
const char* stream = res->getStream(getString(L, 2), length);
lua_pushlstring(L, stream, length);
lua_pushnumber(L, length);
return 2;
}
int LuaScriptInterface::luaResultNext(lua_State* L)
{
DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, -1));
if (!res) {
pushBoolean(L, false);
return 1;
}
pushBoolean(L, res->next());
return 1;
}
int LuaScriptInterface::luaResultFree(lua_State* L)
{
pushBoolean(L, ScriptEnvironment::removeResult(getNumber<uint32_t>(L, -1)));
return 1;
}
// Userdata
int LuaScriptInterface::luaUserdataCompare(lua_State* L)
{
// userdataA == userdataB
pushBoolean(L, getUserdata<void>(L, 1) == getUserdata<void>(L, 2));
return 1;
}
// _G
int LuaScriptInterface::luaIsType(lua_State* L)
{
// isType(derived, base)
lua_getmetatable(L, -2);
lua_getmetatable(L, -2);
lua_rawgeti(L, -2, 'p');
uint_fast8_t parentsB = getNumber<uint_fast8_t>(L, 1);
lua_rawgeti(L, -3, 'h');
size_t hashB = getNumber<size_t>(L, 1);
lua_rawgeti(L, -3, 'p');
uint_fast8_t parentsA = getNumber<uint_fast8_t>(L, 1);
for (uint_fast8_t i = parentsA; i < parentsB; ++i) {
lua_getfield(L, -3, "__index");
lua_replace(L, -4);
}
lua_rawgeti(L, -4, 'h');
size_t hashA = getNumber<size_t>(L, 1);
pushBoolean(L, hashA == hashB);
return 1;
}
int LuaScriptInterface::luaRawGetMetatable(lua_State* L)
{
// rawgetmetatable(metatableName)
luaL_getmetatable(L, getString(L, 1).c_str());
return 1;
}
// os
int LuaScriptInterface::luaSystemTime(lua_State* L)
{
// os.mtime()
lua_pushnumber(L, OTSYS_TIME());
return 1;
}
// table
int LuaScriptInterface::luaTableCreate(lua_State* L)
{
// table.create(arrayLength, keyLength)
lua_createtable(L, getNumber<int32_t>(L, 1), getNumber<int32_t>(L, 2));
return 1;
}
// Game
int LuaScriptInterface::luaGameGetSpectators(lua_State* L)
{
// Game.getSpectators(position[, multifloor = false[, onlyPlayer = false[, minRangeX = 0[, maxRangeX = 0[, minRangeY = 0[, maxRangeY = 0]]]]]])
const Position& position = getPosition(L, 1);
bool multifloor = getBoolean(L, 2, false);
bool onlyPlayers = getBoolean(L, 3, false);
int32_t minRangeX = getNumber<int32_t>(L, 4, 0);
int32_t maxRangeX = getNumber<int32_t>(L, 5, 0);
int32_t minRangeY = getNumber<int32_t>(L, 6, 0);
int32_t maxRangeY = getNumber<int32_t>(L, 7, 0);
SpectatorHashSet spectators;
g_game.map.getSpectators(spectators, position, multifloor, onlyPlayers, minRangeX, maxRangeX, minRangeY, maxRangeY);
lua_createtable(L, spectators.size(), 0);
int index = 0;
for (Creature* creature : spectators) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGameGetPlayers(lua_State* L)
{
// Game.getPlayers()
lua_createtable(L, g_game.getPlayersOnline(), 0);
int index = 0;
for (const auto& playerEntry : g_game.getPlayers()) {
pushUserdata<Player>(L, playerEntry.second);
setMetatable(L, -1, "Player");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGameLoadMap(lua_State* L)
{
// Game.loadMap(path)
const std::string& path = getString(L, 1);
g_dispatcher.addTask(createTask(std::bind(&Game::loadMap, &g_game, path)));
return 0;
}
int LuaScriptInterface::luaGameGetExperienceStage(lua_State* L)
{
// Game.getExperienceStage(level)
uint32_t level = getNumber<uint32_t>(L, 1);
lua_pushnumber(L, g_game.getExperienceStage(level));
return 1;
}
int LuaScriptInterface::luaGameGetMonsterCount(lua_State* L)
{
// Game.getMonsterCount()
lua_pushnumber(L, g_game.getMonstersOnline());
return 1;
}
int LuaScriptInterface::luaGameGetPlayerCount(lua_State* L)
{
// Game.getPlayerCount()
lua_pushnumber(L, g_game.getPlayersOnline());
return 1;
}
int LuaScriptInterface::luaGameGetNpcCount(lua_State* L)
{
// Game.getNpcCount()
lua_pushnumber(L, g_game.getNpcsOnline());
return 1;
}
int LuaScriptInterface::luaGameGetTowns(lua_State* L)
{
// Game.getTowns()
const auto& towns = g_game.map.towns.getTowns();
lua_createtable(L, towns.size(), 0);
int index = 0;
for (auto townEntry : towns) {
pushUserdata<Town>(L, townEntry.second);
setMetatable(L, -1, "Town");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGameGetHouses(lua_State* L)
{
// Game.getHouses()
const auto& houses = g_game.map.houses.getHouses();
lua_createtable(L, houses.size(), 0);
int index = 0;
for (auto houseEntry : houses) {
pushUserdata<House>(L, houseEntry.second);
setMetatable(L, -1, "House");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGameGetGameState(lua_State* L)
{
// Game.getGameState()
lua_pushnumber(L, g_game.getGameState());
return 1;
}
int LuaScriptInterface::luaGameSetGameState(lua_State* L)
{
// Game.setGameState(state)
GameState_t state = getNumber<GameState_t>(L, 1);
g_game.setGameState(state);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaGameGetWorldType(lua_State* L)
{
// Game.getWorldType()
lua_pushnumber(L, g_game.getWorldType());
return 1;
}
int LuaScriptInterface::luaGameSetWorldType(lua_State* L)
{
// Game.setWorldType(type)
WorldType_t type = getNumber<WorldType_t>(L, 1);
g_game.setWorldType(type);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaGameGetReturnMessage(lua_State* L)
{
// Game.getReturnMessage(value)
ReturnValue value = getNumber<ReturnValue>(L, 1);
pushString(L, getReturnMessage(value));
return 1;
}
int LuaScriptInterface::luaGameCreateItem(lua_State* L)
{
// Game.createItem(itemId[, count[, position]])
uint16_t count = getNumber<uint16_t>(L, 2, 1);
uint16_t id;
if (isNumber(L, 1)) {
id = getNumber<uint16_t>(L, 1);
} else {
id = Item::items.getItemIdByName(getString(L, 1));
if (id == 0) {
lua_pushnil(L);
return 1;
}
}
const ItemType& it = Item::items[id];
if (it.stackable) {
count = std::min<uint16_t>(count, 100);
}
Item* item = Item::CreateItem(id, count);
if (!item) {
lua_pushnil(L);
return 1;
}
if (lua_gettop(L) >= 3) {
const Position& position = getPosition(L, 3);
Tile* tile = g_game.map.getTile(position);
if (!tile) {
delete item;
lua_pushnil(L);
return 1;
}
g_game.internalAddItem(tile, item, INDEX_WHEREEVER, FLAG_NOLIMIT);
} else {
getScriptEnv()->addTempItem(item);
item->setParent(VirtualCylinder::virtualCylinder);
}
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
return 1;
}
int LuaScriptInterface::luaGameCreateContainer(lua_State* L)
{
// Game.createContainer(itemId, size[, position])
uint16_t size = getNumber<uint16_t>(L, 2);
uint16_t id;
if (isNumber(L, 1)) {
id = getNumber<uint16_t>(L, 1);
} else {
id = Item::items.getItemIdByName(getString(L, 1));
if (id == 0) {
lua_pushnil(L);
return 1;
}
}
Container* container = Item::CreateItemAsContainer(id, size);
if (!container) {
lua_pushnil(L);
return 1;
}
if (lua_gettop(L) >= 3) {
const Position& position = getPosition(L, 3);
Tile* tile = g_game.map.getTile(position);
if (!tile) {
delete container;
lua_pushnil(L);
return 1;
}
g_game.internalAddItem(tile, container, INDEX_WHEREEVER, FLAG_NOLIMIT);
} else {
getScriptEnv()->addTempItem(container);
container->setParent(VirtualCylinder::virtualCylinder);
}
pushUserdata<Container>(L, container);
setMetatable(L, -1, "Container");
return 1;
}
int LuaScriptInterface::luaGameCreateMonster(lua_State* L)
{
// Game.createMonster(monsterName, position[, extended = false[, force = false]])
Monster* monster = Monster::createMonster(getString(L, 1));
if (!monster) {
lua_pushnil(L);
return 1;
}
const Position& position = getPosition(L, 2);
bool extended = getBoolean(L, 3, false);
bool force = getBoolean(L, 4, false);
if (g_game.placeCreature(monster, position, extended, force)) {
pushUserdata<Monster>(L, monster);
setMetatable(L, -1, "Monster");
} else {
delete monster;
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGameCreateNpc(lua_State* L)
{
// Game.createNpc(npcName, position[, extended = false[, force = false]])
Npc* npc = Npc::createNpc(getString(L, 1));
if (!npc) {
lua_pushnil(L);
return 1;
}
const Position& position = getPosition(L, 2);
bool extended = getBoolean(L, 3, false);
bool force = getBoolean(L, 4, false);
if (g_game.placeCreature(npc, position, extended, force)) {
pushUserdata<Npc>(L, npc);
setMetatable(L, -1, "Npc");
} else {
delete npc;
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGameCreateTile(lua_State* L)
{
// Game.createTile(x, y, z[, isDynamic = false])
// Game.createTile(position[, isDynamic = false])
Position position;
bool isDynamic;
if (isTable(L, 1)) {
position = getPosition(L, 1);
isDynamic = getBoolean(L, 2, false);
} else {
position.x = getNumber<uint16_t>(L, 1);
position.y = getNumber<uint16_t>(L, 2);
position.z = getNumber<uint16_t>(L, 3);
isDynamic = getBoolean(L, 4, false);
}
Tile* tile = g_game.map.getTile(position);
if (!tile) {
if (isDynamic) {
tile = new DynamicTile(position.x, position.y, position.z);
} else {
tile = new StaticTile(position.x, position.y, position.z);
}
g_game.map.setTile(position, tile);
}
pushUserdata(L, tile);
setMetatable(L, -1, "Tile");
return 1;
}
int LuaScriptInterface::luaGameStartRaid(lua_State* L)
{
// Game.startRaid(raidName)
const std::string& raidName = getString(L, 1);
Raid* raid = g_game.raids.getRaidByName(raidName);
if (raid) {
raid->startRaid();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
// Variant
int LuaScriptInterface::luaVariantCreate(lua_State* L)
{
// Variant(number or string or position or thing)
LuaVariant variant;
if (isUserdata(L, 2)) {
if (Thing* thing = getThing(L, 2)) {
variant.type = VARIANT_TARGETPOSITION;
variant.pos = thing->getPosition();
}
} else if (isTable(L, 2)) {
variant.type = VARIANT_POSITION;
variant.pos = getPosition(L, 2);
} else if (isNumber(L, 2)) {
variant.type = VARIANT_NUMBER;
variant.number = getNumber<uint32_t>(L, 2);
} else if (isString(L, 2)) {
variant.type = VARIANT_STRING;
variant.text = getString(L, 2);
}
pushVariant(L, variant);
return 1;
}
int LuaScriptInterface::luaVariantGetNumber(lua_State* L)
{
// Variant:getNumber()
const LuaVariant& variant = getVariant(L, 1);
if (variant.type == VARIANT_NUMBER) {
lua_pushnumber(L, variant.number);
} else {
lua_pushnumber(L, 0);
}
return 1;
}
int LuaScriptInterface::luaVariantGetString(lua_State* L)
{
// Variant:getString()
const LuaVariant& variant = getVariant(L, 1);
if (variant.type == VARIANT_STRING) {
pushString(L, variant.text);
} else {
pushString(L, std::string());
}
return 1;
}
int LuaScriptInterface::luaVariantGetPosition(lua_State* L)
{
// Variant:getPosition()
const LuaVariant& variant = getVariant(L, 1);
if (variant.type == VARIANT_POSITION || variant.type == VARIANT_TARGETPOSITION) {
pushPosition(L, variant.pos);
} else {
pushPosition(L, Position());
}
return 1;
}
// Position
int LuaScriptInterface::luaPositionCreate(lua_State* L)
{
// Position([x = 0[, y = 0[, z = 0[, stackpos = 0]]]])
// Position([position])
if (lua_gettop(L) <= 1) {
pushPosition(L, Position());
return 1;
}
int32_t stackpos;
if (isTable(L, 2)) {
const Position& position = getPosition(L, 2, stackpos);
pushPosition(L, position, stackpos);
} else {
uint16_t x = getNumber<uint16_t>(L, 2, 0);
uint16_t y = getNumber<uint16_t>(L, 3, 0);
uint8_t z = getNumber<uint8_t>(L, 4, 0);
stackpos = getNumber<int32_t>(L, 5, 0);
pushPosition(L, Position(x, y, z), stackpos);
}
return 1;
}
int LuaScriptInterface::luaPositionAdd(lua_State* L)
{
// positionValue = position + positionEx
int32_t stackpos;
const Position& position = getPosition(L, 1, stackpos);
Position positionEx;
if (stackpos == 0) {
positionEx = getPosition(L, 2, stackpos);
} else {
positionEx = getPosition(L, 2);
}
pushPosition(L, position + positionEx, stackpos);
return 1;
}
int LuaScriptInterface::luaPositionSub(lua_State* L)
{
// positionValue = position - positionEx
int32_t stackpos;
const Position& position = getPosition(L, 1, stackpos);
Position positionEx;
if (stackpos == 0) {
positionEx = getPosition(L, 2, stackpos);
} else {
positionEx = getPosition(L, 2);
}
pushPosition(L, position - positionEx, stackpos);
return 1;
}
int LuaScriptInterface::luaPositionCompare(lua_State* L)
{
// position == positionEx
const Position& positionEx = getPosition(L, 2);
const Position& position = getPosition(L, 1);
pushBoolean(L, position == positionEx);
return 1;
}
int LuaScriptInterface::luaPositionGetDistance(lua_State* L)
{
// position:getDistance(positionEx)
const Position& positionEx = getPosition(L, 2);
const Position& position = getPosition(L, 1);
lua_pushnumber(L, std::max<int32_t>(
std::max<int32_t>(
std::abs(Position::getDistanceX(position, positionEx)),
std::abs(Position::getDistanceY(position, positionEx))
),
std::abs(Position::getDistanceZ(position, positionEx))
));
return 1;
}
int LuaScriptInterface::luaPositionIsSightClear(lua_State* L)
{
// position:isSightClear(positionEx[, sameFloor = true])
bool sameFloor = getBoolean(L, 3, true);
const Position& positionEx = getPosition(L, 2);
const Position& position = getPosition(L, 1);
pushBoolean(L, g_game.isSightClear(position, positionEx, sameFloor));
return 1;
}
int LuaScriptInterface::luaPositionSendMagicEffect(lua_State* L)
{
// position:sendMagicEffect(magicEffect[, player = nullptr])
SpectatorHashSet spectators;
if (lua_gettop(L) >= 3) {
Player* player = getPlayer(L, 3);
if (player) {
spectators.insert(player);
}
}
MagicEffectClasses magicEffect = getNumber<MagicEffectClasses>(L, 2);
const Position& position = getPosition(L, 1);
if (!spectators.empty()) {
Game::addMagicEffect(spectators, position, magicEffect);
} else {
g_game.addMagicEffect(position, magicEffect);
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPositionSendDistanceEffect(lua_State* L)
{
// position:sendDistanceEffect(positionEx, distanceEffect[, player = nullptr])
SpectatorHashSet spectators;
if (lua_gettop(L) >= 4) {
Player* player = getPlayer(L, 4);
if (player) {
spectators.insert(player);
}
}
ShootType_t distanceEffect = getNumber<ShootType_t>(L, 3);
const Position& positionEx = getPosition(L, 2);
const Position& position = getPosition(L, 1);
if (!spectators.empty()) {
Game::addDistanceEffect(spectators, position, positionEx, distanceEffect);
} else {
g_game.addDistanceEffect(position, positionEx, distanceEffect);
}
pushBoolean(L, true);
return 1;
}
// Tile
int LuaScriptInterface::luaTileCreate(lua_State* L)
{
// Tile(x, y, z)
// Tile(position)
Tile* tile;
if (isTable(L, 2)) {
tile = g_game.map.getTile(getPosition(L, 2));
} else {
uint8_t z = getNumber<uint8_t>(L, 4);
uint16_t y = getNumber<uint16_t>(L, 3);
uint16_t x = getNumber<uint16_t>(L, 2);
tile = g_game.map.getTile(x, y, z);
}
if (tile) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetPosition(lua_State* L)
{
// tile:getPosition()
Tile* tile = getUserdata<Tile>(L, 1);
if (tile) {
pushPosition(L, tile->getPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetGround(lua_State* L)
{
// tile:getGround()
Tile* tile = getUserdata<Tile>(L, 1);
if (tile && tile->getGround()) {
pushUserdata<Item>(L, tile->getGround());
setItemMetatable(L, -1, tile->getGround());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetThing(lua_State* L)
{
// tile:getThing(index)
int32_t index = getNumber<int32_t>(L, 2);
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Thing* thing = tile->getThing(index);
if (!thing) {
lua_pushnil(L);
return 1;
}
if (Creature* creature = thing->getCreature()) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else if (Item* item = thing->getItem()) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetThingCount(lua_State* L)
{
// tile:getThingCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (tile) {
lua_pushnumber(L, tile->getThingCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopVisibleThing(lua_State* L)
{
// tile:getTopVisibleThing(creature)
Creature* creature = getCreature(L, 2);
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Thing* thing = tile->getTopVisibleThing(creature);
if (!thing) {
lua_pushnil(L);
return 1;
}
if (Creature* visibleCreature = thing->getCreature()) {
pushUserdata<Creature>(L, visibleCreature);
setCreatureMetatable(L, -1, visibleCreature);
} else if (Item* visibleItem = thing->getItem()) {
pushUserdata<Item>(L, visibleItem);
setItemMetatable(L, -1, visibleItem);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopTopItem(lua_State* L)
{
// tile:getTopTopItem()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Item* item = tile->getTopTopItem();
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopDownItem(lua_State* L)
{
// tile:getTopDownItem()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Item* item = tile->getTopDownItem();
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetFieldItem(lua_State* L)
{
// tile:getFieldItem()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Item* item = tile->getFieldItem();
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetItemById(lua_State* L)
{
// tile:getItemById(itemId[, subType = -1])
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
Item* item = g_game.findItemOfType(tile, itemId, false, subType);
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetItemByType(lua_State* L)
{
// tile:getItemByType(itemType)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
bool found;
ItemTypes_t itemType = getNumber<ItemTypes_t>(L, 2);
switch (itemType) {
case ITEM_TYPE_TELEPORT:
found = tile->hasFlag(TILESTATE_TELEPORT);
break;
case ITEM_TYPE_MAGICFIELD:
found = tile->hasFlag(TILESTATE_MAGICFIELD);
break;
case ITEM_TYPE_MAILBOX:
found = tile->hasFlag(TILESTATE_MAILBOX);
break;
case ITEM_TYPE_TRASHHOLDER:
found = tile->hasFlag(TILESTATE_TRASHHOLDER);
break;
case ITEM_TYPE_BED:
found = tile->hasFlag(TILESTATE_BED);
break;
case ITEM_TYPE_DEPOT:
found = tile->hasFlag(TILESTATE_DEPOT);
break;
default:
found = true;
break;
}
if (!found) {
lua_pushnil(L);
return 1;
}
if (Item* item = tile->getGround()) {
const ItemType& it = Item::items[item->getID()];
if (it.type == itemType) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
return 1;
}
}
if (const TileItemVector* items = tile->getItemList()) {
for (Item* item : *items) {
const ItemType& it = Item::items[item->getID()];
if (it.type == itemType) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
return 1;
}
}
}
lua_pushnil(L);
return 1;
}
int LuaScriptInterface::luaTileGetItemByTopOrder(lua_State* L)
{
// tile:getItemByTopOrder(topOrder)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
int32_t topOrder = getNumber<int32_t>(L, 2);
Item* item = tile->getItemByTopOrder(topOrder);
if (!item) {
lua_pushnil(L);
return 1;
}
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
return 1;
}
int LuaScriptInterface::luaTileGetItemCountById(lua_State* L)
{
// tile:getItemCountById(itemId[, subType = -1])
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
lua_pushnumber(L, tile->getItemTypeCount(itemId, subType));
return 1;
}
int LuaScriptInterface::luaTileGetBottomCreature(lua_State* L)
{
// tile:getBottomCreature()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
const Creature* creature = tile->getBottomCreature();
if (!creature) {
lua_pushnil(L);
return 1;
}
pushUserdata<const Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
return 1;
}
int LuaScriptInterface::luaTileGetTopCreature(lua_State* L)
{
// tile:getTopCreature()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Creature* creature = tile->getTopCreature();
if (!creature) {
lua_pushnil(L);
return 1;
}
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
return 1;
}
int LuaScriptInterface::luaTileGetBottomVisibleCreature(lua_State* L)
{
// tile:getBottomVisibleCreature(creature)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Creature* creature = getCreature(L, 2);
if (!creature) {
lua_pushnil(L);
return 1;
}
const Creature* visibleCreature = tile->getBottomVisibleCreature(creature);
if (visibleCreature) {
pushUserdata<const Creature>(L, visibleCreature);
setCreatureMetatable(L, -1, visibleCreature);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopVisibleCreature(lua_State* L)
{
// tile:getTopVisibleCreature(creature)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Creature* creature = getCreature(L, 2);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* visibleCreature = tile->getTopVisibleCreature(creature);
if (visibleCreature) {
pushUserdata<Creature>(L, visibleCreature);
setCreatureMetatable(L, -1, visibleCreature);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetItems(lua_State* L)
{
// tile:getItems()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
TileItemVector* itemVector = tile->getItemList();
if (!itemVector) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, itemVector->size(), 0);
int index = 0;
for (Item* item : *itemVector) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaTileGetItemCount(lua_State* L)
{
// tile:getItemCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, tile->getItemCount());
return 1;
}
int LuaScriptInterface::luaTileGetDownItemCount(lua_State* L)
{
// tile:getDownItemCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (tile) {
lua_pushnumber(L, tile->getDownItemCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetTopItemCount(lua_State* L)
{
// tile:getTopItemCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, tile->getTopItemCount());
return 1;
}
int LuaScriptInterface::luaTileGetCreatures(lua_State* L)
{
// tile:getCreatures()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
CreatureVector* creatureVector = tile->getCreatures();
if (!creatureVector) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, creatureVector->size(), 0);
int index = 0;
for (Creature* creature : *creatureVector) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaTileGetCreatureCount(lua_State* L)
{
// tile:getCreatureCount()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, tile->getCreatureCount());
return 1;
}
int LuaScriptInterface::luaTileHasProperty(lua_State* L)
{
// tile:hasProperty(property[, item])
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Item* item;
if (lua_gettop(L) >= 3) {
item = getUserdata<Item>(L, 3);
} else {
item = nullptr;
}
ITEMPROPERTY property = getNumber<ITEMPROPERTY>(L, 2);
if (item) {
pushBoolean(L, tile->hasProperty(item, property));
} else {
pushBoolean(L, tile->hasProperty(property));
}
return 1;
}
int LuaScriptInterface::luaTileGetThingIndex(lua_State* L)
{
// tile:getThingIndex(thing)
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Thing* thing = getThing(L, 2);
if (thing) {
lua_pushnumber(L, tile->getThingIndex(thing));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileHasFlag(lua_State* L)
{
// tile:hasFlag(flag)
Tile* tile = getUserdata<Tile>(L, 1);
if (tile) {
tileflags_t flag = getNumber<tileflags_t>(L, 2);
pushBoolean(L, tile->hasFlag(flag));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileQueryAdd(lua_State* L)
{
// tile:queryAdd(thing[, flags])
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
Thing* thing = getThing(L, 2);
if (thing) {
uint32_t flags = getNumber<uint32_t>(L, 3, 0);
lua_pushnumber(L, tile->queryAdd(0, *thing, 1, flags));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTileGetHouse(lua_State* L)
{
// tile:getHouse()
Tile* tile = getUserdata<Tile>(L, 1);
if (!tile) {
lua_pushnil(L);
return 1;
}
if (HouseTile* houseTile = dynamic_cast<HouseTile*>(tile)) {
pushUserdata<House>(L, houseTile->getHouse());
setMetatable(L, -1, "House");
} else {
lua_pushnil(L);
}
return 1;
}
// NetworkMessage
int LuaScriptInterface::luaNetworkMessageCreate(lua_State* L)
{
// NetworkMessage()
pushUserdata<NetworkMessage>(L, new NetworkMessage);
setMetatable(L, -1, "NetworkMessage");
return 1;
}
int LuaScriptInterface::luaNetworkMessageDelete(lua_State* L)
{
NetworkMessage** messagePtr = getRawUserdata<NetworkMessage>(L, 1);
if (messagePtr && *messagePtr) {
delete *messagePtr;
*messagePtr = nullptr;
}
return 0;
}
int LuaScriptInterface::luaNetworkMessageGetByte(lua_State* L)
{
// networkMessage:getByte()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
lua_pushnumber(L, message->getByte());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetU16(lua_State* L)
{
// networkMessage:getU16()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
lua_pushnumber(L, message->get<uint16_t>());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetU32(lua_State* L)
{
// networkMessage:getU32()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
lua_pushnumber(L, message->get<uint32_t>());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetU64(lua_State* L)
{
// networkMessage:getU64()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
lua_pushnumber(L, message->get<uint64_t>());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetString(lua_State* L)
{
// networkMessage:getString()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
pushString(L, message->getString());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageGetPosition(lua_State* L)
{
// networkMessage:getPosition()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
pushPosition(L, message->getPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddByte(lua_State* L)
{
// networkMessage:addByte(number)
uint8_t number = getNumber<uint8_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addByte(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddU16(lua_State* L)
{
// networkMessage:addU16(number)
uint16_t number = getNumber<uint16_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->add<uint16_t>(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddU32(lua_State* L)
{
// networkMessage:addU32(number)
uint32_t number = getNumber<uint32_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->add<uint32_t>(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddU64(lua_State* L)
{
// networkMessage:addU64(number)
uint64_t number = getNumber<uint64_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->add<uint64_t>(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddString(lua_State* L)
{
// networkMessage:addString(string)
const std::string& string = getString(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addString(string);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddPosition(lua_State* L)
{
// networkMessage:addPosition(position)
const Position& position = getPosition(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addPosition(position);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddDouble(lua_State* L)
{
// networkMessage:addDouble(number)
double number = getNumber<double>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addDouble(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddItem(lua_State* L)
{
// networkMessage:addItem(item)
Item* item = getUserdata<Item>(L, 2);
if (!item) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
lua_pushnil(L);
return 1;
}
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->addItem(item);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageAddItemId(lua_State* L)
{
// networkMessage:addItemId(itemId)
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (!message) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
message->addItemId(itemId);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaNetworkMessageReset(lua_State* L)
{
// networkMessage:reset()
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->reset();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageSkipBytes(lua_State* L)
{
// networkMessage:skipBytes(number)
int16_t number = getNumber<int16_t>(L, 2);
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (message) {
message->skipBytes(number);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNetworkMessageSendToPlayer(lua_State* L)
{
// networkMessage:sendToPlayer(player)
NetworkMessage* message = getUserdata<NetworkMessage>(L, 1);
if (!message) {
lua_pushnil(L);
return 1;
}
Player* player = getPlayer(L, 2);
if (player) {
player->sendNetworkMessage(*message);
pushBoolean(L, true);
} else {
reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
lua_pushnil(L);
}
return 1;
}
// ModalWindow
int LuaScriptInterface::luaModalWindowCreate(lua_State* L)
{
// ModalWindow(id, title, message)
const std::string& message = getString(L, 4);
const std::string& title = getString(L, 3);
uint32_t id = getNumber<uint32_t>(L, 2);
pushUserdata<ModalWindow>(L, new ModalWindow(id, title, message));
setMetatable(L, -1, "ModalWindow");
return 1;
}
int LuaScriptInterface::luaModalWindowDelete(lua_State* L)
{
ModalWindow** windowPtr = getRawUserdata<ModalWindow>(L, 1);
if (windowPtr && *windowPtr) {
delete *windowPtr;
*windowPtr = nullptr;
}
return 0;
}
int LuaScriptInterface::luaModalWindowGetId(lua_State* L)
{
// modalWindow:getId()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->id);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetTitle(lua_State* L)
{
// modalWindow:getTitle()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
pushString(L, window->title);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetMessage(lua_State* L)
{
// modalWindow:getMessage()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
pushString(L, window->message);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetTitle(lua_State* L)
{
// modalWindow:setTitle(text)
const std::string& text = getString(L, 2);
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->title = text;
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetMessage(lua_State* L)
{
// modalWindow:setMessage(text)
const std::string& text = getString(L, 2);
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->message = text;
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetButtonCount(lua_State* L)
{
// modalWindow:getButtonCount()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->buttons.size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetChoiceCount(lua_State* L)
{
// modalWindow:getChoiceCount()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->choices.size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowAddButton(lua_State* L)
{
// modalWindow:addButton(id, text)
const std::string& text = getString(L, 3);
uint8_t id = getNumber<uint8_t>(L, 2);
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->buttons.emplace_back(text, id);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowAddChoice(lua_State* L)
{
// modalWindow:addChoice(id, text)
const std::string& text = getString(L, 3);
uint8_t id = getNumber<uint8_t>(L, 2);
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->choices.emplace_back(text, id);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetDefaultEnterButton(lua_State* L)
{
// modalWindow:getDefaultEnterButton()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->defaultEnterButton);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetDefaultEnterButton(lua_State* L)
{
// modalWindow:setDefaultEnterButton(buttonId)
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->defaultEnterButton = getNumber<uint8_t>(L, 2);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowGetDefaultEscapeButton(lua_State* L)
{
// modalWindow:getDefaultEscapeButton()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
lua_pushnumber(L, window->defaultEscapeButton);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetDefaultEscapeButton(lua_State* L)
{
// modalWindow:setDefaultEscapeButton(buttonId)
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->defaultEscapeButton = getNumber<uint8_t>(L, 2);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowHasPriority(lua_State* L)
{
// modalWindow:hasPriority()
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
pushBoolean(L, window->priority);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSetPriority(lua_State* L)
{
// modalWindow:setPriority(priority)
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
window->priority = getBoolean(L, 2);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaModalWindowSendToPlayer(lua_State* L)
{
// modalWindow:sendToPlayer(player)
Player* player = getPlayer(L, 2);
if (!player) {
lua_pushnil(L);
return 1;
}
ModalWindow* window = getUserdata<ModalWindow>(L, 1);
if (window) {
if (!player->hasModalWindowOpen(window->id)) {
player->sendModalWindow(*window);
}
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
// Item
int LuaScriptInterface::luaItemCreate(lua_State* L)
{
// Item(uid)
uint32_t id = getNumber<uint32_t>(L, 2);
Item* item = getScriptEnv()->getItemByUID(id);
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemIsItem(lua_State* L)
{
// item:isItem()
pushBoolean(L, getUserdata<const Item>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaItemGetParent(lua_State* L)
{
// item:getParent()
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
Cylinder* parent = item->getParent();
if (!parent) {
lua_pushnil(L);
return 1;
}
pushCylinder(L, parent);
return 1;
}
int LuaScriptInterface::luaItemGetTopParent(lua_State* L)
{
// item:getTopParent()
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
Cylinder* topParent = item->getTopParent();
if (!topParent) {
lua_pushnil(L);
return 1;
}
pushCylinder(L, topParent);
return 1;
}
int LuaScriptInterface::luaItemGetId(lua_State* L)
{
// item:getId()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getID());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemClone(lua_State* L)
{
// item:clone()
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
Item* clone = item->clone();
if (!clone) {
lua_pushnil(L);
return 1;
}
getScriptEnv()->addTempItem(clone);
clone->setParent(VirtualCylinder::virtualCylinder);
pushUserdata<Item>(L, clone);
setItemMetatable(L, -1, clone);
return 1;
}
int LuaScriptInterface::luaItemSplit(lua_State* L)
{
// item:split([count = 1])
Item** itemPtr = getRawUserdata<Item>(L, 1);
if (!itemPtr) {
lua_pushnil(L);
return 1;
}
Item* item = *itemPtr;
if (!item || !item->isStackable()) {
lua_pushnil(L);
return 1;
}
uint16_t count = std::min<uint16_t>(getNumber<uint16_t>(L, 2, 1), item->getItemCount());
uint16_t diff = item->getItemCount() - count;
Item* splitItem = item->clone();
if (!splitItem) {
lua_pushnil(L);
return 1;
}
ScriptEnvironment* env = getScriptEnv();
uint32_t uid = env->addThing(item);
Item* newItem = g_game.transformItem(item, item->getID(), diff);
if (item->isRemoved()) {
env->removeItemByUID(uid);
}
if (newItem && newItem != item) {
env->insertItem(uid, newItem);
}
*itemPtr = newItem;
splitItem->setParent(VirtualCylinder::virtualCylinder);
env->addTempItem(splitItem);
pushUserdata<Item>(L, splitItem);
setItemMetatable(L, -1, splitItem);
return 1;
}
int LuaScriptInterface::luaItemRemove(lua_State* L)
{
// item:remove([count = -1])
Item* item = getUserdata<Item>(L, 1);
if (item) {
int32_t count = getNumber<int32_t>(L, 2, -1);
pushBoolean(L, g_game.internalRemoveItem(item, count) == RETURNVALUE_NOERROR);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetUniqueId(lua_State* L)
{
// item:getUniqueId()
Item* item = getUserdata<Item>(L, 1);
if (item) {
uint32_t uniqueId = item->getUniqueId();
if (uniqueId == 0) {
uniqueId = getScriptEnv()->addThing(item);
}
lua_pushnumber(L, uniqueId);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetActionId(lua_State* L)
{
// item:getActionId()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getActionId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemSetActionId(lua_State* L)
{
// item:setActionId(actionId)
uint16_t actionId = getNumber<uint16_t>(L, 2);
Item* item = getUserdata<Item>(L, 1);
if (item) {
item->setActionId(actionId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetCount(lua_State* L)
{
// item:getCount()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getItemCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetCharges(lua_State* L)
{
// item:getCharges()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getCharges());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetFluidType(lua_State* L)
{
// item:getFluidType()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getFluidType());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetWeight(lua_State* L)
{
// item:getWeight()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getWeight());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetSubType(lua_State* L)
{
// item:getSubType()
Item* item = getUserdata<Item>(L, 1);
if (item) {
lua_pushnumber(L, item->getSubType());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetName(lua_State* L)
{
// item:getName()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushString(L, item->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetPluralName(lua_State* L)
{
// item:getPluralName()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushString(L, item->getPluralName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetArticle(lua_State* L)
{
// item:getArticle()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushString(L, item->getArticle());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetPosition(lua_State* L)
{
// item:getPosition()
Item* item = getUserdata<Item>(L, 1);
if (item) {
pushPosition(L, item->getPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetTile(lua_State* L)
{
// item:getTile()
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
Tile* tile = item->getTile();
if (tile) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemHasAttribute(lua_State* L)
{
// item:hasAttribute(key)
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
itemAttrTypes attribute;
if (isNumber(L, 2)) {
attribute = getNumber<itemAttrTypes>(L, 2);
} else if (isString(L, 2)) {
attribute = stringToItemAttribute(getString(L, 2));
} else {
attribute = ITEM_ATTRIBUTE_NONE;
}
pushBoolean(L, item->hasAttribute(attribute));
return 1;
}
int LuaScriptInterface::luaItemGetAttribute(lua_State* L)
{
// item:getAttribute(key)
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
itemAttrTypes attribute;
if (isNumber(L, 2)) {
attribute = getNumber<itemAttrTypes>(L, 2);
} else if (isString(L, 2)) {
attribute = stringToItemAttribute(getString(L, 2));
} else {
attribute = ITEM_ATTRIBUTE_NONE;
}
if (ItemAttributes::isIntAttrType(attribute)) {
lua_pushnumber(L, item->getIntAttr(attribute));
} else if (ItemAttributes::isStrAttrType(attribute)) {
pushString(L, item->getStrAttr(attribute));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemSetAttribute(lua_State* L)
{
// item:setAttribute(key, value)
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
itemAttrTypes attribute;
if (isNumber(L, 2)) {
attribute = getNumber<itemAttrTypes>(L, 2);
} else if (isString(L, 2)) {
attribute = stringToItemAttribute(getString(L, 2));
} else {
attribute = ITEM_ATTRIBUTE_NONE;
}
if (ItemAttributes::isIntAttrType(attribute)) {
if (attribute == ITEM_ATTRIBUTE_UNIQUEID) {
reportErrorFunc("Attempt to set protected key \"uid\"");
pushBoolean(L, false);
return 1;
}
item->setIntAttr(attribute, getNumber<int32_t>(L, 3));
pushBoolean(L, true);
} else if (ItemAttributes::isStrAttrType(attribute)) {
item->setStrAttr(attribute, getString(L, 3));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemRemoveAttribute(lua_State* L)
{
// item:removeAttribute(key)
Item* item = getUserdata<Item>(L, 1);
if (!item) {
lua_pushnil(L);
return 1;
}
itemAttrTypes attribute;
if (isNumber(L, 2)) {
attribute = getNumber<itemAttrTypes>(L, 2);
} else if (isString(L, 2)) {
attribute = stringToItemAttribute(getString(L, 2));
} else {
attribute = ITEM_ATTRIBUTE_NONE;
}
bool ret = attribute != ITEM_ATTRIBUTE_UNIQUEID;
if (ret) {
item->removeAttribute(attribute);
} else {
reportErrorFunc("Attempt to erase protected key \"uid\"");
}
pushBoolean(L, ret);
return 1;
}
int LuaScriptInterface::luaItemMoveTo(lua_State* L)
{
// item:moveTo(position or cylinder)
Item** itemPtr = getRawUserdata<Item>(L, 1);
if (!itemPtr) {
lua_pushnil(L);
return 1;
}
Item* item = *itemPtr;
if (!item || item->isRemoved()) {
lua_pushnil(L);
return 1;
}
Cylinder* toCylinder;
if (isUserdata(L, 2)) {
const LuaDataType type = getUserdataType(L, 2);
switch (type) {
case LuaData_Container:
toCylinder = getUserdata<Container>(L, 2);
break;
case LuaData_Player:
toCylinder = getUserdata<Player>(L, 2);
break;
case LuaData_Tile:
toCylinder = getUserdata<Tile>(L, 2);
break;
default:
toCylinder = nullptr;
break;
}
} else {
toCylinder = g_game.map.getTile(getPosition(L, 2));
}
if (!toCylinder) {
lua_pushnil(L);
return 1;
}
if (item->getParent() == toCylinder) {
pushBoolean(L, true);
return 1;
}
if (item->getParent() == VirtualCylinder::virtualCylinder) {
pushBoolean(L, g_game.internalAddItem(toCylinder, item) == RETURNVALUE_NOERROR);
} else {
Item* moveItem = nullptr;
ReturnValue ret = g_game.internalMoveItem(item->getParent(), toCylinder, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem, FLAG_NOLIMIT | FLAG_IGNOREBLOCKITEM | FLAG_IGNOREBLOCKCREATURE | FLAG_IGNORENOTMOVEABLE);
if (moveItem) {
*itemPtr = moveItem;
}
pushBoolean(L, ret == RETURNVALUE_NOERROR);
}
return 1;
}
int LuaScriptInterface::luaItemTransform(lua_State* L)
{
// item:transform(itemId[, count/subType = -1])
Item** itemPtr = getRawUserdata<Item>(L, 1);
if (!itemPtr) {
lua_pushnil(L);
return 1;
}
Item*& item = *itemPtr;
if (!item) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
if (item->getID() == itemId && (subType == -1 || subType == item->getSubType())) {
pushBoolean(L, true);
return 1;
}
const ItemType& it = Item::items[itemId];
if (it.stackable) {
subType = std::min<int32_t>(subType, 100);
}
ScriptEnvironment* env = getScriptEnv();
uint32_t uid = env->addThing(item);
Item* newItem = g_game.transformItem(item, itemId, subType);
if (item->isRemoved()) {
env->removeItemByUID(uid);
}
if (newItem && newItem != item) {
env->insertItem(uid, newItem);
}
item = newItem;
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaItemDecay(lua_State* L)
{
// item:decay()
Item* item = getUserdata<Item>(L, 1);
if (item) {
g_game.startDecay(item);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemGetDescription(lua_State* L)
{
// item:getDescription(distance)
Item* item = getUserdata<Item>(L, 1);
if (item) {
int32_t distance = getNumber<int32_t>(L, 2);
pushString(L, item->getDescription(distance));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemHasProperty(lua_State* L)
{
// item:hasProperty(property)
Item* item = getUserdata<Item>(L, 1);
if (item) {
ITEMPROPERTY property = getNumber<ITEMPROPERTY>(L, 2);
pushBoolean(L, item->hasProperty(property));
} else {
lua_pushnil(L);
}
return 1;
}
// Container
int LuaScriptInterface::luaContainerCreate(lua_State* L)
{
// Container(uid)
uint32_t id = getNumber<uint32_t>(L, 2);
Container* container = getScriptEnv()->getContainerByUID(id);
if (container) {
pushUserdata(L, container);
setMetatable(L, -1, "Container");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerGetSize(lua_State* L)
{
// container:getSize()
Container* container = getUserdata<Container>(L, 1);
if (container) {
lua_pushnumber(L, container->size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerGetCapacity(lua_State* L)
{
// container:getCapacity()
Container* container = getUserdata<Container>(L, 1);
if (container) {
lua_pushnumber(L, container->capacity());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerGetEmptySlots(lua_State* L)
{
// container:getEmptySlots([recursive = false])
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
uint32_t slots = container->capacity() - container->size();
bool recursive = getBoolean(L, 2, false);
if (recursive) {
for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) {
if (Container* tmpContainer = (*it)->getContainer()) {
slots += tmpContainer->capacity() - tmpContainer->size();
}
}
}
lua_pushnumber(L, slots);
return 1;
}
int LuaScriptInterface::luaContainerGetItemHoldingCount(lua_State* L)
{
// container:getItemHoldingCount()
Container* container = getUserdata<Container>(L, 1);
if (container) {
lua_pushnumber(L, container->getItemHoldingCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerGetItem(lua_State* L)
{
// container:getItem(index)
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
uint32_t index = getNumber<uint32_t>(L, 2);
Item* item = container->getItemByIndex(index);
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerHasItem(lua_State* L)
{
// container:hasItem(item)
Item* item = getUserdata<Item>(L, 2);
Container* container = getUserdata<Container>(L, 1);
if (container) {
pushBoolean(L, container->isHoldingItem(item));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerAddItem(lua_State* L)
{
// container:addItem(itemId[, count/subType = 1[, index = INDEX_WHEREEVER[, flags = 0]]])
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
uint32_t subType = getNumber<uint32_t>(L, 3, 1);
Item* item = Item::CreateItem(itemId, std::min<uint32_t>(subType, 100));
if (!item) {
lua_pushnil(L);
return 1;
}
int32_t index = getNumber<int32_t>(L, 4, INDEX_WHEREEVER);
uint32_t flags = getNumber<uint32_t>(L, 5, 0);
ReturnValue ret = g_game.internalAddItem(container, item, index, flags);
if (ret == RETURNVALUE_NOERROR) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
delete item;
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaContainerAddItemEx(lua_State* L)
{
// container:addItemEx(item[, index = INDEX_WHEREEVER[, flags = 0]])
Item* item = getUserdata<Item>(L, 2);
if (!item) {
lua_pushnil(L);
return 1;
}
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
if (item->getParent() != VirtualCylinder::virtualCylinder) {
reportErrorFunc("Item already has a parent");
lua_pushnil(L);
return 1;
}
int32_t index = getNumber<int32_t>(L, 3, INDEX_WHEREEVER);
uint32_t flags = getNumber<uint32_t>(L, 4, 0);
ReturnValue ret = g_game.internalAddItem(container, item, index, flags);
if (ret == RETURNVALUE_NOERROR) {
ScriptEnvironment::removeTempItem(item);
}
lua_pushnumber(L, ret);
return 1;
}
int LuaScriptInterface::luaContainerGetItemCountById(lua_State* L)
{
// container:getItemCountById(itemId[, subType = -1])
Container* container = getUserdata<Container>(L, 1);
if (!container) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
lua_pushnumber(L, container->getItemTypeCount(itemId, subType));
return 1;
}
// Teleport
int LuaScriptInterface::luaTeleportCreate(lua_State* L)
{
// Teleport(uid)
uint32_t id = getNumber<uint32_t>(L, 2);
Item* item = getScriptEnv()->getItemByUID(id);
if (item && item->getTeleport()) {
pushUserdata(L, item);
setMetatable(L, -1, "Teleport");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTeleportGetDestination(lua_State* L)
{
// teleport:getDestination()
Teleport* teleport = getUserdata<Teleport>(L, 1);
if (teleport) {
pushPosition(L, teleport->getDestPos());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTeleportSetDestination(lua_State* L)
{
// teleport:setDestination(position)
Teleport* teleport = getUserdata<Teleport>(L, 1);
if (teleport) {
teleport->setDestPos(getPosition(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
// Creature
int LuaScriptInterface::luaCreatureCreate(lua_State* L)
{
// Creature(id or name or userdata)
Creature* creature;
if (isNumber(L, 2)) {
creature = g_game.getCreatureByID(getNumber<uint32_t>(L, 2));
} else if (isString(L, 2)) {
creature = g_game.getCreatureByName(getString(L, 2));
} else if (isUserdata(L, 2)) {
LuaDataType type = getUserdataType(L, 2);
if (type != LuaData_Player && type != LuaData_Monster && type != LuaData_Npc) {
lua_pushnil(L);
return 1;
}
creature = getUserdata<Creature>(L, 2);
} else {
creature = nullptr;
}
if (creature) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetEvents(lua_State* L)
{
// creature:getEvents(type)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
CreatureEventType_t eventType = getNumber<CreatureEventType_t>(L, 2);
const auto& eventList = creature->getCreatureEvents(eventType);
lua_createtable(L, eventList.size(), 0);
int index = 0;
for (CreatureEvent* event : eventList) {
pushString(L, event->getName());
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaCreatureRegisterEvent(lua_State* L)
{
// creature:registerEvent(name)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
const std::string& name = getString(L, 2);
pushBoolean(L, creature->registerCreatureEvent(name));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureUnregisterEvent(lua_State* L)
{
// creature:unregisterEvent(name)
const std::string& name = getString(L, 2);
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
pushBoolean(L, creature->unregisterCreatureEvent(name));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureIsRemoved(lua_State* L)
{
// creature:isRemoved()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushBoolean(L, creature->isRemoved());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureIsCreature(lua_State* L)
{
// creature:isCreature()
pushBoolean(L, getUserdata<const Creature>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaCreatureIsInGhostMode(lua_State* L)
{
// creature:isInGhostMode()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushBoolean(L, creature->isInGhostMode());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureIsHealthHidden(lua_State* L)
{
// creature:isHealthHidden()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushBoolean(L, creature->isHealthHidden());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureCanSee(lua_State* L)
{
// creature:canSee(position)
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
const Position& position = getPosition(L, 2);
pushBoolean(L, creature->canSee(position));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureCanSeeCreature(lua_State* L)
{
// creature:canSeeCreature(creature)
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
const Creature* otherCreature = getCreature(L, 2);
pushBoolean(L, creature->canSeeCreature(otherCreature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetParent(lua_State* L)
{
// creature:getParent()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Cylinder* parent = creature->getParent();
if (!parent) {
lua_pushnil(L);
return 1;
}
pushCylinder(L, parent);
return 1;
}
int LuaScriptInterface::luaCreatureGetId(lua_State* L)
{
// creature:getId()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getID());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetName(lua_State* L)
{
// creature:getName()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushString(L, creature->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetTarget(lua_State* L)
{
// creature:getTarget()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* target = creature->getAttackedCreature();
if (target) {
pushUserdata<Creature>(L, target);
setCreatureMetatable(L, -1, target);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetTarget(lua_State* L)
{
// creature:setTarget(target)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
Creature* target = getCreature(L, 2);
pushBoolean(L, creature->setAttackedCreature(target));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetFollowCreature(lua_State* L)
{
// creature:getFollowCreature()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* followCreature = creature->getFollowCreature();
if (followCreature) {
pushUserdata<Creature>(L, followCreature);
setCreatureMetatable(L, -1, followCreature);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetFollowCreature(lua_State* L)
{
// creature:setFollowCreature(followedCreature)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
Creature* followCreature = getCreature(L, 2);
pushBoolean(L, creature->setFollowCreature(followCreature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetMaster(lua_State* L)
{
// creature:getMaster()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* master = creature->getMaster();
if (!master) {
lua_pushnil(L);
return 1;
}
pushUserdata<Creature>(L, master);
setCreatureMetatable(L, -1, master);
return 1;
}
int LuaScriptInterface::luaCreatureSetMaster(lua_State* L)
{
// creature:setMaster(master)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Creature* master = getCreature(L, 2);
if (master) {
pushBoolean(L, creature->convinceCreature(master));
} else {
master = creature->getMaster();
if (master) {
master->removeSummon(creature);
creature->incrementReferenceCounter();
creature->setDropLoot(true);
}
pushBoolean(L, true);
}
g_game.updateCreatureType(creature);
return 1;
}
int LuaScriptInterface::luaCreatureGetLight(lua_State* L)
{
// creature:getLight()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
LightInfo light;
creature->getCreatureLight(light);
lua_pushnumber(L, light.level);
lua_pushnumber(L, light.color);
return 2;
}
int LuaScriptInterface::luaCreatureSetLight(lua_State* L)
{
// creature:setLight(color, level)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
LightInfo light;
light.color = getNumber<uint8_t>(L, 2);
light.level = getNumber<uint8_t>(L, 3);
creature->setCreatureLight(light);
g_game.changeLight(creature);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureGetSpeed(lua_State* L)
{
// creature:getSpeed()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getSpeed());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetBaseSpeed(lua_State* L)
{
// creature:getBaseSpeed()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getBaseSpeed());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureChangeSpeed(lua_State* L)
{
// creature:changeSpeed(delta)
Creature* creature = getCreature(L, 1);
if (!creature) {
reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
int32_t delta = getNumber<int32_t>(L, 2);
g_game.changeSpeed(creature, delta);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureSetDropLoot(lua_State* L)
{
// creature:setDropLoot(doDrop)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->setDropLoot(getBoolean(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetPosition(lua_State* L)
{
// creature:getPosition()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushPosition(L, creature->getPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetTile(lua_State* L)
{
// creature:getTile()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
Tile* tile = creature->getTile();
if (tile) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetDirection(lua_State* L)
{
// creature:getDirection()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getDirection());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetDirection(lua_State* L)
{
// creature:setDirection(direction)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
pushBoolean(L, g_game.internalCreatureTurn(creature, getNumber<Direction>(L, 2)));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetHealth(lua_State* L)
{
// creature:getHealth()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getHealth());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureAddHealth(lua_State* L)
{
// creature:addHealth(healthChange)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
CombatDamage damage;
damage.primary.value = getNumber<int32_t>(L, 2);
if (damage.primary.value >= 0) {
damage.primary.type = COMBAT_HEALING;
} else {
damage.primary.type = COMBAT_UNDEFINEDDAMAGE;
}
pushBoolean(L, g_game.combatChangeHealth(nullptr, creature, damage));
return 1;
}
int LuaScriptInterface::luaCreatureGetMaxHealth(lua_State* L)
{
// creature:getMaxHealth()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getMaxHealth());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetMaxHealth(lua_State* L)
{
// creature:setMaxHealth(maxHealth)
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
creature->healthMax = getNumber<uint32_t>(L, 2);
creature->health = std::min<int32_t>(creature->health, creature->healthMax);
g_game.addCreatureHealth(creature);
Player* player = creature->getPlayer();
if (player) {
player->sendStats();
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureSetHiddenHealth(lua_State* L)
{
// creature:setHiddenHealth(hide)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->setHiddenHealth(getBoolean(L, 2));
g_game.addCreatureHealth(creature);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetMana(lua_State* L)
{
// creature:getMana()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getMana());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureAddMana(lua_State* L)
{
// creature:addMana(manaChange[, animationOnLoss = false])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
int32_t manaChange = getNumber<int32_t>(L, 2);
bool animationOnLoss = getBoolean(L, 3, false);
if (!animationOnLoss && manaChange < 0) {
creature->changeMana(manaChange);
} else {
g_game.combatChangeMana(nullptr, creature, manaChange, ORIGIN_NONE);
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureGetMaxMana(lua_State* L)
{
// creature:getMaxMana()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getMaxMana());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetSkull(lua_State* L)
{
// creature:getSkull()
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
lua_pushnumber(L, creature->getSkull());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetSkull(lua_State* L)
{
// creature:setSkull(skull)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->setSkull(getNumber<Skulls_t>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetOutfit(lua_State* L)
{
// creature:getOutfit()
const Creature* creature = getUserdata<const Creature>(L, 1);
if (creature) {
pushOutfit(L, creature->getCurrentOutfit());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureSetOutfit(lua_State* L)
{
// creature:setOutfit(outfit)
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
creature->defaultOutfit = getOutfit(L, 2);
g_game.internalCreatureChangeOutfit(creature, creature->defaultOutfit);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetCondition(lua_State* L)
{
// creature:getCondition(conditionType[, conditionId = CONDITIONID_COMBAT[, subId = 0]])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2);
ConditionId_t conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT);
uint32_t subId = getNumber<uint32_t>(L, 4, 0);
Condition* condition = creature->getCondition(conditionType, conditionId, subId);
if (condition) {
pushUserdata<Condition>(L, condition);
setWeakMetatable(L, -1, "Condition");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureAddCondition(lua_State* L)
{
// creature:addCondition(condition[, force = false])
Creature* creature = getUserdata<Creature>(L, 1);
Condition* condition = getUserdata<Condition>(L, 2);
if (creature && condition) {
bool force = getBoolean(L, 3, false);
pushBoolean(L, creature->addCondition(condition->clone(), force));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureRemoveCondition(lua_State* L)
{
// creature:removeCondition(conditionType[, conditionId = CONDITIONID_COMBAT[, subId = 0[, force = false]]])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2);
ConditionId_t conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT);
uint32_t subId = getNumber<uint32_t>(L, 4, 0);
Condition* condition = creature->getCondition(conditionType, conditionId, subId);
if (condition) {
bool force = getBoolean(L, 5, false);
creature->removeCondition(condition, force);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureRemove(lua_State* L)
{
// creature:remove()
Creature** creaturePtr = getRawUserdata<Creature>(L, 1);
if (!creaturePtr) {
lua_pushnil(L);
return 1;
}
Creature* creature = *creaturePtr;
if (!creature) {
lua_pushnil(L);
return 1;
}
Player* player = creature->getPlayer();
if (player) {
player->kickPlayer(true);
} else {
g_game.removeCreature(creature);
}
*creaturePtr = nullptr;
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureTeleportTo(lua_State* L)
{
// creature:teleportTo(position[, pushMovement = false])
bool pushMovement = getBoolean(L, 3, false);
const Position& position = getPosition(L, 2);
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
const Position oldPosition = creature->getPosition();
if (g_game.internalTeleport(creature, position, pushMovement) != RETURNVALUE_NOERROR) {
pushBoolean(L, false);
return 1;
}
if (!pushMovement) {
if (oldPosition.x == position.x) {
if (oldPosition.y < position.y) {
g_game.internalCreatureTurn(creature, DIRECTION_SOUTH);
} else {
g_game.internalCreatureTurn(creature, DIRECTION_NORTH);
}
} else if (oldPosition.x > position.x) {
g_game.internalCreatureTurn(creature, DIRECTION_WEST);
} else if (oldPosition.x < position.x) {
g_game.internalCreatureTurn(creature, DIRECTION_EAST);
}
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCreatureSay(lua_State* L)
{
// creature:say(text, type[, ghost = false[, target = nullptr[, position]]])
int parameters = lua_gettop(L);
Position position;
if (parameters >= 6) {
position = getPosition(L, 6);
if (!position.x || !position.y) {
reportErrorFunc("Invalid position specified.");
pushBoolean(L, false);
return 1;
}
}
Creature* target = nullptr;
if (parameters >= 5) {
target = getCreature(L, 5);
}
bool ghost = getBoolean(L, 4, false);
SpeakClasses type = getNumber<SpeakClasses>(L, 3);
const std::string& text = getString(L, 2);
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
SpectatorHashSet spectators;
if (target) {
spectators.insert(target);
}
if (position.x != 0) {
pushBoolean(L, g_game.internalCreatureSay(creature, type, text, ghost, &spectators, &position));
} else {
pushBoolean(L, g_game.internalCreatureSay(creature, type, text, ghost, &spectators));
}
return 1;
}
int LuaScriptInterface::luaCreatureGetDamageMap(lua_State* L)
{
// creature:getDamageMap()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, creature->damageMap.size(), 0);
for (auto damageEntry : creature->damageMap) {
lua_createtable(L, 0, 2);
setField(L, "total", damageEntry.second.total);
setField(L, "ticks", damageEntry.second.ticks);
lua_rawseti(L, -2, damageEntry.first);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetSummons(lua_State* L)
{
// creature:getSummons()
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, creature->getSummonCount(), 0);
int index = 0;
for (Creature* summon : creature->getSummons()) {
pushUserdata<Creature>(L, summon);
setCreatureMetatable(L, -1, summon);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetDescription(lua_State* L)
{
// creature:getDescription(distance)
int32_t distance = getNumber<int32_t>(L, 2);
Creature* creature = getUserdata<Creature>(L, 1);
if (creature) {
pushString(L, creature->getDescription(distance));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCreatureGetPathTo(lua_State* L)
{
// creature:getPathTo(pos[, minTargetDist = 0[, maxTargetDist = 1[, fullPathSearch = true[, clearSight = true[, maxSearchDist = 0]]]]])
Creature* creature = getUserdata<Creature>(L, 1);
if (!creature) {
lua_pushnil(L);
return 1;
}
const Position& position = getPosition(L, 2);
FindPathParams fpp;
fpp.minTargetDist = getNumber<int32_t>(L, 3, 0);
fpp.maxTargetDist = getNumber<int32_t>(L, 4, 1);
fpp.fullPathSearch = getBoolean(L, 5, fpp.fullPathSearch);
fpp.clearSight = getBoolean(L, 6, fpp.clearSight);
fpp.maxSearchDist = getNumber<int32_t>(L, 7, fpp.maxSearchDist);
std::forward_list<Direction> dirList;
if (creature->getPathTo(position, dirList, fpp)) {
lua_newtable(L);
int index = 0;
for (Direction dir : dirList) {
lua_pushnumber(L, dir);
lua_rawseti(L, -2, ++index);
}
} else {
pushBoolean(L, false);
}
return 1;
}
// Player
int LuaScriptInterface::luaPlayerCreate(lua_State* L)
{
// Player(id or name or userdata)
Player* player;
if (isNumber(L, 2)) {
player = g_game.getPlayerByID(getNumber<uint32_t>(L, 2));
} else if (isString(L, 2)) {
ReturnValue ret = g_game.getPlayerByNameWildcard(getString(L, 2), player);
if (ret != RETURNVALUE_NOERROR) {
lua_pushnil(L);
lua_pushnumber(L, ret);
return 2;
}
} else if (isUserdata(L, 2)) {
if (getUserdataType(L, 2) != LuaData_Player) {
lua_pushnil(L);
return 1;
}
player = getUserdata<Player>(L, 2);
} else {
player = nullptr;
}
if (player) {
pushUserdata<Player>(L, player);
setMetatable(L, -1, "Player");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerIsPlayer(lua_State* L)
{
// player:isPlayer()
pushBoolean(L, getUserdata<const Player>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaPlayerGetGuid(lua_State* L)
{
// player:getGuid()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getGUID());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetIp(lua_State* L)
{
// player:getIp()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getIP());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetAccountId(lua_State* L)
{
// player:getAccountId()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getAccount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetLastLoginSaved(lua_State* L)
{
// player:getLastLoginSaved()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getLastLoginSaved());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetLastLogout(lua_State* L)
{
// player:getLastLogout()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getLastLogout());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetAccountType(lua_State* L)
{
// player:getAccountType()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getAccountType());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetAccountType(lua_State* L)
{
// player:setAccountType(accountType)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->accountType = getNumber<AccountType_t>(L, 2);
IOLoginData::setAccountType(player->getAccount(), player->accountType);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetCapacity(lua_State* L)
{
// player:getCapacity()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getCapacity());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetCapacity(lua_State* L)
{
// player:setCapacity(capacity)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->capacity = getNumber<uint32_t>(L, 2);
player->sendStats();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetFreeCapacity(lua_State* L)
{
// player:getFreeCapacity()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getFreeCapacity());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetDepotChest(lua_State* L)
{
// player:getDepotChest(depotId[, autoCreate = false])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint32_t depotId = getNumber<uint32_t>(L, 2);
bool autoCreate = getBoolean(L, 3, false);
DepotChest* depotChest = player->getDepotChest(depotId, autoCreate);
if (depotChest) {
pushUserdata<Item>(L, depotChest);
setItemMetatable(L, -1, depotChest);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetInbox(lua_State* L)
{
// player:getInbox()
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Inbox* inbox = player->getInbox();
if (inbox) {
pushUserdata<Item>(L, inbox);
setItemMetatable(L, -1, inbox);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSkullTime(lua_State* L)
{
// player:getSkullTime()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getSkullTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetSkullTime(lua_State* L)
{
// player:setSkullTime(skullTime)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setSkullTicks(getNumber<int64_t>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetDeathPenalty(lua_State* L)
{
// player:getDeathPenalty()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, static_cast<uint32_t>(player->getLostPercent() * 100));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetExperience(lua_State* L)
{
// player:getExperience()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getExperience());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddExperience(lua_State* L)
{
// player:addExperience(experience[, sendText = false])
Player* player = getUserdata<Player>(L, 1);
if (player) {
int64_t experience = getNumber<int64_t>(L, 2);
bool sendText = getBoolean(L, 3, false);
player->addExperience(nullptr, experience, sendText);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveExperience(lua_State* L)
{
// player:removeExperience(experience[, sendText = false])
Player* player = getUserdata<Player>(L, 1);
if (player) {
int64_t experience = getNumber<int64_t>(L, 2);
bool sendText = getBoolean(L, 3, false);
player->removeExperience(experience, sendText);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetLevel(lua_State* L)
{
// player:getLevel()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getLevel());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetMagicLevel(lua_State* L)
{
// player:getMagicLevel()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getMagicLevel());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetBaseMagicLevel(lua_State* L)
{
// player:getBaseMagicLevel()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getBaseMagicLevel());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetMaxMana(lua_State* L)
{
// player:setMaxMana(maxMana)
Player* player = getPlayer(L, 1);
if (player) {
player->manaMax = getNumber<int32_t>(L, 2);
player->mana = std::min<int32_t>(player->mana, player->manaMax);
player->sendStats();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetManaSpent(lua_State* L)
{
// player:getManaSpent()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getSpentMana());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddManaSpent(lua_State* L)
{
// player:addManaSpent(amount)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->addManaSpent(getNumber<uint64_t>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetBaseMaxHealth(lua_State* L)
{
// player:getBaseMaxHealth()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->healthMax);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetBaseMaxMana(lua_State* L)
{
// player:getBaseMaxMana()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->manaMax);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSkillLevel(lua_State* L)
{
// player:getSkillLevel(skillType)
skills_t skillType = getNumber<skills_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player && skillType <= SKILL_LAST) {
lua_pushnumber(L, player->skills[skillType].level);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetEffectiveSkillLevel(lua_State* L)
{
// player:getEffectiveSkillLevel(skillType)
skills_t skillType = getNumber<skills_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player && skillType <= SKILL_LAST) {
lua_pushnumber(L, player->getSkillLevel(skillType));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSkillPercent(lua_State* L)
{
// player:getSkillPercent(skillType)
skills_t skillType = getNumber<skills_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player && skillType <= SKILL_LAST) {
lua_pushnumber(L, player->skills[skillType].percent);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSkillTries(lua_State* L)
{
// player:getSkillTries(skillType)
skills_t skillType = getNumber<skills_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player && skillType <= SKILL_LAST) {
lua_pushnumber(L, player->skills[skillType].tries);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddSkillTries(lua_State* L)
{
// player:addSkillTries(skillType, tries)
Player* player = getUserdata<Player>(L, 1);
if (player) {
skills_t skillType = getNumber<skills_t>(L, 2);
uint64_t tries = getNumber<uint64_t>(L, 3);
player->addSkillAdvance(skillType, tries);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddOfflineTrainingTime(lua_State* L)
{
// player:addOfflineTrainingTime(time)
Player* player = getUserdata<Player>(L, 1);
if (player) {
int32_t time = getNumber<int32_t>(L, 2);
player->addOfflineTrainingTime(time);
player->sendStats();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetOfflineTrainingTime(lua_State* L)
{
// player:getOfflineTrainingTime()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getOfflineTrainingTime());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveOfflineTrainingTime(lua_State* L)
{
// player:removeOfflineTrainingTime(time)
Player* player = getUserdata<Player>(L, 1);
if (player) {
int32_t time = getNumber<int32_t>(L, 2);
player->removeOfflineTrainingTime(time);
player->sendStats();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddOfflineTrainingTries(lua_State* L)
{
// player:addOfflineTrainingTries(skillType, tries)
Player* player = getUserdata<Player>(L, 1);
if (player) {
skills_t skillType = getNumber<skills_t>(L, 2);
uint64_t tries = getNumber<uint64_t>(L, 3);
pushBoolean(L, player->addOfflineTrainingTries(skillType, tries));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetOfflineTrainingSkill(lua_State* L)
{
// player:getOfflineTrainingSkill()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getOfflineTrainingSkill());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetOfflineTrainingSkill(lua_State* L)
{
// player:setOfflineTrainingSkill(skillId)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint32_t skillId = getNumber<uint32_t>(L, 2);
player->setOfflineTrainingSkill(skillId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetItemCount(lua_State* L)
{
// player:getItemCount(itemId[, subType = -1])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t subType = getNumber<int32_t>(L, 3, -1);
lua_pushnumber(L, player->getItemTypeCount(itemId, subType));
return 1;
}
int LuaScriptInterface::luaPlayerGetItemById(lua_State* L)
{
// player:getItemById(itemId, deepSearch[, subType = -1])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
bool deepSearch = getBoolean(L, 3);
int32_t subType = getNumber<int32_t>(L, 4, -1);
Item* item = g_game.findItemOfType(player, itemId, deepSearch, subType);
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetVocation(lua_State* L)
{
// player:getVocation()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushUserdata<Vocation>(L, player->getVocation());
setMetatable(L, -1, "Vocation");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetVocation(lua_State* L)
{
// player:setVocation(id or name or userdata)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Vocation* vocation;
if (isNumber(L, 2)) {
vocation = g_vocations.getVocation(getNumber<uint16_t>(L, 2));
} else if (isString(L, 2)) {
vocation = g_vocations.getVocation(g_vocations.getVocationId(getString(L, 2)));
} else if (isUserdata(L, 2)) {
vocation = getUserdata<Vocation>(L, 2);
} else {
vocation = nullptr;
}
if (!vocation) {
pushBoolean(L, false);
return 1;
}
player->setVocation(vocation->getId());
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerGetSex(lua_State* L)
{
// player:getSex()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getSex());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetSex(lua_State* L)
{
// player:setSex(newSex)
Player* player = getUserdata<Player>(L, 1);
if (player) {
PlayerSex_t newSex = getNumber<PlayerSex_t>(L, 2);
player->setSex(newSex);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetTown(lua_State* L)
{
// player:getTown()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushUserdata<Town>(L, player->getTown());
setMetatable(L, -1, "Town");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetTown(lua_State* L)
{
// player:setTown(town)
Town* town = getUserdata<Town>(L, 2);
if (!town) {
pushBoolean(L, false);
return 1;
}
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setTown(town);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetGuild(lua_State* L)
{
// player:getGuild()
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Guild* guild = player->getGuild();
if (!guild) {
lua_pushnil(L);
return 1;
}
pushUserdata<Guild>(L, guild);
setMetatable(L, -1, "Guild");
return 1;
}
int LuaScriptInterface::luaPlayerSetGuild(lua_State* L)
{
// player:setGuild(guild)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
player->setGuild(getUserdata<Guild>(L, 2));
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerGetGuildLevel(lua_State* L)
{
// player:getGuildLevel()
Player* player = getUserdata<Player>(L, 1);
if (player && player->getGuild()) {
lua_pushnumber(L, player->getGuildRank()->level);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetGuildLevel(lua_State* L)
{
// player:setGuildLevel(level)
uint8_t level = getNumber<uint8_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (!player || !player->getGuild()) {
lua_pushnil(L);
return 1;
}
const GuildRank* rank = player->getGuild()->getRankByLevel(level);
if (!rank) {
pushBoolean(L, false);
} else {
player->setGuildRank(rank);
pushBoolean(L, true);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetGuildNick(lua_State* L)
{
// player:getGuildNick()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushString(L, player->getGuildNick());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetGuildNick(lua_State* L)
{
// player:setGuildNick(nick)
const std::string& nick = getString(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setGuildNick(nick);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetGroup(lua_State* L)
{
// player:getGroup()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushUserdata<Group>(L, player->getGroup());
setMetatable(L, -1, "Group");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetGroup(lua_State* L)
{
// player:setGroup(group)
Group* group = getUserdata<Group>(L, 2);
if (!group) {
pushBoolean(L, false);
return 1;
}
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setGroup(group);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetStamina(lua_State* L)
{
// player:getStamina()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getStaminaMinutes());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetStamina(lua_State* L)
{
// player:setStamina(stamina)
uint16_t stamina = getNumber<uint16_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->staminaMinutes = std::min<uint16_t>(2520, stamina);
player->sendStats();
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSoul(lua_State* L)
{
// player:getSoul()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getSoul());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddSoul(lua_State* L)
{
// player:addSoul(soulChange)
int32_t soulChange = getNumber<int32_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->changeSoul(soulChange);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetMaxSoul(lua_State* L)
{
// player:getMaxSoul()
Player* player = getUserdata<Player>(L, 1);
if (player && player->vocation) {
lua_pushnumber(L, player->vocation->getSoulMax());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetBankBalance(lua_State* L)
{
// player:getBankBalance()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getBankBalance());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetBankBalance(lua_State* L)
{
// player:setBankBalance(bankBalance)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->setBankBalance(getNumber<uint64_t>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetStorageValue(lua_State* L)
{
// player:getStorageValue(key)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint32_t key = getNumber<uint32_t>(L, 2);
int32_t value;
if (player->getStorageValue(key, value)) {
lua_pushnumber(L, value);
} else {
lua_pushnumber(L, -1);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetStorageValue(lua_State* L)
{
// player:setStorageValue(key, value)
int32_t value = getNumber<int32_t>(L, 3);
uint32_t key = getNumber<uint32_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (IS_IN_KEYRANGE(key, RESERVED_RANGE)) {
std::ostringstream ss;
ss << "Accessing reserved range: " << key;
reportErrorFunc(ss.str());
pushBoolean(L, false);
return 1;
}
if (player) {
player->addStorageValue(key, value);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddItem(lua_State* L)
{
// player:addItem(itemId[, count = 1[, canDropOnMap = true[, subType = 1[, slot = CONST_SLOT_WHEREEVER]]]])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
pushBoolean(L, false);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
int32_t count = getNumber<int32_t>(L, 3, 1);
int32_t subType = getNumber<int32_t>(L, 5, 1);
const ItemType& it = Item::items[itemId];
int32_t itemCount = 1;
int parameters = lua_gettop(L);
if (parameters >= 4) {
itemCount = std::max<int32_t>(1, count);
} else if (it.hasSubType()) {
if (it.stackable) {
itemCount = std::ceil(count / 100.f);
}
subType = count;
} else {
itemCount = std::max<int32_t>(1, count);
}
bool hasTable = itemCount > 1;
if (hasTable) {
lua_newtable(L);
} else if (itemCount == 0) {
lua_pushnil(L);
return 1;
}
bool canDropOnMap = getBoolean(L, 4, true);
slots_t slot = getNumber<slots_t>(L, 6, CONST_SLOT_WHEREEVER);
for (int32_t i = 1; i <= itemCount; ++i) {
int32_t stackCount = subType;
if (it.stackable) {
stackCount = std::min<int32_t>(stackCount, 100);
subType -= stackCount;
}
Item* item = Item::CreateItem(itemId, stackCount);
if (!item) {
if (!hasTable) {
lua_pushnil(L);
}
return 1;
}
ReturnValue ret = g_game.internalPlayerAddItem(player, item, canDropOnMap, slot);
if (ret != RETURNVALUE_NOERROR) {
delete item;
if (!hasTable) {
lua_pushnil(L);
}
return 1;
}
if (hasTable) {
lua_pushnumber(L, i);
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
lua_settable(L, -3);
} else {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
}
}
return 1;
}
int LuaScriptInterface::luaPlayerAddItemEx(lua_State* L)
{
// player:addItemEx(item[, canDropOnMap = false[, index = INDEX_WHEREEVER[, flags = 0]]])
// player:addItemEx(item[, canDropOnMap = true[, slot = CONST_SLOT_WHEREEVER]])
Item* item = getUserdata<Item>(L, 2);
if (!item) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
if (item->getParent() != VirtualCylinder::virtualCylinder) {
reportErrorFunc("Item already has a parent");
pushBoolean(L, false);
return 1;
}
bool canDropOnMap = getBoolean(L, 3, false);
ReturnValue returnValue;
if (canDropOnMap) {
slots_t slot = getNumber<slots_t>(L, 4, CONST_SLOT_WHEREEVER);
returnValue = g_game.internalPlayerAddItem(player, item, true, slot);
} else {
int32_t index = getNumber<int32_t>(L, 4, INDEX_WHEREEVER);
uint32_t flags = getNumber<uint32_t>(L, 5, 0);
returnValue = g_game.internalAddItem(player, item, index, flags);
}
if (returnValue == RETURNVALUE_NOERROR) {
ScriptEnvironment::removeTempItem(item);
}
lua_pushnumber(L, returnValue);
return 1;
}
int LuaScriptInterface::luaPlayerRemoveItem(lua_State* L)
{
// player:removeItem(itemId, count[, subType = -1[, ignoreEquipped = false]])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
uint32_t count = getNumber<uint32_t>(L, 3);
int32_t subType = getNumber<int32_t>(L, 4, -1);
bool ignoreEquipped = getBoolean(L, 5, false);
pushBoolean(L, player->removeItemOfType(itemId, count, subType, ignoreEquipped));
return 1;
}
int LuaScriptInterface::luaPlayerGetMoney(lua_State* L)
{
// player:getMoney()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getMoney());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddMoney(lua_State* L)
{
// player:addMoney(money)
uint64_t money = getNumber<uint64_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
g_game.addMoney(player, money);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveMoney(lua_State* L)
{
// player:removeMoney(money)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint64_t money = getNumber<uint64_t>(L, 2);
pushBoolean(L, g_game.removeMoney(player, money));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerShowTextDialog(lua_State* L)
{
// player:showTextDialog(itemId[, text[, canWrite[, length]]])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
int32_t length = getNumber<int32_t>(L, 5, -1);
bool canWrite = getBoolean(L, 4, false);
std::string text;
int parameters = lua_gettop(L);
if (parameters >= 3) {
text = getString(L, 3);
}
uint16_t itemId;
if (isNumber(L, 2)) {
itemId = getNumber<uint16_t>(L, 2);
} else {
itemId = Item::items.getItemIdByName(getString(L, 2));
if (itemId == 0) {
lua_pushnil(L);
return 1;
}
}
Item* item = Item::CreateItem(itemId);
if (!item) {
reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
if (length < 0) {
length = Item::items[item->getID()].maxTextLen;
}
if (!text.empty()) {
item->setText(text);
length = std::max<int32_t>(text.size(), length);
}
item->setParent(player);
player->setWriteItem(item, length);
player->sendTextWindow(item, length, canWrite);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerSendTextMessage(lua_State* L)
{
// player:sendTextMessage(type, text[, position, primaryValue = 0, primaryColor = TEXTCOLOR_NONE[, secondaryValue = 0, secondaryColor = TEXTCOLOR_NONE]])
int parameters = lua_gettop(L);
TextMessage message(getNumber<MessageClasses>(L, 2), getString(L, 3));
if (parameters >= 6) {
message.position = getPosition(L, 4);
message.primary.value = getNumber<int32_t>(L, 5);
message.primary.color = getNumber<TextColor_t>(L, 6);
}
if (parameters >= 8) {
message.secondary.value = getNumber<int32_t>(L, 7);
message.secondary.color = getNumber<TextColor_t>(L, 8);
}
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->sendTextMessage(message);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSendChannelMessage(lua_State* L)
{
// player:sendChannelMessage(author, text, type, channelId)
uint16_t channelId = getNumber<uint16_t>(L, 5);
SpeakClasses type = getNumber<SpeakClasses>(L, 4);
const std::string& text = getString(L, 3);
const std::string& author = getString(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->sendChannelMessage(author, text, type, channelId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSendPrivateMessage(lua_State* L)
{
// player:sendPrivateMessage(speaker, text[, type])
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
const Player* speaker = getUserdata<const Player>(L, 2);
const std::string& text = getString(L, 3);
SpeakClasses type = getNumber<SpeakClasses>(L, 4, TALKTYPE_PRIVATE_FROM);
player->sendPrivateMessage(speaker, type, text);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerChannelSay(lua_State* L)
{
// player:channelSay(speaker, type, text, channelId)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Creature* speaker = getCreature(L, 2);
SpeakClasses type = getNumber<SpeakClasses>(L, 3);
const std::string& text = getString(L, 4);
uint16_t channelId = getNumber<uint16_t>(L, 5);
player->sendToChannel(speaker, type, text, channelId);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerOpenChannel(lua_State* L)
{
// player:openChannel(channelId)
uint16_t channelId = getNumber<uint16_t>(L, 2);
Player* player = getUserdata<Player>(L, 1);
if (player) {
g_game.playerOpenChannel(player->getID(), channelId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetSlotItem(lua_State* L)
{
// player:getSlotItem(slot)
const Player* player = getUserdata<const Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint32_t slot = getNumber<uint32_t>(L, 2);
Thing* thing = player->getThing(slot);
if (!thing) {
lua_pushnil(L);
return 1;
}
Item* item = thing->getItem();
if (item) {
pushUserdata<Item>(L, item);
setItemMetatable(L, -1, item);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetParty(lua_State* L)
{
// player:getParty()
const Player* player = getUserdata<const Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Party* party = player->getParty();
if (party) {
pushUserdata<Party>(L, party);
setMetatable(L, -1, "Party");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddOutfit(lua_State* L)
{
// player:addOutfit(lookType)
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->addOutfit(getNumber<uint16_t>(L, 2), 0);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddOutfitAddon(lua_State* L)
{
// player:addOutfitAddon(lookType, addon)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint16_t lookType = getNumber<uint16_t>(L, 2);
uint8_t addon = getNumber<uint8_t>(L, 3);
player->addOutfit(lookType, addon);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveOutfit(lua_State* L)
{
// player:removeOutfit(lookType)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint16_t lookType = getNumber<uint16_t>(L, 2);
pushBoolean(L, player->removeOutfit(lookType));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveOutfitAddon(lua_State* L)
{
// player:removeOutfitAddon(lookType, addon)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint16_t lookType = getNumber<uint16_t>(L, 2);
uint8_t addon = getNumber<uint8_t>(L, 3);
pushBoolean(L, player->removeOutfitAddon(lookType, addon));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerHasOutfit(lua_State* L)
{
// player:hasOutfit(lookType[, addon = 0])
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint16_t lookType = getNumber<uint16_t>(L, 2);
uint8_t addon = getNumber<uint8_t>(L, 3, 0);
pushBoolean(L, player->canWear(lookType, addon));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSendOutfitWindow(lua_State* L)
{
// player:sendOutfitWindow()
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->sendOutfitWindow();
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddMount(lua_State* L)
{
// player:addMount(mountId)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint8_t mountId = getNumber<uint8_t>(L, 2);
pushBoolean(L, player->tameMount(mountId));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerRemoveMount(lua_State* L)
{
// player:removeMount(mountId)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint8_t mountId = getNumber<uint8_t>(L, 2);
pushBoolean(L, player->untameMount(mountId));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerHasMount(lua_State* L)
{
// player:hasMount(mountId)
const Player* player = getUserdata<const Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint8_t mountId = getNumber<uint8_t>(L, 2);
Mount* mount = g_game.mounts.getMountByID(mountId);
if (mount) {
pushBoolean(L, player->hasMount(mount));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetPremiumDays(lua_State* L)
{
// player:getPremiumDays()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->premiumDays);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddPremiumDays(lua_State* L)
{
// player:addPremiumDays(days)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
if (player->premiumDays != std::numeric_limits<uint16_t>::max()) {
uint16_t days = getNumber<uint16_t>(L, 2);
int32_t addDays = std::min<int32_t>(0xFFFE - player->premiumDays, days);
if (addDays > 0) {
player->setPremiumDays(player->premiumDays + addDays);
IOLoginData::addPremiumDays(player->getAccount(), addDays);
}
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerRemovePremiumDays(lua_State* L)
{
// player:removePremiumDays(days)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
if (player->premiumDays != std::numeric_limits<uint16_t>::max()) {
uint16_t days = getNumber<uint16_t>(L, 2);
int32_t removeDays = std::min<int32_t>(player->premiumDays, days);
if (removeDays > 0) {
player->setPremiumDays(player->premiumDays - removeDays);
IOLoginData::removePremiumDays(player->getAccount(), removeDays);
}
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerHasBlessing(lua_State* L)
{
// player:hasBlessing(blessing)
uint8_t blessing = getNumber<uint8_t>(L, 2) - 1;
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushBoolean(L, player->hasBlessing(blessing));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddBlessing(lua_State* L)
{
// player:addBlessing(blessing)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint8_t blessing = getNumber<uint8_t>(L, 2) - 1;
if (player->hasBlessing(blessing)) {
pushBoolean(L, false);
return 1;
}
player->addBlessing(1 << blessing);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerRemoveBlessing(lua_State* L)
{
// player:removeBlessing(blessing)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
uint8_t blessing = getNumber<uint8_t>(L, 2) - 1;
if (!player->hasBlessing(blessing)) {
pushBoolean(L, false);
return 1;
}
player->removeBlessing(1 << blessing);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerCanLearnSpell(lua_State* L)
{
// player:canLearnSpell(spellName)
const Player* player = getUserdata<const Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
const std::string& spellName = getString(L, 2);
InstantSpell* spell = g_spells->getInstantSpellByName(spellName);
if (!spell) {
reportErrorFunc("Spell \"" + spellName + "\" not found");
pushBoolean(L, false);
return 1;
}
if (player->hasFlag(PlayerFlag_IgnoreSpellCheck)) {
pushBoolean(L, true);
return 1;
}
const auto& vocMap = spell->getVocMap();
if (vocMap.count(player->getVocationId()) == 0) {
pushBoolean(L, false);
} else if (player->getLevel() < spell->getLevel()) {
pushBoolean(L, false);
} else if (player->getMagicLevel() < spell->getMagicLevel()) {
pushBoolean(L, false);
} else {
pushBoolean(L, true);
}
return 1;
}
int LuaScriptInterface::luaPlayerLearnSpell(lua_State* L)
{
// player:learnSpell(spellName)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const std::string& spellName = getString(L, 2);
player->learnInstantSpell(spellName);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerForgetSpell(lua_State* L)
{
// player:forgetSpell(spellName)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const std::string& spellName = getString(L, 2);
player->forgetInstantSpell(spellName);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerHasLearnedSpell(lua_State* L)
{
// player:hasLearnedSpell(spellName)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const std::string& spellName = getString(L, 2);
pushBoolean(L, player->hasLearnedInstantSpell(spellName));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSendTutorial(lua_State* L)
{
// player:sendTutorial(tutorialId)
Player* player = getUserdata<Player>(L, 1);
if (player) {
uint8_t tutorialId = getNumber<uint8_t>(L, 2);
player->sendTutorial(tutorialId);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerAddMapMark(lua_State* L)
{
// player:addMapMark(position, type, description)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const Position& position = getPosition(L, 2);
uint8_t type = getNumber<uint8_t>(L, 3);
const std::string& description = getString(L, 4);
player->sendAddMarker(position, type, description);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSave(lua_State* L)
{
// player:save()
Player* player = getUserdata<Player>(L, 1);
if (player) {
player->loginPosition = player->getPosition();
pushBoolean(L, IOLoginData::savePlayer(player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerPopupFYI(lua_State* L)
{
// player:popupFYI(message)
Player* player = getUserdata<Player>(L, 1);
if (player) {
const std::string& message = getString(L, 2);
player->sendFYIBox(message);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerIsPzLocked(lua_State* L)
{
// player:isPzLocked()
Player* player = getUserdata<Player>(L, 1);
if (player) {
pushBoolean(L, player->isPzLocked());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetClient(lua_State* L)
{
// player:getClient()
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_createtable(L, 0, 2);
setField(L, "version", player->getProtocolVersion());
setField(L, "os", player->getOperatingSystem());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetHouse(lua_State* L)
{
// player:getHouse()
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
House* house = g_game.map.houses.getHouseByPlayerId(player->getGUID());
if (house) {
pushUserdata<House>(L, house);
setMetatable(L, -1, "House");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerSetGhostMode(lua_State* L)
{
// player:setGhostMode(enabled)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
bool enabled = getBoolean(L, 2);
if (player->isInGhostMode() == enabled) {
pushBoolean(L, true);
return 1;
}
player->switchGhostMode();
Tile* tile = player->getTile();
const Position& position = player->getPosition();
SpectatorHashSet spectators;
g_game.map.getSpectators(spectators, position, true, true);
for (Creature* spectator : spectators) {
Player* tmpPlayer = spectator->getPlayer();
if (tmpPlayer != player && !tmpPlayer->isAccessPlayer()) {
if (enabled) {
tmpPlayer->sendRemoveTileThing(position, tile->getStackposOfCreature(tmpPlayer, player));
} else {
tmpPlayer->sendCreatureAppear(player, position, true);
}
} else {
tmpPlayer->sendCreatureChangeVisible(player, !enabled);
}
}
if (player->isInGhostMode()) {
for (const auto& it : g_game.getPlayers()) {
if (!it.second->isAccessPlayer()) {
it.second->notifyStatusChange(player, VIPSTATUS_OFFLINE);
}
}
IOLoginData::updateOnlineStatus(player->getGUID(), false);
} else {
for (const auto& it : g_game.getPlayers()) {
if (!it.second->isAccessPlayer()) {
it.second->notifyStatusChange(player, VIPSTATUS_ONLINE);
}
}
IOLoginData::updateOnlineStatus(player->getGUID(), true);
}
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaPlayerGetContainerId(lua_State* L)
{
// player:getContainerId(container)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Container* container = getUserdata<Container>(L, 2);
if (container) {
lua_pushnumber(L, player->getContainerID(container));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetContainerById(lua_State* L)
{
// player:getContainerById(id)
Player* player = getUserdata<Player>(L, 1);
if (!player) {
lua_pushnil(L);
return 1;
}
Container* container = player->getContainerByID(getNumber<uint8_t>(L, 2));
if (container) {
pushUserdata<Container>(L, container);
setMetatable(L, -1, "Container");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPlayerGetContainerIndex(lua_State* L)
{
// player:getContainerIndex(id)
Player* player = getUserdata<Player>(L, 1);
if (player) {
lua_pushnumber(L, player->getContainerIndex(getNumber<uint8_t>(L, 2)));
} else {
lua_pushnil(L);
}
return 1;
}
// Monster
int LuaScriptInterface::luaMonsterCreate(lua_State* L)
{
// Monster(id or userdata)
Monster* monster;
if (isNumber(L, 2)) {
monster = g_game.getMonsterByID(getNumber<uint32_t>(L, 2));
} else if (isUserdata(L, 2)) {
if (getUserdataType(L, 2) != LuaData_Monster) {
lua_pushnil(L);
return 1;
}
monster = getUserdata<Monster>(L, 2);
} else {
monster = nullptr;
}
if (monster) {
pushUserdata<Monster>(L, monster);
setMetatable(L, -1, "Monster");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsMonster(lua_State* L)
{
// monster:isMonster()
pushBoolean(L, getUserdata<const Monster>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaMonsterGetType(lua_State* L)
{
// monster:getType()
const Monster* monster = getUserdata<const Monster>(L, 1);
if (monster) {
pushUserdata<MonsterType>(L, monster->mType);
setMetatable(L, -1, "MonsterType");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterGetSpawnPosition(lua_State* L)
{
// monster:getSpawnPosition()
const Monster* monster = getUserdata<const Monster>(L, 1);
if (monster) {
pushPosition(L, monster->getMasterPos());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsInSpawnRange(lua_State* L)
{
// monster:isInSpawnRange([position])
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
pushBoolean(L, monster->isInSpawnRange(lua_gettop(L) >= 2 ? getPosition(L, 2) : monster->getPosition()));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsIdle(lua_State* L)
{
// monster:isIdle()
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
pushBoolean(L, monster->getIdleStatus());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterSetIdle(lua_State* L)
{
// monster:setIdle(idle)
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
monster->setIdle(getBoolean(L, 2));
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaMonsterIsTarget(lua_State* L)
{
// monster:isTarget(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
const Creature* creature = getCreature(L, 2);
pushBoolean(L, monster->isTarget(creature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsOpponent(lua_State* L)
{
// monster:isOpponent(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
const Creature* creature = getCreature(L, 2);
pushBoolean(L, monster->isOpponent(creature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterIsFriend(lua_State* L)
{
// monster:isFriend(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
const Creature* creature = getCreature(L, 2);
pushBoolean(L, monster->isFriend(creature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterAddFriend(lua_State* L)
{
// monster:addFriend(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
Creature* creature = getCreature(L, 2);
monster->addFriend(creature);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterRemoveFriend(lua_State* L)
{
// monster:removeFriend(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
Creature* creature = getCreature(L, 2);
monster->removeFriend(creature);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterGetFriendList(lua_State* L)
{
// monster:getFriendList()
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
const auto& friendList = monster->getFriendList();
lua_createtable(L, friendList.size(), 0);
int index = 0;
for (Creature* creature : friendList) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterGetFriendCount(lua_State* L)
{
// monster:getFriendCount()
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
lua_pushnumber(L, monster->getFriendList().size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterAddTarget(lua_State* L)
{
// monster:addTarget(creature[, pushFront = false])
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
Creature* creature = getCreature(L, 2);
bool pushFront = getBoolean(L, 3, false);
monster->addTarget(creature, pushFront);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaMonsterRemoveTarget(lua_State* L)
{
// monster:removeTarget(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
monster->removeTarget(getCreature(L, 2));
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaMonsterGetTargetList(lua_State* L)
{
// monster:getTargetList()
Monster* monster = getUserdata<Monster>(L, 1);
if (!monster) {
lua_pushnil(L);
return 1;
}
const auto& targetList = monster->getTargetList();
lua_createtable(L, targetList.size(), 0);
int index = 0;
for (Creature* creature : targetList) {
pushUserdata<Creature>(L, creature);
setCreatureMetatable(L, -1, creature);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterGetTargetCount(lua_State* L)
{
// monster:getTargetCount()
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
lua_pushnumber(L, monster->getTargetList().size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterSelectTarget(lua_State* L)
{
// monster:selectTarget(creature)
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
Creature* creature = getCreature(L, 2);
pushBoolean(L, monster->selectTarget(creature));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterSearchTarget(lua_State* L)
{
// monster:searchTarget([searchType = TARGETSEARCH_DEFAULT])
Monster* monster = getUserdata<Monster>(L, 1);
if (monster) {
TargetSearchType_t searchType = getNumber<TargetSearchType_t>(L, 2, TARGETSEARCH_DEFAULT);
pushBoolean(L, monster->searchTarget(searchType));
} else {
lua_pushnil(L);
}
return 1;
}
// Npc
int LuaScriptInterface::luaNpcCreate(lua_State* L)
{
// Npc([id or name or userdata])
Npc* npc;
if (lua_gettop(L) >= 2) {
if (isNumber(L, 2)) {
npc = g_game.getNpcByID(getNumber<uint32_t>(L, 2));
} else if (isString(L, 2)) {
npc = g_game.getNpcByName(getString(L, 2));
} else if (isUserdata(L, 2)) {
if (getUserdataType(L, 2) != LuaData_Npc) {
lua_pushnil(L);
return 1;
}
npc = getUserdata<Npc>(L, 2);
} else {
npc = nullptr;
}
} else {
npc = getScriptEnv()->getNpc();
}
if (npc) {
pushUserdata<Npc>(L, npc);
setMetatable(L, -1, "Npc");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNpcIsNpc(lua_State* L)
{
// npc:isNpc()
pushBoolean(L, getUserdata<const Npc>(L, 1) != nullptr);
return 1;
}
int LuaScriptInterface::luaNpcSetMasterPos(lua_State* L)
{
// npc:setMasterPos(pos[, radius])
Npc* npc = getUserdata<Npc>(L, 1);
if (!npc) {
lua_pushnil(L);
return 1;
}
const Position& pos = getPosition(L, 2);
int32_t radius = getNumber<int32_t>(L, 3, 1);
npc->setMasterPos(pos, radius);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaNpcGetSpeechBubble(lua_State* L)
{
// npc:getSpeechBubble()
Npc* npc = getUserdata<Npc>(L, 1);
if (npc) {
lua_pushnumber(L, npc->getSpeechBubble());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaNpcSetSpeechBubble(lua_State* L)
{
// npc:setSpeechBubble(speechBubble)
Npc* npc = getUserdata<Npc>(L, 1);
if (npc) {
npc->setSpeechBubble(getNumber<uint8_t>(L, 2));
}
return 0;
}
// Guild
int LuaScriptInterface::luaGuildCreate(lua_State* L)
{
// Guild(id)
uint32_t id = getNumber<uint32_t>(L, 2);
Guild* guild = g_game.getGuild(id);
if (guild) {
pushUserdata<Guild>(L, guild);
setMetatable(L, -1, "Guild");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetId(lua_State* L)
{
// guild:getId()
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
lua_pushnumber(L, guild->getId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetName(lua_State* L)
{
// guild:getName()
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
pushString(L, guild->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetMembersOnline(lua_State* L)
{
// guild:getMembersOnline()
const Guild* guild = getUserdata<const Guild>(L, 1);
if (!guild) {
lua_pushnil(L);
return 1;
}
const auto& members = guild->getMembersOnline();
lua_createtable(L, members.size(), 0);
int index = 0;
for (Player* player : members) {
pushUserdata<Player>(L, player);
setMetatable(L, -1, "Player");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaGuildAddRank(lua_State* L)
{
// guild:addRank(id, name, level)
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
uint32_t id = getNumber<uint32_t>(L, 2);
const std::string& name = getString(L, 3);
uint8_t level = getNumber<uint8_t>(L, 4);
guild->addRank(id, name, level);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetRankById(lua_State* L)
{
// guild:getRankById(id)
Guild* guild = getUserdata<Guild>(L, 1);
if (!guild) {
lua_pushnil(L);
return 1;
}
uint32_t id = getNumber<uint32_t>(L, 2);
GuildRank* rank = guild->getRankById(id);
if (rank) {
lua_createtable(L, 0, 3);
setField(L, "id", rank->id);
setField(L, "name", rank->name);
setField(L, "level", rank->level);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetRankByLevel(lua_State* L)
{
// guild:getRankByLevel(level)
const Guild* guild = getUserdata<const Guild>(L, 1);
if (!guild) {
lua_pushnil(L);
return 1;
}
uint8_t level = getNumber<uint8_t>(L, 2);
const GuildRank* rank = guild->getRankByLevel(level);
if (rank) {
lua_createtable(L, 0, 3);
setField(L, "id", rank->id);
setField(L, "name", rank->name);
setField(L, "level", rank->level);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildGetMotd(lua_State* L)
{
// guild:getMotd()
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
pushString(L, guild->getMotd());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGuildSetMotd(lua_State* L)
{
// guild:setMotd(motd)
const std::string& motd = getString(L, 2);
Guild* guild = getUserdata<Guild>(L, 1);
if (guild) {
guild->setMotd(motd);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
// Group
int LuaScriptInterface::luaGroupCreate(lua_State* L)
{
// Group(id)
uint32_t id = getNumber<uint32_t>(L, 2);
Group* group = g_game.groups.getGroup(id);
if (group) {
pushUserdata<Group>(L, group);
setMetatable(L, -1, "Group");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetId(lua_State* L)
{
// group:getId()
Group* group = getUserdata<Group>(L, 1);
if (group) {
lua_pushnumber(L, group->id);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetName(lua_State* L)
{
// group:getName()
Group* group = getUserdata<Group>(L, 1);
if (group) {
pushString(L, group->name);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetFlags(lua_State* L)
{
// group:getFlags()
Group* group = getUserdata<Group>(L, 1);
if (group) {
lua_pushnumber(L, group->flags);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetAccess(lua_State* L)
{
// group:getAccess()
Group* group = getUserdata<Group>(L, 1);
if (group) {
pushBoolean(L, group->access);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetMaxDepotItems(lua_State* L)
{
// group:getMaxDepotItems()
Group* group = getUserdata<Group>(L, 1);
if (group) {
lua_pushnumber(L, group->maxDepotItems);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaGroupGetMaxVipEntries(lua_State* L)
{
// group:getMaxVipEntries()
Group* group = getUserdata<Group>(L, 1);
if (group) {
lua_pushnumber(L, group->maxVipEntries);
} else {
lua_pushnil(L);
}
return 1;
}
// Vocation
int LuaScriptInterface::luaVocationCreate(lua_State* L)
{
// Vocation(id or name)
uint32_t id;
if (isNumber(L, 2)) {
id = getNumber<uint32_t>(L, 2);
} else {
id = g_vocations.getVocationId(getString(L, 2));
}
Vocation* vocation = g_vocations.getVocation(id);
if (vocation) {
pushUserdata<Vocation>(L, vocation);
setMetatable(L, -1, "Vocation");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetId(lua_State* L)
{
// vocation:getId()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetClientId(lua_State* L)
{
// vocation:getClientId()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getClientId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetName(lua_State* L)
{
// vocation:getName()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
pushString(L, vocation->getVocName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetDescription(lua_State* L)
{
// vocation:getDescription()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
pushString(L, vocation->getVocDescription());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetRequiredSkillTries(lua_State* L)
{
// vocation:getRequiredSkillTries(skillType, skillLevel)
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
skills_t skillType = getNumber<skills_t>(L, 2);
uint16_t skillLevel = getNumber<uint16_t>(L, 3);
lua_pushnumber(L, vocation->getReqSkillTries(skillType, skillLevel));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetRequiredManaSpent(lua_State* L)
{
// vocation:getRequiredManaSpent(magicLevel)
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
uint32_t magicLevel = getNumber<uint32_t>(L, 2);
lua_pushnumber(L, vocation->getReqMana(magicLevel));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetCapacityGain(lua_State* L)
{
// vocation:getCapacityGain()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getCapGain());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetHealthGain(lua_State* L)
{
// vocation:getHealthGain()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getHPGain());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetHealthGainTicks(lua_State* L)
{
// vocation:getHealthGainTicks()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getHealthGainTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetHealthGainAmount(lua_State* L)
{
// vocation:getHealthGainAmount()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getHealthGainAmount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetManaGain(lua_State* L)
{
// vocation:getManaGain()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getManaGain());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetManaGainTicks(lua_State* L)
{
// vocation:getManaGainTicks()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getManaGainTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetManaGainAmount(lua_State* L)
{
// vocation:getManaGainAmount()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getManaGainAmount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetMaxSoul(lua_State* L)
{
// vocation:getMaxSoul()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getSoulMax());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetSoulGainTicks(lua_State* L)
{
// vocation:getSoulGainTicks()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getSoulGainTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetAttackSpeed(lua_State* L)
{
// vocation:getAttackSpeed()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getAttackSpeed());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetBaseSpeed(lua_State* L)
{
// vocation:getBaseSpeed()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (vocation) {
lua_pushnumber(L, vocation->getBaseSpeed());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetDemotion(lua_State* L)
{
// vocation:getDemotion()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (!vocation) {
lua_pushnil(L);
return 1;
}
uint16_t fromId = vocation->getFromVocation();
if (fromId == VOCATION_NONE) {
lua_pushnil(L);
return 1;
}
Vocation* demotedVocation = g_vocations.getVocation(fromId);
if (demotedVocation && demotedVocation != vocation) {
pushUserdata<Vocation>(L, demotedVocation);
setMetatable(L, -1, "Vocation");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaVocationGetPromotion(lua_State* L)
{
// vocation:getPromotion()
Vocation* vocation = getUserdata<Vocation>(L, 1);
if (!vocation) {
lua_pushnil(L);
return 1;
}
uint16_t promotedId = g_vocations.getPromotedVocation(vocation->getId());
if (promotedId == VOCATION_NONE) {
lua_pushnil(L);
return 1;
}
Vocation* promotedVocation = g_vocations.getVocation(promotedId);
if (promotedVocation && promotedVocation != vocation) {
pushUserdata<Vocation>(L, promotedVocation);
setMetatable(L, -1, "Vocation");
} else {
lua_pushnil(L);
}
return 1;
}
// Town
int LuaScriptInterface::luaTownCreate(lua_State* L)
{
// Town(id or name)
Town* town;
if (isNumber(L, 2)) {
town = g_game.map.towns.getTown(getNumber<uint32_t>(L, 2));
} else if (isString(L, 2)) {
town = g_game.map.towns.getTown(getString(L, 2));
} else {
town = nullptr;
}
if (town) {
pushUserdata<Town>(L, town);
setMetatable(L, -1, "Town");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTownGetId(lua_State* L)
{
// town:getId()
Town* town = getUserdata<Town>(L, 1);
if (town) {
lua_pushnumber(L, town->getID());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTownGetName(lua_State* L)
{
// town:getName()
Town* town = getUserdata<Town>(L, 1);
if (town) {
pushString(L, town->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaTownGetTemplePosition(lua_State* L)
{
// town:getTemplePosition()
Town* town = getUserdata<Town>(L, 1);
if (town) {
pushPosition(L, town->getTemplePosition());
} else {
lua_pushnil(L);
}
return 1;
}
// House
int LuaScriptInterface::luaHouseCreate(lua_State* L)
{
// House(id)
House* house = g_game.map.houses.getHouse(getNumber<uint32_t>(L, 2));
if (house) {
pushUserdata<House>(L, house);
setMetatable(L, -1, "House");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetId(lua_State* L)
{
// house:getId()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetName(lua_State* L)
{
// house:getName()
House* house = getUserdata<House>(L, 1);
if (house) {
pushString(L, house->getName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetTown(lua_State* L)
{
// house:getTown()
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
Town* town = g_game.map.towns.getTown(house->getTownId());
if (town) {
pushUserdata<Town>(L, town);
setMetatable(L, -1, "Town");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetExitPosition(lua_State* L)
{
// house:getExitPosition()
House* house = getUserdata<House>(L, 1);
if (house) {
pushPosition(L, house->getEntryPosition());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetRent(lua_State* L)
{
// house:getRent()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getRent());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetOwnerGuid(lua_State* L)
{
// house:getOwnerGuid()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getOwner());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseSetOwnerGuid(lua_State* L)
{
// house:setOwnerGuid(guid[, updateDatabase = true])
House* house = getUserdata<House>(L, 1);
if (house) {
uint32_t guid = getNumber<uint32_t>(L, 2);
bool updateDatabase = getBoolean(L, 3, true);
house->setOwner(guid, updateDatabase);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetBeds(lua_State* L)
{
// house:getBeds()
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
const auto& beds = house->getBeds();
lua_createtable(L, beds.size(), 0);
int index = 0;
for (BedItem* bedItem : beds) {
pushUserdata<Item>(L, bedItem);
setItemMetatable(L, -1, bedItem);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaHouseGetBedCount(lua_State* L)
{
// house:getBedCount()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getBedCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetDoors(lua_State* L)
{
// house:getDoors()
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
const auto& doors = house->getDoors();
lua_createtable(L, doors.size(), 0);
int index = 0;
for (Door* door : doors) {
pushUserdata<Item>(L, door);
setItemMetatable(L, -1, door);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaHouseGetDoorCount(lua_State* L)
{
// house:getDoorCount()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getDoors().size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetTiles(lua_State* L)
{
// house:getTiles()
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
const auto& tiles = house->getTiles();
lua_createtable(L, tiles.size(), 0);
int index = 0;
for (Tile* tile : tiles) {
pushUserdata<Tile>(L, tile);
setMetatable(L, -1, "Tile");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaHouseGetTileCount(lua_State* L)
{
// house:getTileCount()
House* house = getUserdata<House>(L, 1);
if (house) {
lua_pushnumber(L, house->getTiles().size());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaHouseGetAccessList(lua_State* L)
{
// house:getAccessList(listId)
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
std::string list;
uint32_t listId = getNumber<uint32_t>(L, 2);
if (house->getAccessList(listId, list)) {
pushString(L, list);
} else {
pushBoolean(L, false);
}
return 1;
}
int LuaScriptInterface::luaHouseSetAccessList(lua_State* L)
{
// house:setAccessList(listId, list)
House* house = getUserdata<House>(L, 1);
if (!house) {
lua_pushnil(L);
return 1;
}
uint32_t listId = getNumber<uint32_t>(L, 2);
const std::string& list = getString(L, 3);
house->setAccessList(listId, list);
pushBoolean(L, true);
return 1;
}
// ItemType
int LuaScriptInterface::luaItemTypeCreate(lua_State* L)
{
// ItemType(id or name)
uint32_t id;
if (isNumber(L, 2)) {
id = getNumber<uint32_t>(L, 2);
} else {
id = Item::items.getItemIdByName(getString(L, 2));
}
const ItemType& itemType = Item::items[id];
pushUserdata<const ItemType>(L, &itemType);
setMetatable(L, -1, "ItemType");
return 1;
}
int LuaScriptInterface::luaItemTypeIsCorpse(lua_State* L)
{
// itemType:isCorpse()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->corpseType != RACE_NONE);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsDoor(lua_State* L)
{
// itemType:isDoor()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isDoor());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsContainer(lua_State* L)
{
// itemType:isContainer()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isContainer());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsFluidContainer(lua_State* L)
{
// itemType:isFluidContainer()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isFluidContainer());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsMovable(lua_State* L)
{
// itemType:isMovable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->moveable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsRune(lua_State* L)
{
// itemType:isRune()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->isRune());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsStackable(lua_State* L)
{
// itemType:isStackable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->stackable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsReadable(lua_State* L)
{
// itemType:isReadable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->canReadText);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeIsWritable(lua_State* L)
{
// itemType:isWritable()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->canWriteText);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetType(lua_State* L)
{
// itemType:getType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->type);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetId(lua_State* L)
{
// itemType:getId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->id);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetClientId(lua_State* L)
{
// itemType:getClientId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->clientId);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetName(lua_State* L)
{
// itemType:getName()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushString(L, itemType->name);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetPluralName(lua_State* L)
{
// itemType:getPluralName()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushString(L, itemType->getPluralName());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetArticle(lua_State* L)
{
// itemType:getArticle()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushString(L, itemType->article);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetDescription(lua_State* L)
{
// itemType:getDescription()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushString(L, itemType->description);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetSlotPosition(lua_State *L)
{
// itemType:getSlotPosition()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->slotPosition);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetCharges(lua_State* L)
{
// itemType:getCharges()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->charges);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetFluidSource(lua_State* L)
{
// itemType:getFluidSource()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->fluidSource);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetCapacity(lua_State* L)
{
// itemType:getCapacity()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->maxItems);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetWeight(lua_State* L)
{
// itemType:getWeight([count = 1])
uint16_t count = getNumber<uint16_t>(L, 2, 1);
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (!itemType) {
lua_pushnil(L);
return 1;
}
uint64_t weight = static_cast<uint64_t>(itemType->weight) * std::max<int32_t>(1, count);
lua_pushnumber(L, weight);
return 1;
}
int LuaScriptInterface::luaItemTypeGetHitChance(lua_State* L)
{
// itemType:getHitChance()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->hitChance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetShootRange(lua_State* L)
{
// itemType:getShootRange()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->shootRange);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetAttack(lua_State* L)
{
// itemType:getAttack()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->attack);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetDefense(lua_State* L)
{
// itemType:getDefense()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->defense);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetExtraDefense(lua_State* L)
{
// itemType:getExtraDefense()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->extraDefense);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetArmor(lua_State* L)
{
// itemType:getArmor()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->armor);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetWeaponType(lua_State* L)
{
// itemType:getWeaponType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->weaponType);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetElementType(lua_State* L)
{
// itemType:getElementType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (!itemType) {
lua_pushnil(L);
return 1;
}
auto& abilities = itemType->abilities;
if (abilities) {
lua_pushnumber(L, abilities->elementType);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetElementDamage(lua_State* L)
{
// itemType:getElementDamage()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (!itemType) {
lua_pushnil(L);
return 1;
}
auto& abilities = itemType->abilities;
if (abilities) {
lua_pushnumber(L, abilities->elementDamage);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetTransformEquipId(lua_State* L)
{
// itemType:getTransformEquipId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->transformEquipTo);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetTransformDeEquipId(lua_State* L)
{
// itemType:getTransformDeEquipId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->transformDeEquipTo);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetDestroyId(lua_State* L)
{
// itemType:getDestroyId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->destroyTo);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetDecayId(lua_State* L)
{
// itemType:getDecayId()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->decayTo);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeGetRequiredLevel(lua_State* L)
{
// itemType:getRequiredLevel()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
lua_pushnumber(L, itemType->minReqLevel);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaItemTypeHasSubType(lua_State* L)
{
// itemType:hasSubType()
const ItemType* itemType = getUserdata<const ItemType>(L, 1);
if (itemType) {
pushBoolean(L, itemType->hasSubType());
} else {
lua_pushnil(L);
}
return 1;
}
// Combat
int LuaScriptInterface::luaCombatCreate(lua_State* L)
{
// Combat()
pushUserdata<Combat>(L, g_luaEnvironment.createCombatObject(getScriptEnv()->getScriptInterface()));
setMetatable(L, -1, "Combat");
return 1;
}
int LuaScriptInterface::luaCombatSetParameter(lua_State* L)
{
// combat:setParameter(key, value)
Combat* combat = getUserdata<Combat>(L, 1);
if (!combat) {
lua_pushnil(L);
return 1;
}
CombatParam_t key = getNumber<CombatParam_t>(L, 2);
uint32_t value;
if (isBoolean(L, 3)) {
value = getBoolean(L, 3) ? 1 : 0;
} else {
value = getNumber<uint32_t>(L, 3);
}
combat->setParam(key, value);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCombatSetFormula(lua_State* L)
{
// combat:setFormula(type, mina, minb, maxa, maxb)
Combat* combat = getUserdata<Combat>(L, 1);
if (!combat) {
lua_pushnil(L);
return 1;
}
formulaType_t type = getNumber<formulaType_t>(L, 2);
double mina = getNumber<double>(L, 3);
double minb = getNumber<double>(L, 4);
double maxa = getNumber<double>(L, 5);
double maxb = getNumber<double>(L, 6);
combat->setPlayerCombatValues(type, mina, minb, maxa, maxb);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaCombatSetArea(lua_State* L)
{
// combat:setArea(area)
if (getScriptEnv()->getScriptId() != EVENT_ID_LOADING) {
reportErrorFunc("This function can only be used while loading the script.");
lua_pushnil(L);
return 1;
}
const AreaCombat* area = g_luaEnvironment.getAreaObject(getNumber<uint32_t>(L, 2));
if (!area) {
reportErrorFunc(getErrorDesc(LUA_ERROR_AREA_NOT_FOUND));
lua_pushnil(L);
return 1;
}
Combat* combat = getUserdata<Combat>(L, 1);
if (combat) {
combat->setArea(new AreaCombat(*area));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCombatSetCondition(lua_State* L)
{
// combat:setCondition(condition)
Condition* condition = getUserdata<Condition>(L, 2);
Combat* combat = getUserdata<Combat>(L, 1);
if (combat && condition) {
combat->setCondition(condition->clone());
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCombatSetCallback(lua_State* L)
{
// combat:setCallback(key, function)
Combat* combat = getUserdata<Combat>(L, 1);
if (!combat) {
lua_pushnil(L);
return 1;
}
CallBackParam_t key = getNumber<CallBackParam_t>(L, 2);
if (!combat->setCallback(key)) {
lua_pushnil(L);
return 1;
}
CallBack* callback = combat->getCallback(key);
if (!callback) {
lua_pushnil(L);
return 1;
}
const std::string& function = getString(L, 3);
pushBoolean(L, callback->loadCallBack(getScriptEnv()->getScriptInterface(), function));
return 1;
}
int LuaScriptInterface::luaCombatSetOrigin(lua_State* L)
{
// combat:setOrigin(origin)
Combat* combat = getUserdata<Combat>(L, 1);
if (combat) {
combat->setOrigin(getNumber<CombatOrigin>(L, 2));
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaCombatExecute(lua_State* L)
{
// combat:execute(creature, variant)
Combat* combat = getUserdata<Combat>(L, 1);
if (!combat) {
pushBoolean(L, false);
return 1;
}
Creature* creature = getCreature(L, 2);
const LuaVariant& variant = getVariant(L, 3);
switch (variant.type) {
case VARIANT_NUMBER: {
Creature* target = g_game.getCreatureByID(variant.number);
if (!target) {
pushBoolean(L, false);
return 1;
}
if (combat->hasArea()) {
combat->doCombat(creature, target->getPosition());
} else {
combat->doCombat(creature, target);
}
break;
}
case VARIANT_POSITION: {
combat->doCombat(creature, variant.pos);
break;
}
case VARIANT_TARGETPOSITION: {
if (combat->hasArea()) {
combat->doCombat(creature, variant.pos);
} else {
combat->postCombatEffects(creature, variant.pos);
g_game.addMagicEffect(variant.pos, CONST_ME_POFF);
}
break;
}
case VARIANT_STRING: {
Player* target = g_game.getPlayerByName(variant.text);
if (!target) {
pushBoolean(L, false);
return 1;
}
combat->doCombat(creature, target);
break;
}
case VARIANT_NONE: {
reportErrorFunc(getErrorDesc(LUA_ERROR_VARIANT_NOT_FOUND));
pushBoolean(L, false);
return 1;
}
default: {
break;
}
}
pushBoolean(L, true);
return 1;
}
// Condition
int LuaScriptInterface::luaConditionCreate(lua_State* L)
{
// Condition(conditionType[, conditionId = CONDITIONID_COMBAT])
ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2);
ConditionId_t conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT);
Condition* condition = Condition::createCondition(conditionId, conditionType, 0, 0);
if (condition) {
pushUserdata<Condition>(L, condition);
setMetatable(L, -1, "Condition");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionDelete(lua_State* L)
{
// condition:delete()
Condition** conditionPtr = getRawUserdata<Condition>(L, 1);
if (conditionPtr && *conditionPtr) {
delete *conditionPtr;
*conditionPtr = nullptr;
}
return 0;
}
int LuaScriptInterface::luaConditionGetId(lua_State* L)
{
// condition:getId()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetSubId(lua_State* L)
{
// condition:getSubId()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getSubId());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetType(lua_State* L)
{
// condition:getType()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getType());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetIcons(lua_State* L)
{
// condition:getIcons()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getIcons());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetEndTime(lua_State* L)
{
// condition:getEndTime()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getEndTime());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionClone(lua_State* L)
{
// condition:clone()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
pushUserdata<Condition>(L, condition->clone());
setMetatable(L, -1, "Condition");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionGetTicks(lua_State* L)
{
// condition:getTicks()
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
lua_pushnumber(L, condition->getTicks());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionSetTicks(lua_State* L)
{
// condition:setTicks(ticks)
int32_t ticks = getNumber<int32_t>(L, 2);
Condition* condition = getUserdata<Condition>(L, 1);
if (condition) {
condition->setTicks(ticks);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionSetParameter(lua_State* L)
{
// condition:setParameter(key, value)
Condition* condition = getUserdata<Condition>(L, 1);
if (!condition) {
lua_pushnil(L);
return 1;
}
ConditionParam_t key = getNumber<ConditionParam_t>(L, 2);
int32_t value;
if (isBoolean(L, 3)) {
value = getBoolean(L, 3) ? 1 : 0;
} else {
value = getNumber<int32_t>(L, 3);
}
condition->setParam(key, value);
pushBoolean(L, true);
return 1;
}
int LuaScriptInterface::luaConditionSetFormula(lua_State* L)
{
// condition:setFormula(mina, minb, maxa, maxb)
double maxb = getNumber<double>(L, 5);
double maxa = getNumber<double>(L, 4);
double minb = getNumber<double>(L, 3);
double mina = getNumber<double>(L, 2);
ConditionSpeed* condition = dynamic_cast<ConditionSpeed*>(getUserdata<Condition>(L, 1));
if (condition) {
condition->setFormulaVars(mina, minb, maxa, maxb);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionSetOutfit(lua_State* L)
{
// condition:setOutfit(outfit)
// condition:setOutfit(lookTypeEx, lookType, lookHead, lookBody, lookLegs, lookFeet[, lookAddons[, lookMount]])
Outfit_t outfit;
if (isTable(L, 2)) {
outfit = getOutfit(L, 2);
} else {
outfit.lookMount = getNumber<uint16_t>(L, 9, outfit.lookMount);
outfit.lookAddons = getNumber<uint8_t>(L, 8, outfit.lookAddons);
outfit.lookFeet = getNumber<uint8_t>(L, 7);
outfit.lookLegs = getNumber<uint8_t>(L, 6);
outfit.lookBody = getNumber<uint8_t>(L, 5);
outfit.lookHead = getNumber<uint8_t>(L, 4);
outfit.lookType = getNumber<uint16_t>(L, 3);
outfit.lookTypeEx = getNumber<uint16_t>(L, 2);
}
ConditionOutfit* condition = dynamic_cast<ConditionOutfit*>(getUserdata<Condition>(L, 1));
if (condition) {
condition->setOutfit(outfit);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaConditionAddDamage(lua_State* L)
{
// condition:addDamage(rounds, time, value)
int32_t value = getNumber<int32_t>(L, 4);
int32_t time = getNumber<int32_t>(L, 3);
int32_t rounds = getNumber<int32_t>(L, 2);
ConditionDamage* condition = dynamic_cast<ConditionDamage*>(getUserdata<Condition>(L, 1));
if (condition) {
pushBoolean(L, condition->addDamage(rounds, time, value));
} else {
lua_pushnil(L);
}
return 1;
}
// MonsterType
int LuaScriptInterface::luaMonsterTypeCreate(lua_State* L)
{
// MonsterType(name)
MonsterType* monsterType = g_monsters.getMonsterType(getString(L, 2));
if (monsterType) {
pushUserdata<MonsterType>(L, monsterType);
setMetatable(L, -1, "MonsterType");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsAttackable(lua_State* L)
{
// monsterType:isAttackable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.isAttackable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsConvinceable(lua_State* L)
{
// monsterType:isConvinceable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.isConvinceable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsSummonable(lua_State* L)
{
// monsterType:isSummonable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.isSummonable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsIllusionable(lua_State* L)
{
// monsterType:isIllusionable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.isIllusionable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsHostile(lua_State* L)
{
// monsterType:isHostile()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.isHostile);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsPushable(lua_State* L)
{
// monsterType:isPushable()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.pushable);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeIsHealthShown(lua_State* L)
{
// monsterType:isHealthShown()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, !monsterType->info.hiddenHealth);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeCanPushItems(lua_State* L)
{
// monsterType:canPushItems()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.canPushItems);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeCanPushCreatures(lua_State* L)
{
// monsterType:canPushCreatures()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushBoolean(L, monsterType->info.canPushCreatures);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetName(lua_State* L)
{
// monsterType:getName()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushString(L, monsterType->name);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetNameDescription(lua_State* L)
{
// monsterType:getNameDescription()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushString(L, monsterType->nameDescription);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetHealth(lua_State* L)
{
// monsterType:getHealth()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.health);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetMaxHealth(lua_State* L)
{
// monsterType:getMaxHealth()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.healthMax);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetRunHealth(lua_State* L)
{
// monsterType:getRunHealth()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.runAwayHealth);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetExperience(lua_State* L)
{
// monsterType:getExperience()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.experience);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetCombatImmunities(lua_State* L)
{
// monsterType:getCombatImmunities()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.damageImmunities);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetConditionImmunities(lua_State* L)
{
// monsterType:getConditionImmunities()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.conditionImmunities);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetAttackList(lua_State* L)
{
// monsterType:getAttackList()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, monsterType->info.attackSpells.size(), 0);
int index = 0;
for (const auto& spellBlock : monsterType->info.attackSpells) {
lua_createtable(L, 0, 8);
setField(L, "chance", spellBlock.chance);
setField(L, "isCombatSpell", spellBlock.combatSpell ? 1 : 0);
setField(L, "isMelee", spellBlock.isMelee ? 1 : 0);
setField(L, "minCombatValue", spellBlock.minCombatValue);
setField(L, "maxCombatValue", spellBlock.maxCombatValue);
setField(L, "range", spellBlock.range);
setField(L, "speed", spellBlock.speed);
pushUserdata<CombatSpell>(L, static_cast<CombatSpell*>(spellBlock.spell));
lua_setfield(L, -2, "spell");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetDefenseList(lua_State* L)
{
// monsterType:getDefenseList()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, monsterType->info.defenseSpells.size(), 0);
int index = 0;
for (const auto& spellBlock : monsterType->info.defenseSpells) {
lua_createtable(L, 0, 8);
setField(L, "chance", spellBlock.chance);
setField(L, "isCombatSpell", spellBlock.combatSpell ? 1 : 0);
setField(L, "isMelee", spellBlock.isMelee ? 1 : 0);
setField(L, "minCombatValue", spellBlock.minCombatValue);
setField(L, "maxCombatValue", spellBlock.maxCombatValue);
setField(L, "range", spellBlock.range);
setField(L, "speed", spellBlock.speed);
pushUserdata<CombatSpell>(L, static_cast<CombatSpell*>(spellBlock.spell));
lua_setfield(L, -2, "spell");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetElementList(lua_State* L)
{
// monsterType:getElementList()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
lua_createtable(L, monsterType->info.elementMap.size(), 0);
for (const auto& elementEntry : monsterType->info.elementMap) {
lua_pushnumber(L, elementEntry.second);
lua_rawseti(L, -2, elementEntry.first);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetVoices(lua_State* L)
{
// monsterType:getVoices()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
int index = 0;
lua_createtable(L, monsterType->info.voiceVector.size(), 0);
for (const auto& voiceBlock : monsterType->info.voiceVector) {
lua_createtable(L, 0, 2);
setField(L, "text", voiceBlock.text);
setField(L, "yellText", voiceBlock.yellText);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetLoot(lua_State* L)
{
// monsterType:getLoot()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
static const std::function<void(const std::vector<LootBlock>&)> parseLoot = [&](const std::vector<LootBlock>& lootList) {
lua_createtable(L, lootList.size(), 0);
int index = 0;
for (const auto& lootBlock : lootList) {
lua_createtable(L, 0, 7);
setField(L, "itemId", lootBlock.id);
setField(L, "chance", lootBlock.chance);
setField(L, "subType", lootBlock.subType);
setField(L, "maxCount", lootBlock.countmax);
setField(L, "actionId", lootBlock.actionId);
setField(L, "text", lootBlock.text);
parseLoot(lootBlock.childLoot);
lua_setfield(L, -2, "childLoot");
lua_rawseti(L, -2, ++index);
}
};
parseLoot(monsterType->info.lootItems);
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetCreatureEvents(lua_State* L)
{
// monsterType:getCreatureEvents()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
int index = 0;
lua_createtable(L, monsterType->info.scripts.size(), 0);
for (const std::string& creatureEvent : monsterType->info.scripts) {
pushString(L, creatureEvent);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetSummonList(lua_State* L)
{
// monsterType:getSummonList()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
int index = 0;
lua_createtable(L, monsterType->info.summons.size(), 0);
for (const auto& summonBlock : monsterType->info.summons) {
lua_createtable(L, 0, 3);
setField(L, "name", summonBlock.name);
setField(L, "speed", summonBlock.speed);
setField(L, "chance", summonBlock.chance);
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetMaxSummons(lua_State* L)
{
// monsterType:getMaxSummons()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.maxSummons);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetArmor(lua_State* L)
{
// monsterType:getArmor()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.armor);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetDefense(lua_State* L)
{
// monsterType:getDefense()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.defense);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetOutfit(lua_State* L)
{
// monsterType:getOutfit()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
pushOutfit(L, monsterType->info.outfit);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetRace(lua_State* L)
{
// monsterType:getRace()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.race);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetCorpseId(lua_State* L)
{
// monsterType:getCorpseId()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.lookcorpse);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetManaCost(lua_State* L)
{
// monsterType:getManaCost()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.manaCost);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetBaseSpeed(lua_State* L)
{
// monsterType:getBaseSpeed()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.baseSpeed);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetLight(lua_State* L)
{
// monsterType:getLight()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (!monsterType) {
lua_pushnil(L);
return 1;
}
lua_pushnumber(L, monsterType->info.light.level);
lua_pushnumber(L, monsterType->info.light.color);
return 2;
}
int LuaScriptInterface::luaMonsterTypeGetStaticAttackChance(lua_State* L)
{
// monsterType:getStaticAttackChance()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.staticAttackChance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetTargetDistance(lua_State* L)
{
// monsterType:getTargetDistance()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.targetDistance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetYellChance(lua_State* L)
{
// monsterType:getYellChance()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.yellChance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetYellSpeedTicks(lua_State* L)
{
// monsterType:getYellSpeedTicks()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.yellSpeedTicks);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetChangeTargetChance(lua_State* L)
{
// monsterType:getChangeTargetChance()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.changeTargetChance);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaMonsterTypeGetChangeTargetSpeed(lua_State* L)
{
// monsterType:getChangeTargetSpeed()
MonsterType* monsterType = getUserdata<MonsterType>(L, 1);
if (monsterType) {
lua_pushnumber(L, monsterType->info.changeTargetSpeed);
} else {
lua_pushnil(L);
}
return 1;
}
// Party
int LuaScriptInterface::luaPartyDisband(lua_State* L)
{
// party:disband()
Party** partyPtr = getRawUserdata<Party>(L, 1);
if (partyPtr && *partyPtr) {
Party*& party = *partyPtr;
party->disband();
party = nullptr;
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyGetLeader(lua_State* L)
{
// party:getLeader()
Party* party = getUserdata<Party>(L, 1);
if (!party) {
lua_pushnil(L);
return 1;
}
Player* leader = party->getLeader();
if (leader) {
pushUserdata<Player>(L, leader);
setMetatable(L, -1, "Player");
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartySetLeader(lua_State* L)
{
// party:setLeader(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->passPartyLeadership(player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyGetMembers(lua_State* L)
{
// party:getMembers()
Party* party = getUserdata<Party>(L, 1);
if (!party) {
lua_pushnil(L);
return 1;
}
int index = 0;
lua_createtable(L, party->getMemberCount(), 0);
for (Player* player : party->getMembers()) {
pushUserdata<Player>(L, player);
setMetatable(L, -1, "Player");
lua_rawseti(L, -2, ++index);
}
return 1;
}
int LuaScriptInterface::luaPartyGetMemberCount(lua_State* L)
{
// party:getMemberCount()
Party* party = getUserdata<Party>(L, 1);
if (party) {
lua_pushnumber(L, party->getMemberCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyGetInvitees(lua_State* L)
{
// party:getInvitees()
Party* party = getUserdata<Party>(L, 1);
if (party) {
lua_createtable(L, party->getInvitationCount(), 0);
int index = 0;
for (Player* player : party->getInvitees()) {
pushUserdata<Player>(L, player);
setMetatable(L, -1, "Player");
lua_rawseti(L, -2, ++index);
}
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyGetInviteeCount(lua_State* L)
{
// party:getInviteeCount()
Party* party = getUserdata<Party>(L, 1);
if (party) {
lua_pushnumber(L, party->getInvitationCount());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyAddInvite(lua_State* L)
{
// party:addInvite(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->invitePlayer(*player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyRemoveInvite(lua_State* L)
{
// party:removeInvite(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->removeInvite(*player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyAddMember(lua_State* L)
{
// party:addMember(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->joinParty(*player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyRemoveMember(lua_State* L)
{
// party:removeMember(player)
Player* player = getPlayer(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party && player) {
pushBoolean(L, party->leaveParty(player));
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyIsSharedExperienceActive(lua_State* L)
{
// party:isSharedExperienceActive()
Party* party = getUserdata<Party>(L, 1);
if (party) {
pushBoolean(L, party->isSharedExperienceActive());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyIsSharedExperienceEnabled(lua_State* L)
{
// party:isSharedExperienceEnabled()
Party* party = getUserdata<Party>(L, 1);
if (party) {
pushBoolean(L, party->isSharedExperienceEnabled());
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartyShareExperience(lua_State* L)
{
// party:shareExperience(experience)
uint64_t experience = getNumber<uint64_t>(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party) {
party->shareExperience(experience);
pushBoolean(L, true);
} else {
lua_pushnil(L);
}
return 1;
}
int LuaScriptInterface::luaPartySetSharedExperience(lua_State* L)
{
// party:setSharedExperience(active)
bool active = getBoolean(L, 2);
Party* party = getUserdata<Party>(L, 1);
if (party) {
pushBoolean(L, party->setSharedExperience(party->getLeader(), active));
} else {
lua_pushnil(L);
}
return 1;
}
//
LuaEnvironment::LuaEnvironment() : LuaScriptInterface("Main Interface") {}
LuaEnvironment::~LuaEnvironment()
{
delete testInterface;
closeState();
}
bool LuaEnvironment::initState()
{
luaState = luaL_newstate();
if (!luaState) {
return false;
}
luaL_openlibs(luaState);
registerFunctions();
runningEventId = EVENT_ID_USER;
return true;
}
bool LuaEnvironment::reInitState()
{
// TODO: get children, reload children
closeState();
return initState();
}
bool LuaEnvironment::closeState()
{
if (!luaState) {
return false;
}
for (const auto& combatEntry : combatIdMap) {
clearCombatObjects(combatEntry.first);
}
for (const auto& areaEntry : areaIdMap) {
clearAreaObjects(areaEntry.first);
}
for (auto& timerEntry : timerEvents) {
LuaTimerEventDesc timerEventDesc = std::move(timerEntry.second);
for (int32_t parameter : timerEventDesc.parameters) {
luaL_unref(luaState, LUA_REGISTRYINDEX, parameter);
}
luaL_unref(luaState, LUA_REGISTRYINDEX, timerEventDesc.function);
}
combatIdMap.clear();
areaIdMap.clear();
timerEvents.clear();
cacheFiles.clear();
lua_close(luaState);
luaState = nullptr;
return true;
}
LuaScriptInterface* LuaEnvironment::getTestInterface()
{
if (!testInterface) {
testInterface = new LuaScriptInterface("Test Interface");
testInterface->initState();
}
return testInterface;
}
Combat* LuaEnvironment::getCombatObject(uint32_t id) const
{
auto it = combatMap.find(id);
if (it == combatMap.end()) {
return nullptr;
}
return it->second;
}
Combat* LuaEnvironment::createCombatObject(LuaScriptInterface* interface)
{
Combat* combat = new Combat;
combatMap[++lastCombatId] = combat;
combatIdMap[interface].push_back(lastCombatId);
return combat;
}
void LuaEnvironment::clearCombatObjects(LuaScriptInterface* interface)
{
auto it = combatIdMap.find(interface);
if (it == combatIdMap.end()) {
return;
}
for (uint32_t id : it->second) {
auto itt = combatMap.find(id);
if (itt != combatMap.end()) {
delete itt->second;
combatMap.erase(itt);
}
}
it->second.clear();
}
AreaCombat* LuaEnvironment::getAreaObject(uint32_t id) const
{
auto it = areaMap.find(id);
if (it == areaMap.end()) {
return nullptr;
}
return it->second;
}
uint32_t LuaEnvironment::createAreaObject(LuaScriptInterface* interface)
{
areaMap[++lastAreaId] = new AreaCombat;
areaIdMap[interface].push_back(lastAreaId);
return lastAreaId;
}
void LuaEnvironment::clearAreaObjects(LuaScriptInterface* interface)
{
auto it = areaIdMap.find(interface);
if (it == areaIdMap.end()) {
return;
}
for (uint32_t id : it->second) {
auto itt = areaMap.find(id);
if (itt != areaMap.end()) {
delete itt->second;
areaMap.erase(itt);
}
}
it->second.clear();
}
void LuaEnvironment::executeTimerEvent(uint32_t eventIndex)
{
auto it = timerEvents.find(eventIndex);
if (it == timerEvents.end()) {
return;
}
LuaTimerEventDesc timerEventDesc = std::move(it->second);
timerEvents.erase(it);
//push function
lua_rawgeti(luaState, LUA_REGISTRYINDEX, timerEventDesc.function);
//push parameters
for (auto parameter : boost::adaptors::reverse(timerEventDesc.parameters)) {
lua_rawgeti(luaState, LUA_REGISTRYINDEX, parameter);
}
//call the function
if (reserveScriptEnv()) {
ScriptEnvironment* env = getScriptEnv();
env->setTimerEvent();
env->setScriptId(timerEventDesc.scriptId, this);
callFunction(timerEventDesc.parameters.size());
} else {
std::cout << "[Error - LuaScriptInterface::executeTimerEvent] Call stack overflow" << std::endl;
}
//free resources
luaL_unref(luaState, LUA_REGISTRYINDEX, timerEventDesc.function);
for (auto parameter : timerEventDesc.parameters) {
luaL_unref(luaState, LUA_REGISTRYINDEX, parameter);
}
}
| 1 | 13,693 | Sorry if I'm being too pedantic here, but wouldn't it be nice to have standard parameter name? Like using `defaultValue` everywhere. | otland-forgottenserver | cpp |
@@ -119,9 +119,14 @@ func defaultBServer(ctx Context) string {
case libkb.DevelRunMode:
return memoryAddr
case libkb.StagingRunMode:
- return "bserver-0.dev.keybase.io:443"
+ return `
+ bserver-0.dev.keybase.io:443,bserver-1.dev.keybase.io:443;
+ bserver.dev.keybase.io:443`
case libkb.ProductionRunMode:
- return "bserver.kbfs.keybase.io:443"
+ return `
+ bserver-0.kbfs.keybaseapi.com:443,bserver-1.kbfs.keybaseapi.com:443;
+ bserver-0.kbfs.keybase.io:443,bserver-1.kbfs.keybase.io:443;
+ bserver.kbfs.keybase.io:443`
default:
return ""
} | 1 | // Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"context"
"errors"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"strings"
"time"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/go-framed-msgpack-rpc/rpc"
)
const (
// InitDefaultString is the normal mode for when KBFS data will be
// read and written.
InitDefaultString string = "default"
// InitMinimalString is for when KBFS will only be used as a MD
// lookup layer (e.g., for chat on mobile).
InitMinimalString = "minimal"
// InitSingleOpString is for when KBFS will only be used for a
// single logical operation (e.g., as a git remote helper).
InitSingleOpString = "singleOp"
)
// InitParams contains the initialization parameters for Init(). It is
// usually filled in by the flags parser passed into AddFlags().
type InitParams struct {
// Whether to print debug messages.
Debug bool
// If non-empty, the host:port of the block server. If empty,
// a default value is used depending on the run mode. Can also
// be "memory" for an in-memory test server or
// "dir:/path/to/dir" for an on-disk test server.
BServerAddr string
// If non-empty the host:port of the metadata server. If
// empty, a default value is used depending on the run mode.
// Can also be "memory" for an in-memory test server or
// "dir:/path/to/dir" for an on-disk test server.
MDServerAddr string
// If non-zero, specifies the capacity (in bytes) of the block cache. If
// zero, the capacity is set using getDefaultBlockCacheCapacity().
CleanBlockCacheCapacity uint64
// Fake local user name.
LocalUser string
// Where to put favorites. Has an effect only when LocalUser
// is non-empty, in which case it must be either "memory" or
// "dir:/path/to/dir".
LocalFavoriteStorage string
// TLFValidDuration is the duration that TLFs are valid
// before marked for lazy revalidation.
TLFValidDuration time.Duration
// MetadataVersion is the default version of metadata to use
// when creating new metadata.
MetadataVersion MetadataVer
// LogToFile if true, logs to a default file location.
LogToFile bool
// LogFileConfig tells us where to log and rotation config.
LogFileConfig logger.LogFileConfig
// TLFJournalBackgroundWorkStatus is the status to use to
// pass into JournalServer.enableJournaling. Only has an effect when
// EnableJournal is non-empty.
TLFJournalBackgroundWorkStatus TLFJournalBackgroundWorkStatus
// CreateSimpleFSInstance creates a SimpleFSInterface from config.
// If this is nil then simplefs will be omitted in the rpc api.
CreateSimpleFSInstance func(Config) keybase1.SimpleFSInterface
// CreateGitHandlerInstance creates a KBFSGitInterface from config.
// If this is nil then git will be omitted in the rpc api.
CreateGitHandlerInstance func(Config) keybase1.KBFSGitInterface
// EnableJournal enables journaling.
EnableJournal bool
// DiskCacheMode specifies which mode to start the disk cache.
DiskCacheMode DiskCacheMode
// StorageRoot, if non-empty, points to a local directory to put its local
// databases for things like the journal or disk cache.
StorageRoot string
// BGFlushPeriod indicates how long to wait for a batch to fill up
// before syncing a set of changes on a TLF to the servers.
BGFlushPeriod time.Duration
// BGFlushDirOpBatchSize indicates how many directory operations
// in a TLF should be batched together in a single background
// flush.
BGFlushDirOpBatchSize int
// Mode describes how KBFS should initialize itself.
Mode string
}
// defaultBServer returns the default value for the -bserver flag.
func defaultBServer(ctx Context) string {
switch ctx.GetRunMode() {
case libkb.DevelRunMode:
return memoryAddr
case libkb.StagingRunMode:
return "bserver-0.dev.keybase.io:443"
case libkb.ProductionRunMode:
return "bserver.kbfs.keybase.io:443"
default:
return ""
}
}
// defaultMDServer returns the default value for the -mdserver flag.
func defaultMDServer(ctx Context) string {
switch ctx.GetRunMode() {
case libkb.DevelRunMode:
return memoryAddr
case libkb.StagingRunMode:
return "mdserver-0.dev.keybase.io:443"
case libkb.ProductionRunMode:
return "mdserver.kbfs.keybase.io:443"
default:
return ""
}
}
// defaultMetadataVersion returns the default metadata version per run mode.
func defaultMetadataVersion(ctx Context) MetadataVer {
switch ctx.GetRunMode() {
case libkb.DevelRunMode:
return SegregatedKeyBundlesVer
case libkb.StagingRunMode:
return SegregatedKeyBundlesVer
case libkb.ProductionRunMode:
return SegregatedKeyBundlesVer
default:
return SegregatedKeyBundlesVer
}
}
func defaultLogPath(ctx Context) string {
return filepath.Join(ctx.GetLogDir(), libkb.KBFSLogFileName)
}
// DefaultInitParams returns default init params
func DefaultInitParams(ctx Context) InitParams {
return InitParams{
Debug: BoolForString(os.Getenv("KBFS_DEBUG")),
BServerAddr: defaultBServer(ctx),
MDServerAddr: defaultMDServer(ctx),
TLFValidDuration: tlfValidDurationDefault,
MetadataVersion: defaultMetadataVersion(ctx),
LogFileConfig: logger.LogFileConfig{
MaxAge: 30 * 24 * time.Hour,
MaxSize: 128 * 1024 * 1024,
MaxKeepFiles: 3,
},
TLFJournalBackgroundWorkStatus: TLFJournalBackgroundWorkEnabled,
StorageRoot: ctx.GetDataDir(),
BGFlushPeriod: bgFlushPeriodDefault,
BGFlushDirOpBatchSize: bgFlushDirOpBatchSizeDefault,
EnableJournal: true,
DiskCacheMode: DiskCacheModeLocal,
Mode: InitDefaultString,
}
}
// AddFlagsWithDefaults adds libkbfs flags to the given FlagSet, given
// a set of default flags. Returns an InitParams that will be filled
// in once the given FlagSet is parsed.
func AddFlagsWithDefaults(
flags *flag.FlagSet, defaultParams InitParams,
defaultLogPath string) *InitParams {
var params InitParams
flags.BoolVar(¶ms.Debug, "debug", defaultParams.Debug,
"Print debug messages")
flags.StringVar(¶ms.BServerAddr, "bserver", defaultParams.BServerAddr,
"host:port of the block server, 'memory', or 'dir:/path/to/dir'")
flags.StringVar(¶ms.MDServerAddr, "mdserver",
defaultParams.MDServerAddr,
"host:port of the metadata server, 'memory', or 'dir:/path/to/dir'")
flags.StringVar(¶ms.LocalUser, "localuser", defaultParams.LocalUser,
"fake local user")
flags.StringVar(¶ms.LocalFavoriteStorage, "local-fav-storage",
defaultParams.LocalFavoriteStorage,
"where to put favorites; used only when -localuser is set, then must "+
"either be 'memory' or 'dir:/path/to/dir'")
flags.DurationVar(¶ms.TLFValidDuration, "tlf-valid",
defaultParams.TLFValidDuration,
"time tlfs are valid before redoing identification")
flags.BoolVar(¶ms.LogToFile, "log-to-file", defaultParams.LogToFile,
fmt.Sprintf("Log to default file: %s", defaultLogPath))
flags.StringVar(¶ms.LogFileConfig.Path, "log-file", "",
"Path to log file")
flags.DurationVar(¶ms.LogFileConfig.MaxAge, "log-file-max-age",
defaultParams.LogFileConfig.MaxAge,
"Maximum age of a log file before rotation")
params.LogFileConfig.MaxSize = defaultParams.LogFileConfig.MaxSize
flags.Var(SizeFlag{¶ms.LogFileConfig.MaxSize}, "log-file-max-size",
"Maximum size of a log file before rotation")
// The default is to *DELETE* old log files for kbfs.
flags.IntVar(¶ms.LogFileConfig.MaxKeepFiles, "log-file-max-keep-files",
defaultParams.LogFileConfig.MaxKeepFiles, "Maximum number of log "+
"files for this service, older ones are deleted. 0 for infinite.")
flags.Uint64Var(¶ms.CleanBlockCacheCapacity, "clean-bcache-cap",
defaultParams.CleanBlockCacheCapacity,
"If non-zero, specify the capacity of clean block cache. If zero, "+
"the capacity is set based on system RAM.")
flags.StringVar(¶ms.StorageRoot, "storage-root",
defaultParams.StorageRoot, "Specifies where Keybase will store its "+
"local databases for the journal and disk cache.")
params.DiskCacheMode = defaultParams.DiskCacheMode
flags.Var(¶ms.DiskCacheMode, "disk-cache-mode",
"Sets the mode for the disk cache. If 'local', then it uses a "+
"subdirectory of -storage-root to store the cache. If 'remote', "+
"then it connects to the local KBFS instance and delegates disk "+
"cache operations to it.")
flags.BoolVar(¶ms.EnableJournal, "enable-journal",
defaultParams.EnableJournal, "Enables write journaling for TLFs.")
// No real need to enable setting
// params.TLFJournalBackgroundWorkStatus via a flag.
params.TLFJournalBackgroundWorkStatus =
defaultParams.TLFJournalBackgroundWorkStatus
flags.DurationVar(¶ms.BGFlushPeriod, "sync-batch-period",
defaultParams.BGFlushPeriod,
"The amount of time to wait before syncing data in a TLF, if the "+
"batch size doesn't fill up.")
flags.IntVar((*int)(¶ms.BGFlushDirOpBatchSize), "sync-batch-size",
int(defaultParams.BGFlushDirOpBatchSize),
"The number of unflushed directory operations in a TLF that will "+
"trigger an immediate data sync.")
flags.IntVar((*int)(¶ms.MetadataVersion), "md-version",
int(defaultParams.MetadataVersion),
"Metadata version to use when creating new metadata")
flags.StringVar(¶ms.Mode, "mode", defaultParams.Mode,
fmt.Sprintf("Overall initialization mode for KBFS, indicating how "+
"heavy-weight it can be (%s, %s or %s)", InitDefaultString,
InitMinimalString, InitSingleOpString))
return ¶ms
}
// AddFlags adds libkbfs flags to the given FlagSet. Returns an
// InitParams that will be filled in once the given FlagSet is parsed.
func AddFlags(flags *flag.FlagSet, ctx Context) *InitParams {
return AddFlagsWithDefaults(
flags, DefaultInitParams(ctx), defaultLogPath(ctx))
}
// GetRemoteUsageString returns a string describing the flags to use
// to run against remote KBFS servers.
func GetRemoteUsageString() string {
return ` [-debug]
[-bserver=host:port] [-mdserver=host:port]
[-log-to-file] [-log-file=path/to/file] [-clean-bcache-cap=0]`
}
// GetLocalUsageString returns a string describing the flags to use to
// run in a local testing environment.
func GetLocalUsageString() string {
return ` [-debug]
[-bserver=(memory | dir:/path/to/dir | host:port)]
[-mdserver=(memory | dir:/path/to/dir | host:port)]
[-localuser=<user>]
[-local-fav-storage=(memory | dir:/path/to/dir)]
[-log-to-file] [-log-file=path/to/file] [-clean-bcache-cap=0]`
}
// GetDefaultsUsageString returns a string describing the default
// values of flags based on the run mode.
func GetDefaultsUsageString(ctx Context) string {
runMode := ctx.GetRunMode()
defaultBServer := defaultBServer(ctx)
defaultMDServer := defaultMDServer(ctx)
return fmt.Sprintf(` (KEYBASE_RUN_MODE=%s)
-bserver=%s
-mdserver=%s`,
runMode, defaultBServer, defaultMDServer)
}
const memoryAddr = "memory"
const dirAddrPrefix = "dir:"
func parseRootDir(addr string) (string, bool) {
if !strings.HasPrefix(addr, dirAddrPrefix) {
return "", false
}
serverRootDir := addr[len(dirAddrPrefix):]
if len(serverRootDir) == 0 {
return "", false
}
return serverRootDir, true
}
func makeMDServer(config Config, mdserverAddr string,
rpcLogFactory rpc.LogFactory, log logger.Logger) (
MDServer, error) {
if mdserverAddr == memoryAddr {
log.Debug("Using in-memory mdserver")
// local in-memory MD server
return NewMDServerMemory(mdServerLocalConfigAdapter{config})
}
if len(mdserverAddr) == 0 {
return nil, errors.New("Empty MD server address")
}
if serverRootDir, ok := parseRootDir(mdserverAddr); ok {
log.Debug("Using on-disk mdserver at %s", serverRootDir)
// local persistent MD server
mdPath := filepath.Join(serverRootDir, "kbfs_md")
return NewMDServerDir(mdServerLocalConfigAdapter{config}, mdPath)
}
// remote MD server. this can't fail. reconnection attempts
// will be automatic.
log.Debug("Using remote mdserver %s", mdserverAddr)
mdServer := NewMDServerRemote(config, mdserverAddr, rpcLogFactory)
return mdServer, nil
}
func makeKeyServer(config Config, keyserverAddr string,
log logger.Logger) (KeyServer, error) {
if keyserverAddr == memoryAddr {
log.Debug("Using in-memory keyserver")
// local in-memory key server
return NewKeyServerMemory(config)
}
if len(keyserverAddr) == 0 {
return nil, errors.New("Empty key server address")
}
if serverRootDir, ok := parseRootDir(keyserverAddr); ok {
log.Debug("Using on-disk keyserver at %s", serverRootDir)
// local persistent key server
keyPath := filepath.Join(serverRootDir, "kbfs_key")
return NewKeyServerDir(config, keyPath)
}
log.Debug("Using remote keyserver %s (same as mdserver)", keyserverAddr)
// currently the MD server also acts as the key server.
keyServer, ok := config.MDServer().(KeyServer)
if !ok {
return nil, errors.New("MD server is not a key server")
}
return keyServer, nil
}
func makeBlockServer(config Config, bserverAddr string,
rpcLogFactory rpc.LogFactory,
log logger.Logger) (BlockServer, error) {
if bserverAddr == memoryAddr {
log.Debug("Using in-memory bserver")
bserverLog := config.MakeLogger("BSM")
// local in-memory block server
return NewBlockServerMemory(bserverLog), nil
}
if len(bserverAddr) == 0 {
return nil, errors.New("Empty block server address")
}
if serverRootDir, ok := parseRootDir(bserverAddr); ok {
log.Debug("Using on-disk bserver at %s", serverRootDir)
// local persistent block server
blockPath := filepath.Join(serverRootDir, "kbfs_block")
bserverLog := config.MakeLogger("BSD")
return NewBlockServerDir(config.Codec(),
bserverLog, blockPath), nil
}
log.Debug("Using remote bserver %s", bserverAddr)
return NewBlockServerRemote(config, bserverAddr, rpcLogFactory), nil
}
// InitLogWithPrefix sets up logging switching to a log file if
// necessary, given a prefix and a default log path. Returns a valid
// logger even on error, which are non-fatal, thus errors from this
// function may be ignored. Possible errors are logged to the logger
// returned.
func InitLogWithPrefix(
params InitParams, ctx Context, prefix string,
defaultLogPath string) (logger.Logger, error) {
var err error
// Set log file to default if log-to-file was specified
if params.LogToFile {
if params.LogFileConfig.Path != "" {
return nil, fmt.Errorf(
"log-to-file and log-file flags can't be specified together")
}
params.LogFileConfig.Path = defaultLogPath
}
if params.LogFileConfig.Path != "" {
err = logger.SetLogFileConfig(¶ms.LogFileConfig)
}
log := logger.NewWithCallDepth(prefix, 1)
log.Configure("", params.Debug, "")
log.Info("KBFS version %s", VersionString())
if err != nil {
log.Warning("Failed to setup log file %q: %+v",
params.LogFileConfig.Path, err)
}
return log, err
}
// InitLog sets up logging switching to a log file if necessary.
// Returns a valid logger even on error, which are non-fatal, thus
// errors from this function may be ignored.
// Possible errors are logged to the logger returned.
func InitLog(params InitParams, ctx Context) (logger.Logger, error) {
return InitLogWithPrefix(params, ctx, "kbfs", defaultLogPath(ctx))
}
// InitWithLogPrefix initializes a config and returns it, given a prefix.
//
// onInterruptFn is called whenever an interrupt signal is received
// (e.g., if the user hits Ctrl-C).
//
// Init should be called at the beginning of main. Shutdown (see
// below) should then be called at the end of main (usually via
// defer).
//
// The keybaseServiceCn argument is to specify a custom service and
// crypto (for non-RPC environments) like mobile. If this is nil, we'll
// use the default RPC implementation.
func InitWithLogPrefix(
ctx context.Context, kbCtx Context, params InitParams,
keybaseServiceCn KeybaseServiceCn, onInterruptFn func(),
log logger.Logger, logPrefix string) (cfg Config, err error) {
done := make(chan struct{})
interruptChan := make(chan os.Signal, 1)
signal.Notify(interruptChan, os.Interrupt)
go func() {
_ = <-interruptChan
close(done)
if onInterruptFn != nil {
onInterruptFn()
// Unmount can fail if there are open file handles. In
// this case, the files need to be closed before calling
// unmount again. We keep listening on the signal channel
// in case unmount fails the first time, so user can press
// Ctrl-C again after closing open files.
//
// Not closing the channel here because we need to keep it
// open to handle further incoming signals. We don't
// explicitly call os.Exit here so that the process exits
// through normal workflow as a result of Ctrl-C. If the
// process needs to exit immediately no matter unmount
// succeeds or not, a different interrupt (e.g. SIGTERM)
// can be used to skip this.
for range interruptChan {
onInterruptFn()
}
}
}()
// Spawn a new goroutine for `doInit` so that we can `select` on
// `done` and `errCh` below. This is particularly for the
// situation where a SIGINT comes in while `doInit` is still not
// finished (because e.g. service daemon is not up), where the
// process can fail to exit while being stuck in `doInit`. This
// allows us to not call `os.Exit()` in the interrupt handler.
errCh := make(chan error)
go func() {
var er error
cfg, er = doInit(ctx, kbCtx, params, keybaseServiceCn, log, logPrefix)
errCh <- er
}()
select {
case <-done:
return nil, errors.New(os.Interrupt.String())
case err = <-errCh:
return cfg, err
}
}
// Init initializes a config and returns it.
//
// onInterruptFn is called whenever an interrupt signal is received
// (e.g., if the user hits Ctrl-C).
//
// Init should be called at the beginning of main. Shutdown (see
// below) should then be called at the end of main (usually via
// defer).
//
// The keybaseServiceCn argument is to specify a custom service and
// crypto (for non-RPC environments) like mobile. If this is nil, we'll
// use the default RPC implementation.
func Init(
ctx context.Context, kbCtx Context, params InitParams,
keybaseServiceCn KeybaseServiceCn, onInterruptFn func(),
log logger.Logger) (cfg Config, err error) {
return InitWithLogPrefix(
ctx, kbCtx, params, keybaseServiceCn, onInterruptFn, log, "kbfs")
}
func doInit(
ctx context.Context, kbCtx Context, params InitParams,
keybaseServiceCn KeybaseServiceCn, log logger.Logger,
logPrefix string) (Config, error) {
mode := InitDefault
switch params.Mode {
case InitDefaultString:
log.CDebugf(ctx, "Initializing in default mode")
// Already the default
case InitMinimalString:
log.CDebugf(ctx, "Initializing in minimal mode")
mode = InitMinimal
case InitSingleOpString:
log.CDebugf(ctx, "Initializing in singleOp mode")
mode = InitSingleOp
default:
return nil, fmt.Errorf("Unexpected mode: %s", params.Mode)
}
config := NewConfigLocal(mode, func(module string) logger.Logger {
mname := logPrefix
if module != "" {
mname += fmt.Sprintf("(%s)", module)
}
// Add log depth so that context-based messages get the right
// file printed out.
lg := logger.NewWithCallDepth(mname, 1)
if params.Debug {
// Turn on debugging. TODO: allow a proper log file and
// style to be specified.
lg.Configure("", true, "")
}
return lg
}, params.StorageRoot, params.DiskCacheMode, kbCtx)
if params.CleanBlockCacheCapacity > 0 {
log.CDebugf(
ctx, "overriding default clean block cache capacity from %d to %d",
config.BlockCache().GetCleanBytesCapacity(),
params.CleanBlockCacheCapacity)
config.BlockCache().SetCleanBytesCapacity(
params.CleanBlockCacheCapacity)
}
workers := defaultBlockRetrievalWorkerQueueSize
prefetchWorkers := defaultPrefetchWorkerQueueSize
if config.Mode() == InitMinimal {
// In minimal mode, a few workers are still needed to fetch
// unembedded block changes in the MD updates, but not many.
// TODO: turn off the block retriever entirely as part of
// KBFS-2026, when block re-embedding is no longer required.
workers = minimalBlockRetrievalWorkerQueueSize
prefetchWorkers = minimalPrefetchWorkerQueueSize
}
config.SetBlockOps(NewBlockOpsStandard(config, workers, prefetchWorkers))
bsplitter, err := NewBlockSplitterSimple(MaxBlockSizeBytesDefault, 8*1024,
config.Codec())
if err != nil {
return nil, err
}
config.SetBlockSplitter(bsplitter)
if registry := config.MetricsRegistry(); registry != nil {
keyCache := config.KeyCache()
keyCache = NewKeyCacheMeasured(keyCache, registry)
config.SetKeyCache(keyCache)
keyBundleCache := config.KeyBundleCache()
keyBundleCache = NewKeyBundleCacheMeasured(keyBundleCache, registry)
config.SetKeyBundleCache(keyBundleCache)
}
config.SetMetadataVersion(MetadataVer(params.MetadataVersion))
config.SetTLFValidDuration(params.TLFValidDuration)
config.SetBGFlushPeriod(params.BGFlushPeriod)
kbfsOps := NewKBFSOpsStandard(config)
config.SetKBFSOps(kbfsOps)
config.SetNotifier(kbfsOps)
config.SetKeyManager(NewKeyManagerStandard(config))
config.SetMDOps(NewMDOpsStandard(config))
kbfsLog := config.MakeLogger("")
if keybaseServiceCn == nil {
keybaseServiceCn = keybaseDaemon{}
}
service, err := keybaseServiceCn.NewKeybaseService(
config, params, kbCtx, kbfsLog)
if err != nil {
return nil, fmt.Errorf("problem creating service: %s", err)
}
err = config.MakeDiskBlockCacheIfNotExists()
if err != nil {
log.CWarningf(ctx, "Could not initialize disk cache: %+v", err)
notification := &keybase1.FSNotification{
StatusCode: keybase1.FSStatusCode_ERROR,
NotificationType: keybase1.FSNotificationType_INITIALIZED,
ErrorType: keybase1.FSErrorType_DISK_CACHE_ERROR_LOG_SEND,
}
defer config.Reporter().Notify(ctx, notification)
} else {
log.CDebugf(ctx, "Disk cache of type \"%s\" enabled",
params.DiskCacheMode.String())
}
if config.Mode() == InitDefault {
// Initialize kbfsService only when we run a full KBFS process.
// This requires the disk block cache to have been initialized, if it
// should be initialized.
kbfsService, err := NewKBFSService(kbCtx, config)
if err != nil {
// This error shouldn't be fatal
log.CWarningf(ctx, "Error starting RPC server for KBFS: %+v", err)
} else {
config.SetKBFSService(kbfsService)
log.CDebugf(ctx, "Started RPC server for KBFS")
}
}
if registry := config.MetricsRegistry(); registry != nil {
service = NewKeybaseServiceMeasured(service, registry)
}
config.SetKeybaseService(service)
k := NewKBPKIClient(config, kbfsLog)
config.SetKBPKI(k)
config.SetReporter(NewReporterKBPKI(config, 10, 1000))
// crypto must be initialized before the MD and block servers
// are initialized, since those depend on crypto.
crypto, err := keybaseServiceCn.NewCrypto(config, params, kbCtx, kbfsLog)
if err != nil {
return nil, fmt.Errorf("problem creating crypto: %s", err)
}
config.SetCrypto(crypto)
mdServer, err := makeMDServer(
config, params.MDServerAddr, kbCtx.NewRPCLogFactory(), log)
if err != nil {
return nil, fmt.Errorf("problem creating MD server: %+v", err)
}
config.SetMDServer(mdServer)
// note: the mdserver is the keyserver at the moment.
keyServer, err := makeKeyServer(config, params.MDServerAddr, log)
if err != nil {
return nil, fmt.Errorf("problem creating key server: %+v", err)
}
if registry := config.MetricsRegistry(); registry != nil {
keyServer = NewKeyServerMeasured(keyServer, registry)
}
config.SetKeyServer(keyServer)
bserv, err := makeBlockServer(
config, params.BServerAddr, kbCtx.NewRPCLogFactory(), log)
if err != nil {
return nil, fmt.Errorf("cannot open block database: %+v", err)
}
if registry := config.MetricsRegistry(); registry != nil {
bserv = NewBlockServerMeasured(bserv, registry)
}
config.SetBlockServer(bserv)
err = config.EnableDiskLimiter(params.StorageRoot)
if err != nil {
log.CWarningf(ctx, "Could not enable disk limiter: %+v", err)
return nil, err
}
ctx10s, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
// TODO: Don't turn on journaling if either -bserver or
// -mdserver point to local implementations.
if params.EnableJournal && config.Mode() != InitMinimal {
journalRoot := filepath.Join(params.StorageRoot, "kbfs_journal")
err = config.EnableJournaling(ctx10s, journalRoot,
params.TLFJournalBackgroundWorkStatus)
if err != nil {
log.CWarningf(ctx, "Could not initialize journal server: %+v", err)
}
log.CDebugf(ctx, "Journaling enabled")
}
if params.BGFlushDirOpBatchSize < 1 {
return nil, fmt.Errorf(
"Illegal sync batch size: %d", params.BGFlushDirOpBatchSize)
}
log.CDebugf(ctx, "Enabling a dir op batch size of %d",
params.BGFlushDirOpBatchSize)
config.SetBGFlushDirOpBatchSize(params.BGFlushDirOpBatchSize)
return config, nil
}
// Shutdown does any necessary shutdown tasks for libkbfs. Shutdown
// should be called at the end of main.
func Shutdown() {}
| 1 | 18,353 | Remind me again: what's the point of having new clients connect to both -0 and -1? If we ever have to blackhole -0, we'd have to blackhole -1 at the same time, right? What is supposed to be the difference between the two? Is it just that someday we might want to have two ELBs, and this will help load balance between them? | keybase-kbfs | go |
@@ -1792,8 +1792,8 @@ func (s *Server) createClient(conn net.Conn) *client {
// Do final client initialization
- // Set the First Ping timer.
- s.setFirstPingTimer(c)
+ // Set the Ping timer. Will be reset once connect was received.
+ c.setPingTimer()
// Spin up the read loop.
s.startGoRoutine(func() { c.readLoop() }) | 1 | // Copyright 2012-2019 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"math/rand"
"net"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
// Allow dynamic profiling.
_ "net/http/pprof"
"github.com/nats-io/jwt"
"github.com/nats-io/nats-server/v2/logger"
"github.com/nats-io/nkeys"
)
const (
// Time to wait before starting closing clients when in LD mode.
lameDuckModeDefaultInitialDelay = int64(10 * time.Second)
// Interval for the first PING for non client connections.
firstPingInterval = time.Second
// This is for the first ping for client connections.
firstClientPingInterval = 2 * time.Second
)
// Make this a variable so that we can change during tests
var lameDuckModeInitialDelay = int64(lameDuckModeDefaultInitialDelay)
// Info is the information sent to clients, routes, gateways, and leaf nodes,
// to help them understand information about this server.
type Info struct {
ID string `json:"server_id"`
Name string `json:"server_name"`
Version string `json:"version"`
Proto int `json:"proto"`
GitCommit string `json:"git_commit,omitempty"`
GoVersion string `json:"go"`
Host string `json:"host"`
Port int `json:"port"`
AuthRequired bool `json:"auth_required,omitempty"`
TLSRequired bool `json:"tls_required,omitempty"`
TLSVerify bool `json:"tls_verify,omitempty"`
MaxPayload int32 `json:"max_payload"`
IP string `json:"ip,omitempty"`
CID uint64 `json:"client_id,omitempty"`
ClientIP string `json:"client_ip,omitempty"`
Nonce string `json:"nonce,omitempty"`
Cluster string `json:"cluster,omitempty"`
ClientConnectURLs []string `json:"connect_urls,omitempty"` // Contains URLs a client can connect to.
// Route Specific
Import *SubjectPermission `json:"import,omitempty"`
Export *SubjectPermission `json:"export,omitempty"`
// Gateways Specific
Gateway string `json:"gateway,omitempty"` // Name of the origin Gateway (sent by gateway's INFO)
GatewayURLs []string `json:"gateway_urls,omitempty"` // Gateway URLs in the originating cluster (sent by gateway's INFO)
GatewayURL string `json:"gateway_url,omitempty"` // Gateway URL on that server (sent by route's INFO)
GatewayCmd byte `json:"gateway_cmd,omitempty"` // Command code for the receiving server to know what to do
GatewayCmdPayload []byte `json:"gateway_cmd_payload,omitempty"` // Command payload when needed
GatewayNRP bool `json:"gateway_nrp,omitempty"` // Uses new $GNR. prefix for mapped replies
// LeafNode Specific
LeafNodeURLs []string `json:"leafnode_urls,omitempty"` // LeafNode URLs that the server can reconnect to.
}
// Server is our main struct.
type Server struct {
gcid uint64
stats
mu sync.Mutex
kp nkeys.KeyPair
prand *rand.Rand
info Info
configFile string
optsMu sync.RWMutex
opts *Options
running bool
shutdown bool
listener net.Listener
gacc *Account
sys *internal
accounts sync.Map
tmpAccounts sync.Map // Temporarily stores accounts that are being built
activeAccounts int32
accResolver AccountResolver
clients map[uint64]*client
routes map[uint64]*client
routesByHash sync.Map
hash []byte
remotes map[string]*client
leafs map[uint64]*client
users map[string]*User
nkeys map[string]*NkeyUser
totalClients uint64
closed *closedRingBuffer
done chan bool
start time.Time
http net.Listener
httpHandler http.Handler
profiler net.Listener
httpReqStats map[string]uint64
routeListener net.Listener
routeInfo Info
routeInfoJSON []byte
leafNodeListener net.Listener
leafNodeInfo Info
leafNodeInfoJSON []byte
leafNodeOpts struct {
resolver netResolver
dialTimeout time.Duration
}
quitCh chan struct{}
shutdownComplete chan struct{}
// Tracking Go routines
grMu sync.Mutex
grTmpClients map[uint64]*client
grRunning bool
grWG sync.WaitGroup // to wait on various go routines
cproto int64 // number of clients supporting async INFO
configTime time.Time // last time config was loaded
logging struct {
sync.RWMutex
logger Logger
trace int32
debug int32
traceSysAcc bool
}
clientConnectURLs []string
// Used internally for quick look-ups.
clientConnectURLsMap map[string]struct{}
lastCURLsUpdate int64
// For Gateways
gatewayListener net.Listener // Accept listener
gateway *srvGateway
// Used by tests to check that http.Servers do
// not set any timeout.
monitoringServer *http.Server
profilingServer *http.Server
// LameDuck mode
ldm bool
ldmCh chan bool
// Trusted public operator keys.
trustedKeys []string
// We use this to minimize mem copies for request to monitoring
// endpoint /varz (when it comes from http).
varzMu sync.Mutex
varz *Varz
// This is set during a config reload if we detect that we have
// added/removed routes. The monitoring code then check that
// to know if it should update the cluster's URLs array.
varzUpdateRouteURLs bool
// Keeps a sublist of of subscriptions attached to leafnode connections
// for the $GNR.*.*.*.> subject so that a server can send back a mapped
// gateway reply.
gwLeafSubs *Sublist
// Used for expiration of mapped GW replies
gwrm struct {
w int32
ch chan time.Duration
m sync.Map
}
}
// Make sure all are 64bits for atomic use
type stats struct {
inMsgs int64
outMsgs int64
inBytes int64
outBytes int64
slowConsumers int64
}
// New will setup a new server struct after parsing the options.
// DEPRECATED: Use NewServer(opts)
func New(opts *Options) *Server {
s, _ := NewServer(opts)
return s
}
// NewServer will setup a new server struct after parsing the options.
// Could return an error if options can not be validated.
func NewServer(opts *Options) (*Server, error) {
setBaselineOptions(opts)
// Process TLS options, including whether we require client certificates.
tlsReq := opts.TLSConfig != nil
verify := (tlsReq && opts.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert)
// Created server's nkey identity.
kp, _ := nkeys.CreateServer()
pub, _ := kp.PublicKey()
serverName := pub
if opts.ServerName != "" {
serverName = opts.ServerName
}
// Validate some options. This is here because we cannot assume that
// server will always be started with configuration parsing (that could
// report issues). Its options can be (incorrectly) set by hand when
// server is embedded. If there is an error, return nil.
if err := validateOptions(opts); err != nil {
return nil, err
}
info := Info{
ID: pub,
Version: VERSION,
Proto: PROTO,
GitCommit: gitCommit,
GoVersion: runtime.Version(),
Name: serverName,
Host: opts.Host,
Port: opts.Port,
AuthRequired: false,
TLSRequired: tlsReq,
TLSVerify: verify,
MaxPayload: opts.MaxPayload,
}
now := time.Now()
s := &Server{
kp: kp,
configFile: opts.ConfigFile,
info: info,
prand: rand.New(rand.NewSource(time.Now().UnixNano())),
opts: opts,
done: make(chan bool, 1),
start: now,
configTime: now,
gwLeafSubs: NewSublistWithCache(),
}
// Trusted root operator keys.
if !s.processTrustedKeys() {
return nil, fmt.Errorf("Error processing trusted operator keys")
}
s.mu.Lock()
defer s.mu.Unlock()
// Ensure that non-exported options (used in tests) are properly set.
s.setLeafNodeNonExportedOptions()
// Used internally for quick look-ups.
s.clientConnectURLsMap = make(map[string]struct{})
// Call this even if there is no gateway defined. It will
// initialize the structure so we don't have to check for
// it to be nil or not in various places in the code.
if err := s.newGateway(opts); err != nil {
return nil, err
}
if s.gateway.enabled {
s.info.Cluster = s.getGatewayName()
}
// This is normally done in the AcceptLoop, once the
// listener has been created (possibly with random port),
// but since some tests may expect the INFO to be properly
// set after New(), let's do it now.
s.setInfoHostPortAndGenerateJSON()
// For tracking clients
s.clients = make(map[uint64]*client)
// For tracking closed clients.
s.closed = newClosedRingBuffer(opts.MaxClosedClients)
// For tracking connections that are not yet registered
// in s.routes, but for which readLoop has started.
s.grTmpClients = make(map[uint64]*client)
// For tracking routes and their remote ids
s.routes = make(map[uint64]*client)
s.remotes = make(map[string]*client)
// For tracking leaf nodes.
s.leafs = make(map[uint64]*client)
// Used to kick out all go routines possibly waiting on server
// to shutdown.
s.quitCh = make(chan struct{})
// Closed when Shutdown() is complete. Allows WaitForShutdown() to block
// waiting for complete shutdown.
s.shutdownComplete = make(chan struct{})
// For tracking accounts
if err := s.configureAccounts(); err != nil {
return nil, err
}
// If there is an URL account resolver, do basic test to see if anyone is home.
// Do this after configureAccounts() which calls configureResolver(), which will
// set TLSConfig if specified.
if ar := opts.AccountResolver; ar != nil {
if ur, ok := ar.(*URLAccResolver); ok {
if _, err := ur.Fetch(""); err != nil {
return nil, err
}
}
}
// In local config mode, check that leafnode configuration
// refers to account that exist.
if len(opts.TrustedOperators) == 0 {
checkAccountExists := func(accName string) error {
if accName == _EMPTY_ {
return nil
}
if _, ok := s.accounts.Load(accName); !ok {
return fmt.Errorf("cannot find account %q specified in leafnode authorization", accName)
}
return nil
}
if err := checkAccountExists(opts.LeafNode.Account); err != nil {
return nil, err
}
for _, lu := range opts.LeafNode.Users {
if lu.Account == nil {
continue
}
if err := checkAccountExists(lu.Account.Name); err != nil {
return nil, err
}
}
for _, r := range opts.LeafNode.Remotes {
if r.LocalAccount == _EMPTY_ {
continue
}
if _, ok := s.accounts.Load(r.LocalAccount); !ok {
return nil, fmt.Errorf("no local account %q for remote leafnode", r.LocalAccount)
}
}
}
// Used to setup Authorization.
s.configureAuthorization()
// Start signal handler
s.handleSignals()
return s, nil
}
// ClientURL returns the URL used to connect clients. Helpful in testing
// when we designate a random client port (-1).
func (s *Server) ClientURL() string {
// FIXME(dlc) - should we add in user and pass if defined single?
opts := s.getOpts()
scheme := "nats://"
if opts.TLSConfig != nil {
scheme = "tls://"
}
return fmt.Sprintf("%s%s:%d", scheme, opts.Host, opts.Port)
}
func validateOptions(o *Options) error {
// Check that the trust configuration is correct.
if err := validateTrustedOperators(o); err != nil {
return err
}
// Check on leaf nodes which will require a system
// account when gateways are also configured.
if err := validateLeafNode(o); err != nil {
return err
}
// Check that gateway is properly configured. Returns no error
// if there is no gateway defined.
return validateGatewayOptions(o)
}
func (s *Server) getOpts() *Options {
s.optsMu.RLock()
opts := s.opts
s.optsMu.RUnlock()
return opts
}
func (s *Server) setOpts(opts *Options) {
s.optsMu.Lock()
s.opts = opts
s.optsMu.Unlock()
}
func (s *Server) globalAccount() *Account {
s.mu.Lock()
gacc := s.gacc
s.mu.Unlock()
return gacc
}
// Used to setup Accounts.
// Lock is held upon entry.
func (s *Server) configureAccounts() error {
// Create global account.
if s.gacc == nil {
s.gacc = NewAccount(globalAccountName)
s.registerAccountNoLock(s.gacc)
}
opts := s.opts
// Check opts and walk through them. We need to copy them here
// so that we do not keep a real one sitting in the options.
for _, acc := range s.opts.Accounts {
a := acc.shallowCopy()
acc.sl = nil
acc.clients = nil
s.registerAccountNoLock(a)
}
// Now that we have this we need to remap any referenced accounts in
// import or export maps to the new ones.
swapApproved := func(ea *exportAuth) {
for sub, a := range ea.approved {
var acc *Account
if v, ok := s.accounts.Load(a.Name); ok {
acc = v.(*Account)
}
ea.approved[sub] = acc
}
}
s.accounts.Range(func(k, v interface{}) bool {
acc := v.(*Account)
// Exports
for _, ea := range acc.exports.streams {
if ea != nil {
swapApproved(&ea.exportAuth)
}
}
for _, ea := range acc.exports.services {
if ea != nil {
swapApproved(&ea.exportAuth)
}
}
// Imports
for _, si := range acc.imports.streams {
if v, ok := s.accounts.Load(si.acc.Name); ok {
si.acc = v.(*Account)
}
}
for _, si := range acc.imports.services {
if v, ok := s.accounts.Load(si.acc.Name); ok {
si.acc = v.(*Account)
}
}
return true
})
// Check for configured account resolvers.
if err := s.configureResolver(); err != nil {
return err
}
// Set the system account if it was configured.
if opts.SystemAccount != _EMPTY_ {
// Lock may be acquired in lookupAccount, so release to call lookupAccount.
s.mu.Unlock()
_, err := s.lookupAccount(opts.SystemAccount)
s.mu.Lock()
if err != nil {
return fmt.Errorf("error resolving system account: %v", err)
}
}
return nil
}
// Setup the account resolver. For memory resolver, make sure the JWTs are
// properly formed but do not enforce expiration etc.
func (s *Server) configureResolver() error {
opts := s.getOpts()
s.accResolver = opts.AccountResolver
if opts.AccountResolver != nil {
// For URL resolver, set the TLSConfig if specified.
if opts.AccountResolverTLSConfig != nil {
if ar, ok := opts.AccountResolver.(*URLAccResolver); ok {
if t, ok := ar.c.Transport.(*http.Transport); ok {
t.CloseIdleConnections()
t.TLSClientConfig = opts.AccountResolverTLSConfig.Clone()
}
}
}
if len(opts.resolverPreloads) > 0 {
if _, ok := s.accResolver.(*MemAccResolver); !ok {
return fmt.Errorf("resolver preloads only available for resolver type MEM")
}
for k, v := range opts.resolverPreloads {
_, err := jwt.DecodeAccountClaims(v)
if err != nil {
return fmt.Errorf("preload account error for %q: %v", k, err)
}
s.accResolver.Store(k, v)
}
}
}
return nil
}
// This will check preloads for validation issues.
func (s *Server) checkResolvePreloads() {
opts := s.getOpts()
// We can just check the read-only opts versions here, that way we do not need
// to grab server lock or access s.accResolver.
for k, v := range opts.resolverPreloads {
claims, err := jwt.DecodeAccountClaims(v)
if err != nil {
s.Errorf("Preloaded account [%s] not valid", k)
}
// Check if it is expired.
vr := jwt.CreateValidationResults()
claims.Validate(vr)
if vr.IsBlocking(true) {
s.Warnf("Account [%s] has validation issues:", k)
for _, v := range vr.Issues {
s.Warnf(" - %s", v.Description)
}
}
}
}
func (s *Server) generateRouteInfoJSON() {
// New proto wants a nonce.
var raw [nonceLen]byte
nonce := raw[:]
s.generateNonce(nonce)
s.routeInfo.Nonce = string(nonce)
b, _ := json.Marshal(s.routeInfo)
pcs := [][]byte{[]byte("INFO"), b, []byte(CR_LF)}
s.routeInfoJSON = bytes.Join(pcs, []byte(" "))
}
// isTrustedIssuer will check that the issuer is a trusted public key.
// This is used to make sure an account was signed by a trusted operator.
func (s *Server) isTrustedIssuer(issuer string) bool {
s.mu.Lock()
defer s.mu.Unlock()
// If we are not running in trusted mode and there is no issuer, that is ok.
if len(s.trustedKeys) == 0 && issuer == "" {
return true
}
for _, tk := range s.trustedKeys {
if tk == issuer {
return true
}
}
return false
}
// processTrustedKeys will process binary stamped and
// options-based trusted nkeys. Returns success.
func (s *Server) processTrustedKeys() bool {
if trustedKeys != "" && !s.initStampedTrustedKeys() {
return false
} else if s.opts.TrustedKeys != nil {
for _, key := range s.opts.TrustedKeys {
if !nkeys.IsValidPublicOperatorKey(key) {
return false
}
}
s.trustedKeys = s.opts.TrustedKeys
}
return true
}
// checkTrustedKeyString will check that the string is a valid array
// of public operator nkeys.
func checkTrustedKeyString(keys string) []string {
tks := strings.Fields(keys)
if len(tks) == 0 {
return nil
}
// Walk all the keys and make sure they are valid.
for _, key := range tks {
if !nkeys.IsValidPublicOperatorKey(key) {
return nil
}
}
return tks
}
// initStampedTrustedKeys will check the stamped trusted keys
// and will set the server field 'trustedKeys'. Returns whether
// it succeeded or not.
func (s *Server) initStampedTrustedKeys() bool {
// Check to see if we have an override in options, which will cause us to fail.
if len(s.opts.TrustedKeys) > 0 {
return false
}
tks := checkTrustedKeyString(trustedKeys)
if len(tks) == 0 {
return false
}
s.trustedKeys = tks
return true
}
// PrintAndDie is exported for access in other packages.
func PrintAndDie(msg string) {
fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
}
// PrintServerAndExit will print our version and exit.
func PrintServerAndExit() {
fmt.Printf("nats-server: v%s\n", VERSION)
os.Exit(0)
}
// ProcessCommandLineArgs takes the command line arguments
// validating and setting flags for handling in case any
// sub command was present.
func ProcessCommandLineArgs(cmd *flag.FlagSet) (showVersion bool, showHelp bool, err error) {
if len(cmd.Args()) > 0 {
arg := cmd.Args()[0]
switch strings.ToLower(arg) {
case "version":
return true, false, nil
case "help":
return false, true, nil
default:
return false, false, fmt.Errorf("unrecognized command: %q", arg)
}
}
return false, false, nil
}
// Protected check on running state
func (s *Server) isRunning() bool {
s.mu.Lock()
running := s.running
s.mu.Unlock()
return running
}
func (s *Server) logPid() error {
pidStr := strconv.Itoa(os.Getpid())
return ioutil.WriteFile(s.getOpts().PidFile, []byte(pidStr), 0660)
}
// NewAccountsAllowed returns whether or not new accounts can be created on the fly.
func (s *Server) NewAccountsAllowed() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.opts.AllowNewAccounts
}
// numReservedAccounts will return the number of reserved accounts configured in the server.
// Currently this is 1 for the global default service.
func (s *Server) numReservedAccounts() int {
return 1
}
// NumActiveAccounts reports number of active accounts on this server.
func (s *Server) NumActiveAccounts() int32 {
return atomic.LoadInt32(&s.activeAccounts)
}
// incActiveAccounts() just adds one under lock.
func (s *Server) incActiveAccounts() {
atomic.AddInt32(&s.activeAccounts, 1)
}
// decActiveAccounts() just subtracts one under lock.
func (s *Server) decActiveAccounts() {
atomic.AddInt32(&s.activeAccounts, -1)
}
// This should be used for testing only. Will be slow since we have to
// range over all accounts in the sync.Map to count.
func (s *Server) numAccounts() int {
count := 0
s.mu.Lock()
s.accounts.Range(func(k, v interface{}) bool {
count++
return true
})
s.mu.Unlock()
return count
}
// NumLoadedAccounts returns the number of loaded accounts.
func (s *Server) NumLoadedAccounts() int {
return s.numAccounts()
}
// LookupOrRegisterAccount will return the given account if known or create a new entry.
func (s *Server) LookupOrRegisterAccount(name string) (account *Account, isNew bool) {
s.mu.Lock()
defer s.mu.Unlock()
if v, ok := s.accounts.Load(name); ok {
return v.(*Account), false
}
acc := NewAccount(name)
s.registerAccountNoLock(acc)
return acc, true
}
// RegisterAccount will register an account. The account must be new
// or this call will fail.
func (s *Server) RegisterAccount(name string) (*Account, error) {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.accounts.Load(name); ok {
return nil, ErrAccountExists
}
acc := NewAccount(name)
s.registerAccountNoLock(acc)
return acc, nil
}
// SetSystemAccount will set the internal system account.
// If root operators are present it will also check validity.
func (s *Server) SetSystemAccount(accName string) error {
// Lookup from sync.Map first.
if v, ok := s.accounts.Load(accName); ok {
return s.setSystemAccount(v.(*Account))
}
// If we are here we do not have local knowledge of this account.
// Do this one by hand to return more useful error.
ac, jwt, err := s.fetchAccountClaims(accName)
if err != nil {
return err
}
acc := s.buildInternalAccount(ac)
acc.claimJWT = jwt
// Due to race, we need to make sure that we are not
// registering twice.
if racc := s.registerAccount(acc); racc != nil {
return nil
}
return s.setSystemAccount(acc)
}
// SystemAccount returns the system account if set.
func (s *Server) SystemAccount() *Account {
s.mu.Lock()
defer s.mu.Unlock()
if s.sys != nil {
return s.sys.account
}
return nil
}
// For internal sends.
const internalSendQLen = 4096
// Assign a system account. Should only be called once.
// This sets up a server to send and receive messages from
// inside the server itself.
func (s *Server) setSystemAccount(acc *Account) error {
if acc == nil {
return ErrMissingAccount
}
// Don't try to fix this here.
if acc.IsExpired() {
return ErrAccountExpired
}
// If we are running with trusted keys for an operator
// make sure we check the account is legit.
if !s.isTrustedIssuer(acc.Issuer) {
return ErrAccountValidation
}
s.mu.Lock()
if s.sys != nil {
s.mu.Unlock()
return ErrAccountExists
}
// This is here in an attempt to quiet the race detector and not have to place
// locks on fast path for inbound messages and checking service imports.
acc.mu.Lock()
if acc.imports.services == nil {
acc.imports.services = make(map[string]*serviceImport)
}
acc.mu.Unlock()
now := time.Now()
s.sys = &internal{
account: acc,
client: &client{srv: s, kind: SYSTEM, opts: internalOpts, msubs: -1, mpay: -1, start: now, last: now},
seq: 1,
sid: 1,
servers: make(map[string]*serverUpdate),
subs: make(map[string]msgHandler),
replies: make(map[string]msgHandler),
sendq: make(chan *pubMsg, internalSendQLen),
statsz: eventsHBInterval,
orphMax: 5 * eventsHBInterval,
chkOrph: 3 * eventsHBInterval,
}
s.sys.client.initClient()
s.sys.client.echo = false
s.sys.wg.Add(1)
s.mu.Unlock()
// Register with the account.
s.sys.client.registerWithAccount(acc)
// Start our internal loop to serialize outbound messages.
// We do our own wg here since we will stop first during shutdown.
go s.internalSendLoop(&s.sys.wg)
// Start up our general subscriptions
s.initEventTracking()
// Track for dead remote servers.
s.wrapChk(s.startRemoteServerSweepTimer)()
// Send out statsz updates periodically.
s.wrapChk(s.startStatszTimer)()
return nil
}
func (s *Server) systemAccount() *Account {
var sacc *Account
s.mu.Lock()
if s.sys != nil {
sacc = s.sys.account
}
s.mu.Unlock()
return sacc
}
// Determine if accounts should track subscriptions for
// efficient propagation.
// Lock should be held on entry.
func (s *Server) shouldTrackSubscriptions() bool {
return (s.opts.Cluster.Port != 0 || s.opts.Gateway.Port != 0)
}
// Invokes registerAccountNoLock under the protection of the server lock.
// That is, server lock is acquired/released in this function.
// See registerAccountNoLock for comment on returned value.
func (s *Server) registerAccount(acc *Account) *Account {
s.mu.Lock()
racc := s.registerAccountNoLock(acc)
s.mu.Unlock()
return racc
}
// Helper to set the sublist based on preferences.
func (s *Server) setAccountSublist(acc *Account) {
if acc != nil && acc.sl == nil {
opts := s.getOpts()
if opts != nil && opts.NoSublistCache {
acc.sl = NewSublistNoCache()
} else {
acc.sl = NewSublistWithCache()
}
}
}
// Registers an account in the server.
// Due to some locking considerations, we may end-up trying
// to register the same account twice. This function will
// then return the already registered account.
// Lock should be held on entry.
func (s *Server) registerAccountNoLock(acc *Account) *Account {
// We are under the server lock. Lookup from map, if present
// return existing account.
if a, _ := s.accounts.Load(acc.Name); a != nil {
s.tmpAccounts.Delete(acc.Name)
return a.(*Account)
}
// Finish account setup and store.
s.setAccountSublist(acc)
if acc.maxnae == 0 {
acc.maxnae = DEFAULT_MAX_ACCOUNT_AE_RESPONSE_MAPS
}
if acc.maxaettl == 0 {
acc.maxaettl = DEFAULT_TTL_AE_RESPONSE_MAP
}
if acc.maxnrm == 0 {
acc.maxnrm = DEFAULT_MAX_ACCOUNT_INTERNAL_RESPONSE_MAPS
}
if acc.clients == nil {
acc.clients = make(map[*client]*client)
}
// If we are capable of routing we will track subscription
// information for efficient interest propagation.
// During config reload, it is possible that account was
// already created (global account), so use locking and
// make sure we create only if needed.
acc.mu.Lock()
// TODO(dlc)- Double check that we need this for GWs.
if acc.rm == nil && s.opts != nil && s.shouldTrackSubscriptions() {
acc.rm = make(map[string]int32)
acc.lqws = make(map[string]int32)
}
acc.srv = s
acc.mu.Unlock()
s.accounts.Store(acc.Name, acc)
s.tmpAccounts.Delete(acc.Name)
s.enableAccountTracking(acc)
return nil
}
// lookupAccount is a function to return the account structure
// associated with an account name.
// Lock MUST NOT be held upon entry.
func (s *Server) lookupAccount(name string) (*Account, error) {
var acc *Account
if v, ok := s.accounts.Load(name); ok {
acc = v.(*Account)
} else if v, ok := s.tmpAccounts.Load(name); ok {
acc = v.(*Account)
}
if acc != nil {
// If we are expired and we have a resolver, then
// return the latest information from the resolver.
if acc.IsExpired() {
s.Debugf("Requested account [%s] has expired", name)
if s.AccountResolver() != nil {
if err := s.updateAccount(acc); err != nil {
// This error could mask expired, so just return expired here.
return nil, ErrAccountExpired
}
} else {
return nil, ErrAccountExpired
}
}
return acc, nil
}
// If we have a resolver see if it can fetch the account.
if s.AccountResolver() == nil {
return nil, ErrMissingAccount
}
return s.fetchAccount(name)
}
// LookupAccount is a public function to return the account structure
// associated with name.
func (s *Server) LookupAccount(name string) (*Account, error) {
return s.lookupAccount(name)
}
// This will fetch new claims and if found update the account with new claims.
// Lock MUST NOT be held upon entry.
func (s *Server) updateAccount(acc *Account) error {
// TODO(dlc) - Make configurable
if time.Since(acc.updated) < time.Second {
s.Debugf("Requested account update for [%s] ignored, too soon", acc.Name)
return ErrAccountResolverUpdateTooSoon
}
claimJWT, err := s.fetchRawAccountClaims(acc.Name)
if err != nil {
return err
}
return s.updateAccountWithClaimJWT(acc, claimJWT)
}
// updateAccountWithClaimJWT will check and apply the claim update.
// Lock MUST NOT be held upon entry.
func (s *Server) updateAccountWithClaimJWT(acc *Account, claimJWT string) error {
if acc == nil {
return ErrMissingAccount
}
acc.updated = time.Now()
if acc.claimJWT != "" && acc.claimJWT == claimJWT {
s.Debugf("Requested account update for [%s], same claims detected", acc.Name)
return ErrAccountResolverSameClaims
}
accClaims, _, err := s.verifyAccountClaims(claimJWT)
if err == nil && accClaims != nil {
acc.claimJWT = claimJWT
s.updateAccountClaims(acc, accClaims)
return nil
}
return err
}
// fetchRawAccountClaims will grab raw account claims iff we have a resolver.
// Lock is NOT held upon entry.
func (s *Server) fetchRawAccountClaims(name string) (string, error) {
accResolver := s.AccountResolver()
if accResolver == nil {
return "", ErrNoAccountResolver
}
// Need to do actual Fetch
start := time.Now()
claimJWT, err := accResolver.Fetch(name)
fetchTime := time.Since(start)
if fetchTime > time.Second {
s.Warnf("Account [%s] fetch took %v", name, fetchTime)
} else {
s.Debugf("Account [%s] fetch took %v", name, fetchTime)
}
if err != nil {
s.Warnf("Account fetch failed: %v", err)
return "", err
}
return claimJWT, nil
}
// fetchAccountClaims will attempt to fetch new claims if a resolver is present.
// Lock is NOT held upon entry.
func (s *Server) fetchAccountClaims(name string) (*jwt.AccountClaims, string, error) {
claimJWT, err := s.fetchRawAccountClaims(name)
if err != nil {
return nil, _EMPTY_, err
}
return s.verifyAccountClaims(claimJWT)
}
// verifyAccountClaims will decode and validate any account claims.
func (s *Server) verifyAccountClaims(claimJWT string) (*jwt.AccountClaims, string, error) {
accClaims, err := jwt.DecodeAccountClaims(claimJWT)
if err != nil {
return nil, _EMPTY_, err
}
vr := jwt.CreateValidationResults()
accClaims.Validate(vr)
if vr.IsBlocking(true) {
return nil, _EMPTY_, ErrAccountValidation
}
return accClaims, claimJWT, nil
}
// This will fetch an account from a resolver if defined.
// Lock is NOT held upon entry.
func (s *Server) fetchAccount(name string) (*Account, error) {
accClaims, claimJWT, err := s.fetchAccountClaims(name)
if accClaims != nil {
acc := s.buildInternalAccount(accClaims)
acc.claimJWT = claimJWT
// Due to possible race, if registerAccount() returns a non
// nil account, it means the same account was already
// registered and we should use this one.
if racc := s.registerAccount(acc); racc != nil {
// Update with the new claims in case they are new.
// Following call will return ErrAccountResolverSameClaims
// if claims are the same.
err = s.updateAccountWithClaimJWT(racc, claimJWT)
if err != nil && err != ErrAccountResolverSameClaims {
return nil, err
}
return racc, nil
}
return acc, nil
}
return nil, err
}
// Start up the server, this will block.
// Start via a Go routine if needed.
func (s *Server) Start() {
s.Noticef("Starting nats-server version %s", VERSION)
s.Debugf("Go build version %s", s.info.GoVersion)
gc := gitCommit
if gc == "" {
gc = "not set"
}
s.Noticef("Git commit [%s]", gc)
// Check for insecure configurations.op
s.checkAuthforWarnings()
// Avoid RACE between Start() and Shutdown()
s.mu.Lock()
s.running = true
s.mu.Unlock()
s.grMu.Lock()
s.grRunning = true
s.grMu.Unlock()
// Snapshot server options.
opts := s.getOpts()
hasOperators := len(opts.TrustedOperators) > 0
if hasOperators {
s.Noticef("Trusted Operators")
}
for _, opc := range opts.TrustedOperators {
s.Noticef(" System : %q", opc.Audience)
s.Noticef(" Operator: %q", opc.Name)
s.Noticef(" Issued : %v", time.Unix(opc.IssuedAt, 0))
s.Noticef(" Expires : %v", time.Unix(opc.Expires, 0))
}
if hasOperators && opts.SystemAccount == _EMPTY_ {
s.Warnf("Trusted Operators should utilize a System Account")
}
// If we have a memory resolver, check the accounts here for validation exceptions.
// This allows them to be logged right away vs when they are accessed via a client.
if hasOperators && len(opts.resolverPreloads) > 0 {
s.checkResolvePreloads()
}
// Log the pid to a file
if opts.PidFile != _EMPTY_ {
if err := s.logPid(); err != nil {
PrintAndDie(fmt.Sprintf("Could not write pidfile: %v\n", err))
}
}
// Start monitoring if needed
if err := s.StartMonitoring(); err != nil {
s.Fatalf("Can't start monitoring: %v", err)
return
}
// Setup system account which will start eventing stack.
if sa := opts.SystemAccount; sa != _EMPTY_ {
if err := s.SetSystemAccount(sa); err != nil {
s.Fatalf("Can't set system account: %v", err)
return
}
}
// Start expiration of mapped GW replies, regardless if
// this server is configured with gateway or not.
s.startGWReplyMapExpiration()
// Start up gateway if needed. Do this before starting the routes, because
// we want to resolve the gateway host:port so that this information can
// be sent to other routes.
if opts.Gateway.Port != 0 {
s.startGateways()
}
// Start up listen if we want to accept leaf node connections.
if opts.LeafNode.Port != 0 {
// Spin up the accept loop if needed
ch := make(chan struct{})
go s.leafNodeAcceptLoop(ch)
// This ensure that we have resolved or assigned the advertise
// address for the leafnode listener. We need that in StartRouting().
<-ch
}
// Solicit remote servers for leaf node connections.
if len(opts.LeafNode.Remotes) > 0 {
s.solicitLeafNodeRemotes(opts.LeafNode.Remotes)
}
// The Routing routine needs to wait for the client listen
// port to be opened and potential ephemeral port selected.
clientListenReady := make(chan struct{})
// Start up routing as well if needed.
if opts.Cluster.Port != 0 {
s.startGoRoutine(func() {
s.StartRouting(clientListenReady)
})
}
// Pprof http endpoint for the profiler.
if opts.ProfPort != 0 {
s.StartProfiler()
}
if opts.PortsFileDir != _EMPTY_ {
s.logPorts()
}
// Wait for clients.
s.AcceptLoop(clientListenReady)
}
// Shutdown will shutdown the server instance by kicking out the AcceptLoop
// and closing all associated clients.
func (s *Server) Shutdown() {
// Shutdown the eventing system as needed.
// This is done first to send out any messages for
// account status. We will also clean up any
// eventing items associated with accounts.
s.shutdownEventing()
s.mu.Lock()
// Prevent issues with multiple calls.
if s.shutdown {
s.mu.Unlock()
return
}
s.Noticef("Initiating Shutdown...")
opts := s.getOpts()
s.shutdown = true
s.running = false
s.grMu.Lock()
s.grRunning = false
s.grMu.Unlock()
conns := make(map[uint64]*client)
// Copy off the clients
for i, c := range s.clients {
conns[i] = c
}
// Copy off the connections that are not yet registered
// in s.routes, but for which the readLoop has started
s.grMu.Lock()
for i, c := range s.grTmpClients {
conns[i] = c
}
s.grMu.Unlock()
// Copy off the routes
for i, r := range s.routes {
conns[i] = r
}
// Copy off the gateways
s.getAllGatewayConnections(conns)
// Copy off the leaf nodes
for i, c := range s.leafs {
conns[i] = c
}
// Number of done channel responses we expect.
doneExpected := 0
// Kick client AcceptLoop()
if s.listener != nil {
doneExpected++
s.listener.Close()
s.listener = nil
}
// Kick leafnodes AcceptLoop()
if s.leafNodeListener != nil {
doneExpected++
s.leafNodeListener.Close()
s.leafNodeListener = nil
}
// Kick route AcceptLoop()
if s.routeListener != nil {
doneExpected++
s.routeListener.Close()
s.routeListener = nil
}
// Kick Gateway AcceptLoop()
if s.gatewayListener != nil {
doneExpected++
s.gatewayListener.Close()
s.gatewayListener = nil
}
// Kick HTTP monitoring if its running
if s.http != nil {
doneExpected++
s.http.Close()
s.http = nil
}
// Kick Profiling if its running
if s.profiler != nil {
doneExpected++
s.profiler.Close()
}
s.mu.Unlock()
// Release go routines that wait on that channel
close(s.quitCh)
// Close client and route connections
for _, c := range conns {
c.setNoReconnect()
c.closeConnection(ServerShutdown)
}
// Block until the accept loops exit
for doneExpected > 0 {
<-s.done
doneExpected--
}
// Wait for go routines to be done.
s.grWG.Wait()
if opts.PortsFileDir != _EMPTY_ {
s.deletePortsFile(opts.PortsFileDir)
}
s.Noticef("Server Exiting..")
// Close logger if applicable. It allows tests on Windows
// to be able to do proper cleanup (delete log file).
s.logging.RLock()
log := s.logging.logger
s.logging.RUnlock()
if log != nil {
if l, ok := log.(*logger.Logger); ok {
l.Close()
}
}
// Notify that the shutdown is complete
close(s.shutdownComplete)
}
// WaitForShutdown will block until the server has been fully shutdown.
func (s *Server) WaitForShutdown() {
<-s.shutdownComplete
}
// AcceptLoop is exported for easier testing.
func (s *Server) AcceptLoop(clr chan struct{}) {
// If we were to exit before the listener is setup properly,
// make sure we close the channel.
defer func() {
if clr != nil {
close(clr)
}
}()
// Snapshot server options.
opts := s.getOpts()
hp := net.JoinHostPort(opts.Host, strconv.Itoa(opts.Port))
l, e := net.Listen("tcp", hp)
if e != nil {
s.Fatalf("Error listening on port: %s, %q", hp, e)
return
}
s.Noticef("Listening for client connections on %s",
net.JoinHostPort(opts.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
// Alert of TLS enabled.
if opts.TLSConfig != nil {
s.Noticef("TLS required for client connections")
}
s.Noticef("Server id is %s", s.info.ID)
s.Noticef("Server is ready")
// Setup state that can enable shutdown
s.mu.Lock()
s.listener = l
// If server was started with RANDOM_PORT (-1), opts.Port would be equal
// to 0 at the beginning this function. So we need to get the actual port
if opts.Port == 0 {
// Write resolved port back to options.
opts.Port = l.Addr().(*net.TCPAddr).Port
}
// Now that port has been set (if it was set to RANDOM), set the
// server's info Host/Port with either values from Options or
// ClientAdvertise. Also generate the JSON byte array.
if err := s.setInfoHostPortAndGenerateJSON(); err != nil {
s.Fatalf("Error setting server INFO with ClientAdvertise value of %s, err=%v", s.opts.ClientAdvertise, err)
s.mu.Unlock()
return
}
// Keep track of client connect URLs. We may need them later.
s.clientConnectURLs = s.getClientConnectURLs()
s.mu.Unlock()
// Let the caller know that we are ready
close(clr)
clr = nil
tmpDelay := ACCEPT_MIN_SLEEP
for s.isRunning() {
conn, err := l.Accept()
if err != nil {
if s.isLameDuckMode() {
// Signal that we are not accepting new clients
s.ldmCh <- true
// Now wait for the Shutdown...
<-s.quitCh
return
}
tmpDelay = s.acceptError("Client", err, tmpDelay)
continue
}
tmpDelay = ACCEPT_MIN_SLEEP
s.startGoRoutine(func() {
s.createClient(conn)
s.grWG.Done()
})
}
s.done <- true
}
// This function sets the server's info Host/Port based on server Options.
// Note that this function may be called during config reload, this is why
// Host/Port may be reset to original Options if the ClientAdvertise option
// is not set (since it may have previously been).
// The function then generates the server infoJSON.
func (s *Server) setInfoHostPortAndGenerateJSON() error {
// When this function is called, opts.Port is set to the actual listen
// port (if option was originally set to RANDOM), even during a config
// reload. So use of s.opts.Port is safe.
if s.opts.ClientAdvertise != "" {
h, p, err := parseHostPort(s.opts.ClientAdvertise, s.opts.Port)
if err != nil {
return err
}
s.info.Host = h
s.info.Port = p
} else {
s.info.Host = s.opts.Host
s.info.Port = s.opts.Port
}
return nil
}
// StartProfiler is called to enable dynamic profiling.
func (s *Server) StartProfiler() {
// Snapshot server options.
opts := s.getOpts()
port := opts.ProfPort
// Check for Random Port
if port == -1 {
port = 0
}
hp := net.JoinHostPort(opts.Host, strconv.Itoa(port))
l, err := net.Listen("tcp", hp)
s.Noticef("profiling port: %d", l.Addr().(*net.TCPAddr).Port)
if err != nil {
s.Fatalf("error starting profiler: %s", err)
}
srv := &http.Server{
Addr: hp,
Handler: http.DefaultServeMux,
MaxHeaderBytes: 1 << 20,
}
s.mu.Lock()
s.profiler = l
s.profilingServer = srv
s.mu.Unlock()
// Enable blocking profile
runtime.SetBlockProfileRate(1)
go func() {
// if this errors out, it's probably because the server is being shutdown
err := srv.Serve(l)
if err != nil {
s.mu.Lock()
shutdown := s.shutdown
s.mu.Unlock()
if !shutdown {
s.Fatalf("error starting profiler: %s", err)
}
}
srv.Close()
s.done <- true
}()
}
// StartHTTPMonitoring will enable the HTTP monitoring port.
// DEPRECATED: Should use StartMonitoring.
func (s *Server) StartHTTPMonitoring() {
s.startMonitoring(false)
}
// StartHTTPSMonitoring will enable the HTTPS monitoring port.
// DEPRECATED: Should use StartMonitoring.
func (s *Server) StartHTTPSMonitoring() {
s.startMonitoring(true)
}
// StartMonitoring starts the HTTP or HTTPs server if needed.
func (s *Server) StartMonitoring() error {
// Snapshot server options.
opts := s.getOpts()
// Specifying both HTTP and HTTPS ports is a misconfiguration
if opts.HTTPPort != 0 && opts.HTTPSPort != 0 {
return fmt.Errorf("can't specify both HTTP (%v) and HTTPs (%v) ports", opts.HTTPPort, opts.HTTPSPort)
}
var err error
if opts.HTTPPort != 0 {
err = s.startMonitoring(false)
} else if opts.HTTPSPort != 0 {
if opts.TLSConfig == nil {
return fmt.Errorf("TLS cert and key required for HTTPS")
}
err = s.startMonitoring(true)
}
return err
}
// HTTP endpoints
const (
RootPath = "/"
VarzPath = "/varz"
ConnzPath = "/connz"
RoutezPath = "/routez"
GatewayzPath = "/gatewayz"
LeafzPath = "/leafz"
SubszPath = "/subsz"
StackszPath = "/stacksz"
)
// Start the monitoring server
func (s *Server) startMonitoring(secure bool) error {
// Snapshot server options.
opts := s.getOpts()
// Used to track HTTP requests
s.httpReqStats = map[string]uint64{
RootPath: 0,
VarzPath: 0,
ConnzPath: 0,
RoutezPath: 0,
GatewayzPath: 0,
SubszPath: 0,
}
var (
hp string
err error
httpListener net.Listener
port int
)
monitorProtocol := "http"
if secure {
monitorProtocol += "s"
port = opts.HTTPSPort
if port == -1 {
port = 0
}
hp = net.JoinHostPort(opts.HTTPHost, strconv.Itoa(port))
config := opts.TLSConfig.Clone()
config.ClientAuth = tls.NoClientCert
httpListener, err = tls.Listen("tcp", hp, config)
} else {
port = opts.HTTPPort
if port == -1 {
port = 0
}
hp = net.JoinHostPort(opts.HTTPHost, strconv.Itoa(port))
httpListener, err = net.Listen("tcp", hp)
}
if err != nil {
return fmt.Errorf("can't listen to the monitor port: %v", err)
}
s.Noticef("Starting %s monitor on %s", monitorProtocol,
net.JoinHostPort(opts.HTTPHost, strconv.Itoa(httpListener.Addr().(*net.TCPAddr).Port)))
mux := http.NewServeMux()
// Root
mux.HandleFunc(RootPath, s.HandleRoot)
// Varz
mux.HandleFunc(VarzPath, s.HandleVarz)
// Connz
mux.HandleFunc(ConnzPath, s.HandleConnz)
// Routez
mux.HandleFunc(RoutezPath, s.HandleRoutez)
// Gatewayz
mux.HandleFunc(GatewayzPath, s.HandleGatewayz)
// Leafz
mux.HandleFunc(LeafzPath, s.HandleLeafz)
// Subz
mux.HandleFunc(SubszPath, s.HandleSubsz)
// Subz alias for backwards compatibility
mux.HandleFunc("/subscriptionsz", s.HandleSubsz)
// Stacksz
mux.HandleFunc(StackszPath, s.HandleStacksz)
// Do not set a WriteTimeout because it could cause cURL/browser
// to return empty response or unable to display page if the
// server needs more time to build the response.
srv := &http.Server{
Addr: hp,
Handler: mux,
MaxHeaderBytes: 1 << 20,
}
s.mu.Lock()
s.http = httpListener
s.httpHandler = mux
s.monitoringServer = srv
s.mu.Unlock()
go func() {
if err := srv.Serve(httpListener); err != nil {
s.mu.Lock()
shutdown := s.shutdown
s.mu.Unlock()
if !shutdown {
s.Fatalf("Error starting monitor on %q: %v", hp, err)
}
}
srv.Close()
srv.Handler = nil
s.mu.Lock()
s.httpHandler = nil
s.mu.Unlock()
s.done <- true
}()
return nil
}
// HTTPHandler returns the http.Handler object used to handle monitoring
// endpoints. It will return nil if the server is not configured for
// monitoring, or if the server has not been started yet (Server.Start()).
func (s *Server) HTTPHandler() http.Handler {
s.mu.Lock()
defer s.mu.Unlock()
return s.httpHandler
}
// Perform a conditional deep copy due to reference nature of ClientConnectURLs.
// If updates are made to Info, this function should be consulted and updated.
// Assume lock is held.
func (s *Server) copyInfo() Info {
info := s.info
if info.ClientConnectURLs != nil {
info.ClientConnectURLs = make([]string, len(s.info.ClientConnectURLs))
copy(info.ClientConnectURLs, s.info.ClientConnectURLs)
}
if s.nonceRequired() {
// Nonce handling
var raw [nonceLen]byte
nonce := raw[:]
s.generateNonce(nonce)
info.Nonce = string(nonce)
}
return info
}
func (s *Server) createClient(conn net.Conn) *client {
// Snapshot server options.
opts := s.getOpts()
maxPay := int32(opts.MaxPayload)
maxSubs := int32(opts.MaxSubs)
// For system, maxSubs of 0 means unlimited, so re-adjust here.
if maxSubs == 0 {
maxSubs = -1
}
now := time.Now()
c := &client{srv: s, nc: conn, opts: defaultOpts, mpay: maxPay, msubs: maxSubs, start: now, last: now}
c.registerWithAccount(s.globalAccount())
// Grab JSON info string
s.mu.Lock()
info := s.copyInfo()
c.nonce = []byte(info.Nonce)
s.totalClients++
s.mu.Unlock()
// Grab lock
c.mu.Lock()
if info.AuthRequired {
c.flags.set(expectConnect)
}
// Initialize
c.initClient()
c.Debugf("Client connection created")
// Send our information.
// Need to be sent in place since writeLoop cannot be started until
// TLS handshake is done (if applicable).
c.sendProtoNow(c.generateClientInfoJSON(info))
// Unlock to register
c.mu.Unlock()
// Register with the server.
s.mu.Lock()
// If server is not running, Shutdown() may have already gathered the
// list of connections to close. It won't contain this one, so we need
// to bail out now otherwise the readLoop started down there would not
// be interrupted. Skip also if in lame duck mode.
if !s.running || s.ldm {
s.mu.Unlock()
return c
}
// If there is a max connections specified, check that adding
// this new client would not push us over the max
if opts.MaxConn > 0 && len(s.clients) >= opts.MaxConn {
s.mu.Unlock()
c.maxConnExceeded()
return nil
}
s.clients[c.cid] = c
s.mu.Unlock()
// Re-Grab lock
c.mu.Lock()
// Check for TLS
if info.TLSRequired {
c.Debugf("Starting TLS client connection handshake")
c.nc = tls.Server(c.nc, opts.TLSConfig)
conn := c.nc.(*tls.Conn)
// Setup the timeout
ttl := secondsToDuration(opts.TLSTimeout)
time.AfterFunc(ttl, func() { tlsTimeout(c, conn) })
conn.SetReadDeadline(time.Now().Add(ttl))
// Force handshake
c.mu.Unlock()
if err := conn.Handshake(); err != nil {
c.Errorf("TLS handshake error: %v", err)
c.closeConnection(TLSHandshakeError)
return nil
}
// Reset the read deadline
conn.SetReadDeadline(time.Time{})
// Re-Grab lock
c.mu.Lock()
// Indicate that handshake is complete (used in monitoring)
c.flags.set(handshakeComplete)
}
// The connection may have been closed
if c.isClosed() {
c.mu.Unlock()
return c
}
// Check for Auth. We schedule this timer after the TLS handshake to avoid
// the race where the timer fires during the handshake and causes the
// server to write bad data to the socket. See issue #432.
if info.AuthRequired {
c.setAuthTimer(secondsToDuration(opts.AuthTimeout))
}
// Do final client initialization
// Set the First Ping timer.
s.setFirstPingTimer(c)
// Spin up the read loop.
s.startGoRoutine(func() { c.readLoop() })
// Spin up the write loop.
s.startGoRoutine(func() { c.writeLoop() })
if info.TLSRequired {
c.Debugf("TLS handshake complete")
cs := c.nc.(*tls.Conn).ConnectionState()
c.Debugf("TLS version %s, cipher suite %s", tlsVersion(cs.Version), tlsCipher(cs.CipherSuite))
}
c.mu.Unlock()
return c
}
// This will save off a closed client in a ring buffer such that
// /connz can inspect. Useful for debugging, etc.
func (s *Server) saveClosedClient(c *client, nc net.Conn, reason ClosedState) {
now := time.Now()
s.accountDisconnectEvent(c, now, reason.String())
c.mu.Lock()
cc := &closedClient{}
cc.fill(c, nc, now)
cc.Stop = &now
cc.Reason = reason.String()
// Do subs, do not place by default in main ConnInfo
if len(c.subs) > 0 {
cc.subs = make([]string, 0, len(c.subs))
for _, sub := range c.subs {
cc.subs = append(cc.subs, string(sub.subject))
}
}
// Hold user as well.
cc.user = c.opts.Username
// Hold account name if not the global account.
if c.acc != nil && c.acc.Name != globalAccountName {
cc.acc = c.acc.Name
}
c.mu.Unlock()
// Place in the ring buffer
s.mu.Lock()
if s.closed != nil {
s.closed.append(cc)
}
s.mu.Unlock()
}
// Adds the given array of urls to the server's INFO.ClientConnectURLs
// array. The server INFO JSON is regenerated.
// Note that a check is made to ensure that given URLs are not
// already present. So the INFO JSON is regenerated only if new ULRs
// were added.
// If there was a change, an INFO protocol is sent to registered clients
// that support async INFO protocols.
func (s *Server) addClientConnectURLsAndSendINFOToClients(urls []string) {
s.updateServerINFOAndSendINFOToClients(urls, true)
}
// Removes the given array of urls from the server's INFO.ClientConnectURLs
// array. The server INFO JSON is regenerated if needed.
// If there was a change, an INFO protocol is sent to registered clients
// that support async INFO protocols.
func (s *Server) removeClientConnectURLsAndSendINFOToClients(urls []string) {
s.updateServerINFOAndSendINFOToClients(urls, false)
}
// Updates the server's Info object with the given array of URLs and re-generate
// the infoJSON byte array, then send an (async) INFO protocol to clients that
// support it.
func (s *Server) updateServerINFOAndSendINFOToClients(urls []string, add bool) {
s.mu.Lock()
defer s.mu.Unlock()
// Will be set to true if we alter the server's Info object.
wasUpdated := false
remove := !add
for _, url := range urls {
_, present := s.clientConnectURLsMap[url]
if add && !present {
s.clientConnectURLsMap[url] = struct{}{}
wasUpdated = true
} else if remove && present {
delete(s.clientConnectURLsMap, url)
wasUpdated = true
}
}
if wasUpdated {
// Recreate the info.ClientConnectURL array from the map
s.info.ClientConnectURLs = s.info.ClientConnectURLs[:0]
// Add this server client connect ULRs first...
s.info.ClientConnectURLs = append(s.info.ClientConnectURLs, s.clientConnectURLs...)
for url := range s.clientConnectURLsMap {
s.info.ClientConnectURLs = append(s.info.ClientConnectURLs, url)
}
// Update the time of this update
s.lastCURLsUpdate = time.Now().UnixNano()
// Send to all registered clients that support async INFO protocols.
s.sendAsyncInfoToClients()
}
}
// Handle closing down a connection when the handshake has timedout.
func tlsTimeout(c *client, conn *tls.Conn) {
c.mu.Lock()
closed := c.isClosed()
c.mu.Unlock()
// Check if already closed
if closed {
return
}
cs := conn.ConnectionState()
if !cs.HandshakeComplete {
c.Errorf("TLS handshake timeout")
c.sendErr("Secure Connection - TLS Required")
c.closeConnection(TLSHandshakeError)
}
}
// Seems silly we have to write these
func tlsVersion(ver uint16) string {
switch ver {
case tls.VersionTLS10:
return "1.0"
case tls.VersionTLS11:
return "1.1"
case tls.VersionTLS12:
return "1.2"
}
return fmt.Sprintf("Unknown [%x]", ver)
}
// We use hex here so we don't need multiple versions
func tlsCipher(cs uint16) string {
name, present := cipherMapByID[cs]
if present {
return name
}
return fmt.Sprintf("Unknown [%x]", cs)
}
// Remove a client or route from our internal accounting.
func (s *Server) removeClient(c *client) {
// kind is immutable, so can check without lock
switch c.kind {
case CLIENT:
c.mu.Lock()
cid := c.cid
updateProtoInfoCount := false
if c.kind == CLIENT && c.opts.Protocol >= ClientProtoInfo {
updateProtoInfoCount = true
}
c.mu.Unlock()
s.mu.Lock()
delete(s.clients, cid)
if updateProtoInfoCount {
s.cproto--
}
s.mu.Unlock()
case ROUTER:
s.removeRoute(c)
case GATEWAY:
s.removeRemoteGatewayConnection(c)
case LEAF:
s.removeLeafNodeConnection(c)
}
}
func (s *Server) removeFromTempClients(cid uint64) {
s.grMu.Lock()
delete(s.grTmpClients, cid)
s.grMu.Unlock()
}
func (s *Server) addToTempClients(cid uint64, c *client) bool {
added := false
s.grMu.Lock()
if s.grRunning {
s.grTmpClients[cid] = c
added = true
}
s.grMu.Unlock()
return added
}
/////////////////////////////////////////////////////////////////
// These are some helpers for accounting in functional tests.
/////////////////////////////////////////////////////////////////
// NumRoutes will report the number of registered routes.
func (s *Server) NumRoutes() int {
s.mu.Lock()
nr := len(s.routes)
s.mu.Unlock()
return nr
}
// NumRemotes will report number of registered remotes.
func (s *Server) NumRemotes() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.remotes)
}
// NumLeafNodes will report number of leaf node connections.
func (s *Server) NumLeafNodes() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.leafs)
}
// NumClients will report the number of registered clients.
func (s *Server) NumClients() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.clients)
}
// GetClient will return the client associated with cid.
func (s *Server) GetClient(cid uint64) *client {
return s.getClient(cid)
}
// getClient will return the client associated with cid.
func (s *Server) getClient(cid uint64) *client {
s.mu.Lock()
defer s.mu.Unlock()
return s.clients[cid]
}
// GetLeafNode returns the leafnode associated with the cid.
func (s *Server) GetLeafNode(cid uint64) *client {
s.mu.Lock()
defer s.mu.Unlock()
return s.leafs[cid]
}
// NumSubscriptions will report how many subscriptions are active.
func (s *Server) NumSubscriptions() uint32 {
s.mu.Lock()
defer s.mu.Unlock()
return s.numSubscriptions()
}
// numSubscriptions will report how many subscriptions are active.
// Lock should be held.
func (s *Server) numSubscriptions() uint32 {
var subs int
s.accounts.Range(func(k, v interface{}) bool {
acc := v.(*Account)
if acc.sl != nil {
subs += acc.TotalSubs()
}
return true
})
return uint32(subs)
}
// NumSlowConsumers will report the number of slow consumers.
func (s *Server) NumSlowConsumers() int64 {
return atomic.LoadInt64(&s.slowConsumers)
}
// ConfigTime will report the last time the server configuration was loaded.
func (s *Server) ConfigTime() time.Time {
s.mu.Lock()
defer s.mu.Unlock()
return s.configTime
}
// Addr will return the net.Addr object for the current listener.
func (s *Server) Addr() net.Addr {
s.mu.Lock()
defer s.mu.Unlock()
if s.listener == nil {
return nil
}
return s.listener.Addr()
}
// MonitorAddr will return the net.Addr object for the monitoring listener.
func (s *Server) MonitorAddr() *net.TCPAddr {
s.mu.Lock()
defer s.mu.Unlock()
if s.http == nil {
return nil
}
return s.http.Addr().(*net.TCPAddr)
}
// ClusterAddr returns the net.Addr object for the route listener.
func (s *Server) ClusterAddr() *net.TCPAddr {
s.mu.Lock()
defer s.mu.Unlock()
if s.routeListener == nil {
return nil
}
return s.routeListener.Addr().(*net.TCPAddr)
}
// ProfilerAddr returns the net.Addr object for the profiler listener.
func (s *Server) ProfilerAddr() *net.TCPAddr {
s.mu.Lock()
defer s.mu.Unlock()
if s.profiler == nil {
return nil
}
return s.profiler.Addr().(*net.TCPAddr)
}
// ReadyForConnections returns `true` if the server is ready to accept clients
// and, if routing is enabled, route connections. If after the duration
// `dur` the server is still not ready, returns `false`.
func (s *Server) ReadyForConnections(dur time.Duration) bool {
// Snapshot server options.
opts := s.getOpts()
end := time.Now().Add(dur)
for time.Now().Before(end) {
s.mu.Lock()
ok := s.listener != nil && (opts.Cluster.Port == 0 || s.routeListener != nil) && (opts.Gateway.Name == "" || s.gatewayListener != nil)
s.mu.Unlock()
if ok {
return true
}
time.Sleep(25 * time.Millisecond)
}
return false
}
// ID returns the server's ID
func (s *Server) ID() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.info.ID
}
func (s *Server) startGoRoutine(f func()) {
s.grMu.Lock()
if s.grRunning {
s.grWG.Add(1)
go f()
}
s.grMu.Unlock()
}
func (s *Server) numClosedConns() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.closed.len()
}
func (s *Server) totalClosedConns() uint64 {
s.mu.Lock()
defer s.mu.Unlock()
return s.closed.totalConns()
}
func (s *Server) closedClients() []*closedClient {
s.mu.Lock()
defer s.mu.Unlock()
return s.closed.closedClients()
}
// getClientConnectURLs returns suitable URLs for clients to connect to the listen
// port based on the server options' Host and Port. If the Host corresponds to
// "any" interfaces, this call returns the list of resolved IP addresses.
// If ClientAdvertise is set, returns the client advertise host and port.
// The server lock is assumed held on entry.
func (s *Server) getClientConnectURLs() []string {
// Snapshot server options.
opts := s.getOpts()
urls := make([]string, 0, 1)
// short circuit if client advertise is set
if opts.ClientAdvertise != "" {
// just use the info host/port. This is updated in s.New()
urls = append(urls, net.JoinHostPort(s.info.Host, strconv.Itoa(s.info.Port)))
} else {
sPort := strconv.Itoa(opts.Port)
_, ips, err := s.getNonLocalIPsIfHostIsIPAny(opts.Host, true)
for _, ip := range ips {
urls = append(urls, net.JoinHostPort(ip, sPort))
}
if err != nil || len(urls) == 0 {
// We are here if s.opts.Host is not "0.0.0.0" nor "::", or if for some
// reason we could not add any URL in the loop above.
// We had a case where a Windows VM was hosed and would have err == nil
// and not add any address in the array in the loop above, and we
// ended-up returning 0.0.0.0, which is problematic for Windows clients.
// Check for 0.0.0.0 or :: specifically, and ignore if that's the case.
if opts.Host == "0.0.0.0" || opts.Host == "::" {
s.Errorf("Address %q can not be resolved properly", opts.Host)
} else {
urls = append(urls, net.JoinHostPort(opts.Host, sPort))
}
}
}
return urls
}
// Returns an array of non local IPs if the provided host is
// 0.0.0.0 or ::. It returns the first resolved if `all` is
// false.
// The boolean indicate if the provided host was 0.0.0.0 (or ::)
// so that if the returned array is empty caller can decide
// what to do next.
func (s *Server) getNonLocalIPsIfHostIsIPAny(host string, all bool) (bool, []string, error) {
ip := net.ParseIP(host)
// If this is not an IP, we are done
if ip == nil {
return false, nil, nil
}
// If this is not 0.0.0.0 or :: we have nothing to do.
if !ip.IsUnspecified() {
return false, nil, nil
}
s.Debugf("Get non local IPs for %q", host)
var ips []string
ifaces, _ := net.Interfaces()
for _, i := range ifaces {
addrs, _ := i.Addrs()
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
ipStr := ip.String()
// Skip non global unicast addresses
if !ip.IsGlobalUnicast() || ip.IsUnspecified() {
ip = nil
continue
}
s.Debugf(" ip=%s", ipStr)
ips = append(ips, ipStr)
if !all {
break
}
}
}
return true, ips, nil
}
// if the ip is not specified, attempt to resolve it
func resolveHostPorts(addr net.Listener) []string {
hostPorts := make([]string, 0)
hp := addr.Addr().(*net.TCPAddr)
port := strconv.Itoa(hp.Port)
if hp.IP.IsUnspecified() {
var ip net.IP
ifaces, _ := net.Interfaces()
for _, i := range ifaces {
addrs, _ := i.Addrs()
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
hostPorts = append(hostPorts, net.JoinHostPort(ip.String(), port))
case *net.IPAddr:
ip = v.IP
hostPorts = append(hostPorts, net.JoinHostPort(ip.String(), port))
default:
continue
}
}
}
} else {
hostPorts = append(hostPorts, net.JoinHostPort(hp.IP.String(), port))
}
return hostPorts
}
// format the address of a net.Listener with a protocol
func formatURL(protocol string, addr net.Listener) []string {
hostports := resolveHostPorts(addr)
for i, hp := range hostports {
hostports[i] = fmt.Sprintf("%s://%s", protocol, hp)
}
return hostports
}
// Ports describes URLs that the server can be contacted in
type Ports struct {
Nats []string `json:"nats,omitempty"`
Monitoring []string `json:"monitoring,omitempty"`
Cluster []string `json:"cluster,omitempty"`
Profile []string `json:"profile,omitempty"`
}
// PortsInfo attempts to resolve all the ports. If after maxWait the ports are not
// resolved, it returns nil. Otherwise it returns a Ports struct
// describing ports where the server can be contacted
func (s *Server) PortsInfo(maxWait time.Duration) *Ports {
if s.readyForListeners(maxWait) {
opts := s.getOpts()
s.mu.Lock()
info := s.copyInfo()
listener := s.listener
httpListener := s.http
clusterListener := s.routeListener
profileListener := s.profiler
s.mu.Unlock()
ports := Ports{}
if listener != nil {
natsProto := "nats"
if info.TLSRequired {
natsProto = "tls"
}
ports.Nats = formatURL(natsProto, listener)
}
if httpListener != nil {
monProto := "http"
if opts.HTTPSPort != 0 {
monProto = "https"
}
ports.Monitoring = formatURL(monProto, httpListener)
}
if clusterListener != nil {
clusterProto := "nats"
if opts.Cluster.TLSConfig != nil {
clusterProto = "tls"
}
ports.Cluster = formatURL(clusterProto, clusterListener)
}
if profileListener != nil {
ports.Profile = formatURL("http", profileListener)
}
return &ports
}
return nil
}
// Returns the portsFile. If a non-empty dirHint is provided, the dirHint
// path is used instead of the server option value
func (s *Server) portFile(dirHint string) string {
dirname := s.getOpts().PortsFileDir
if dirHint != "" {
dirname = dirHint
}
if dirname == _EMPTY_ {
return _EMPTY_
}
return filepath.Join(dirname, fmt.Sprintf("%s_%d.ports", filepath.Base(os.Args[0]), os.Getpid()))
}
// Delete the ports file. If a non-empty dirHint is provided, the dirHint
// path is used instead of the server option value
func (s *Server) deletePortsFile(hintDir string) {
portsFile := s.portFile(hintDir)
if portsFile != "" {
if err := os.Remove(portsFile); err != nil {
s.Errorf("Error cleaning up ports file %s: %v", portsFile, err)
}
}
}
// Writes a file with a serialized Ports to the specified ports_file_dir.
// The name of the file is `exename_pid.ports`, typically nats-server_pid.ports.
// if ports file is not set, this function has no effect
func (s *Server) logPorts() {
opts := s.getOpts()
portsFile := s.portFile(opts.PortsFileDir)
if portsFile != _EMPTY_ {
go func() {
info := s.PortsInfo(5 * time.Second)
if info == nil {
s.Errorf("Unable to resolve the ports in the specified time")
return
}
data, err := json.Marshal(info)
if err != nil {
s.Errorf("Error marshaling ports file: %v", err)
return
}
if err := ioutil.WriteFile(portsFile, data, 0666); err != nil {
s.Errorf("Error writing ports file (%s): %v", portsFile, err)
return
}
}()
}
}
// waits until a calculated list of listeners is resolved or a timeout
func (s *Server) readyForListeners(dur time.Duration) bool {
end := time.Now().Add(dur)
for time.Now().Before(end) {
s.mu.Lock()
listeners := s.serviceListeners()
s.mu.Unlock()
if len(listeners) == 0 {
return false
}
ok := true
for _, l := range listeners {
if l == nil {
ok = false
break
}
}
if ok {
return true
}
select {
case <-s.quitCh:
return false
case <-time.After(25 * time.Millisecond):
// continue - unable to select from quit - we are still running
}
}
return false
}
// returns a list of listeners that are intended for the process
// if the entry is nil, the interface is yet to be resolved
func (s *Server) serviceListeners() []net.Listener {
listeners := make([]net.Listener, 0)
opts := s.getOpts()
listeners = append(listeners, s.listener)
if opts.Cluster.Port != 0 {
listeners = append(listeners, s.routeListener)
}
if opts.HTTPPort != 0 || opts.HTTPSPort != 0 {
listeners = append(listeners, s.http)
}
if opts.ProfPort != 0 {
listeners = append(listeners, s.profiler)
}
return listeners
}
// Returns true if in lame duck mode.
func (s *Server) isLameDuckMode() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.ldm
}
// This function will close the client listener then close the clients
// at some interval to avoid a reconnecting storm.
func (s *Server) lameDuckMode() {
s.mu.Lock()
// Check if there is actually anything to do
if s.shutdown || s.ldm || s.listener == nil {
s.mu.Unlock()
return
}
s.Noticef("Entering lame duck mode, stop accepting new clients")
s.ldm = true
s.ldmCh = make(chan bool, 1)
s.listener.Close()
s.listener = nil
s.mu.Unlock()
// Wait for accept loop to be done to make sure that no new
// client can connect
<-s.ldmCh
s.mu.Lock()
// Need to recheck few things
if s.shutdown || len(s.clients) == 0 {
s.mu.Unlock()
// If there is no client, we need to call Shutdown() to complete
// the LDMode. If server has been shutdown while lock was released,
// calling Shutdown() should be no-op.
s.Shutdown()
return
}
dur := int64(s.getOpts().LameDuckDuration)
dur -= atomic.LoadInt64(&lameDuckModeInitialDelay)
if dur <= 0 {
dur = int64(time.Second)
}
numClients := int64(len(s.clients))
batch := 1
// Sleep interval between each client connection close.
si := dur / numClients
if si < 1 {
// Should not happen (except in test with very small LD duration), but
// if there are too many clients, batch the number of close and
// use a tiny sleep interval that will result in yield likely.
si = 1
batch = int(numClients / dur)
} else if si > int64(time.Second) {
// Conversely, there is no need to sleep too long between clients
// and spread say 10 clients for the 2min duration. Sleeping no
// more than 1sec.
si = int64(time.Second)
}
// Now capture all clients
clients := make([]*client, 0, len(s.clients))
for _, client := range s.clients {
clients = append(clients, client)
}
s.mu.Unlock()
t := time.NewTimer(time.Duration(atomic.LoadInt64(&lameDuckModeInitialDelay)))
// Delay start of closing of client connections in case
// we have several servers that we want to signal to enter LD mode
// and not have their client reconnect to each other.
select {
case <-t.C:
s.Noticef("Closing existing clients")
case <-s.quitCh:
return
}
for i, client := range clients {
client.closeConnection(ServerShutdown)
if i == len(clients)-1 {
break
}
if batch == 1 || i%batch == 0 {
// We pick a random interval which will be at least si/2
v := rand.Int63n(si)
if v < si/2 {
v = si / 2
}
t.Reset(time.Duration(v))
// Sleep for given interval or bail out if kicked by Shutdown().
select {
case <-t.C:
case <-s.quitCh:
t.Stop()
return
}
}
}
s.Shutdown()
}
// If given error is a net.Error and is temporary, sleeps for the given
// delay and double it, but cap it to ACCEPT_MAX_SLEEP. The sleep is
// interrupted if the server is shutdown.
// An error message is displayed depending on the type of error.
// Returns the new (or unchanged) delay.
func (s *Server) acceptError(acceptName string, err error, tmpDelay time.Duration) time.Duration {
if ne, ok := err.(net.Error); ok && ne.Temporary() {
s.Errorf("Temporary %s Accept Error(%v), sleeping %dms", acceptName, ne, tmpDelay/time.Millisecond)
select {
case <-time.After(tmpDelay):
case <-s.quitCh:
return tmpDelay
}
tmpDelay *= 2
if tmpDelay > ACCEPT_MAX_SLEEP {
tmpDelay = ACCEPT_MAX_SLEEP
}
} else if s.isRunning() {
s.Errorf("%s Accept error: %v", acceptName, err)
}
return tmpDelay
}
func (s *Server) getRandomIP(resolver netResolver, url string) (string, error) {
host, port, err := net.SplitHostPort(url)
if err != nil {
return "", err
}
// If already an IP, skip.
if net.ParseIP(host) != nil {
return url, nil
}
ips, err := resolver.LookupHost(context.Background(), host)
if err != nil {
return "", fmt.Errorf("lookup for host %q: %v", host, err)
}
var address string
if len(ips) == 0 {
s.Warnf("Unable to get IP for %s, will try with %s: %v", host, url, err)
address = url
} else {
var ip string
if len(ips) == 1 {
ip = ips[0]
} else {
ip = ips[rand.Int31n(int32(len(ips)))]
}
// add the port
address = net.JoinHostPort(ip, port)
}
return address, nil
}
// Returns true for the first attempt and depending on the nature
// of the attempt (first connect or a reconnect), when the number
// of attempts is equal to the configured report attempts.
func (s *Server) shouldReportConnectErr(firstConnect bool, attempts int) bool {
opts := s.getOpts()
if firstConnect {
if attempts == 1 || attempts%opts.ConnectErrorReports == 0 {
return true
}
return false
}
if attempts == 1 || attempts%opts.ReconnectErrorReports == 0 {
return true
}
return false
}
// Invoked for route, leaf and gateway connections. Set the very first
// PING to a lower interval to capture the initial RTT.
// After that the PING interval will be set to the user defined value.
// Client lock should be held.
func (s *Server) setFirstPingTimer(c *client) {
opts := s.getOpts()
d := opts.PingInterval
if !opts.DisableShortFirstPing {
if c.kind != CLIENT {
if d > firstPingInterval {
d = firstPingInterval
}
} else if d > firstClientPingInterval {
d = firstClientPingInterval
}
}
// We randomize the first one by an offset up to 20%, e.g. 2m ~= max 24s.
addDelay := rand.Int63n(int64(d / 5))
d += time.Duration(addDelay)
c.ping.tmr = time.AfterFunc(d, c.processPingTimer)
}
| 1 | 10,006 | Why not go back to `c.setPingTimer()` here instead so you don't need the new boolean in setFirstPingTimer(). | nats-io-nats-server | go |
@@ -1,4 +1,4 @@
-/*
+/*
* Original author: Brendan MacLean <brendanx .at. u.washington.edu>,
* MacCoss Lab, Department of Genome Sciences, UW
* | 1 | /*
* Original author: Brendan MacLean <brendanx .at. u.washington.edu>,
* MacCoss Lab, Department of Genome Sciences, UW
*
* Copyright 2009 University of Washington - Seattle, WA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using pwiz.BiblioSpec.Properties;
using pwiz.Common.SystemUtil;
namespace pwiz.BiblioSpec
{
// ReSharper disable InconsistentNaming
public enum LibraryBuildAction { Create, Append }
// ReSharper restore InconsistentNaming
public static class LibraryBuildActionExtension
{
private static string[] LOCALIZED_VALUES
{
get
{
return new[]
{
Resources.LibraryBuildActionExtension_LOCALIZED_VALUES_Create,
Resources.LibraryBuildActionExtension_LOCALIZED_VALUES_Append
};
}
}
public static string GetLocalizedString(this LibraryBuildAction val)
{
return LOCALIZED_VALUES[(int)val];
}
public static LibraryBuildAction GetEnum(string enumValue)
{
for (int i = 0; i < LOCALIZED_VALUES.Length; i++)
{
if (LOCALIZED_VALUES[i] == enumValue)
{
return (LibraryBuildAction)i;
}
}
throw new ArgumentException(string.Format(Resources.LibraryBuildActionExtension_GetEnum_The_string___0___does_not_match_an_enum_value, enumValue));
}
public static LibraryBuildAction GetEnum(string enumValue, LibraryBuildAction defaultValue)
{
for (int i = 0; i < LOCALIZED_VALUES.Length; i++)
{
if (LOCALIZED_VALUES[i] == enumValue)
{
return (LibraryBuildAction)i;
}
}
return defaultValue;
}
}
public sealed class BlibBuild
{
private const string EXE_BLIB_BUILD = "BlibBuild"; // Not L10N
public const string EXT_SQLITE_JOURNAL = "-journal"; // Not L10N
private ReadOnlyCollection<string> _inputFiles;
public BlibBuild(string outputPath, IList<string> inputFiles, IList<string> targetSequences = null)
{
OutputPath = outputPath;
InputFiles = inputFiles;
TargetSequences = targetSequences;
}
public string OutputPath { get; private set; }
public string Id { get;set; }
public double? CutOffScore { get; set; }
public string Authority { get; set; }
public int? CompressLevel { get; set; }
public bool IncludeAmbiguousMatches { get; set; }
public IList<string> InputFiles
{
get { return _inputFiles; }
private set { _inputFiles = value as ReadOnlyCollection<string> ?? new ReadOnlyCollection<string>(value); }
}
public IList<string> TargetSequences { get; private set; }
public bool BuildLibrary(LibraryBuildAction libraryBuildAction, IProgressMonitor progressMonitor, ref IProgressStatus status, out string[] ambiguous)
{
// Arguments for BlibBuild
// ReSharper disable NonLocalizedString
List<string> argv = new List<string> { "-s", "-A", "-H" }; // Read from stdin, get ambiguous match messages, high precision modifications
if (libraryBuildAction == LibraryBuildAction.Create)
argv.Add("-o");
if (CutOffScore.HasValue)
{
argv.Add("-c");
argv.Add(CutOffScore.Value.ToString(CultureInfo.InvariantCulture));
}
if (CompressLevel.HasValue)
{
argv.Add("-l");
argv.Add(CompressLevel.Value.ToString(CultureInfo.InvariantCulture));
}
if (!string.IsNullOrEmpty(Authority))
{
argv.Add("-a");
argv.Add(Authority);
}
if (!string.IsNullOrEmpty(Id))
{
argv.Add("-i");
argv.Add(Id);
}
if (IncludeAmbiguousMatches)
{
argv.Add("-K");
}
string dirCommon = PathEx.GetCommonRoot(InputFiles);
var stdinBuilder = new StringBuilder();
foreach (string fileName in InputFiles)
stdinBuilder.AppendLine(fileName.Substring(dirCommon.Length));
if (TargetSequences != null)
{
argv.Add("-U");
stdinBuilder.AppendLine();
foreach (string targetSequence in TargetSequences)
stdinBuilder.AppendLine(targetSequence);
}
// ReSharper restore NonLocalizedString
argv.Add("\"" + OutputPath + "\""); // Not L10N
var psiBlibBuilder = new ProcessStartInfo(EXE_BLIB_BUILD)
{
CreateNoWindow = true,
UseShellExecute = false,
// Common directory includes the directory separator
WorkingDirectory = dirCommon.Substring(0, dirCommon.Length - 1),
Arguments = string.Join(" ", argv.ToArray()), // Not L10N
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true
};
bool isComplete = false;
ambiguous = new string[0];
try
{
var processRunner = new ProcessRunner {MessagePrefix = "AMBIGUOUS:"}; // Not L10N
processRunner.Run(psiBlibBuilder, stdinBuilder.ToString(), progressMonitor, ref status);
isComplete = status.IsComplete;
if (isComplete)
ambiguous = processRunner.MessageLog().Distinct().OrderBy(s => s).ToArray();
}
finally
{
if (!isComplete)
{
// If something happened (error or cancel) to end processing, then
// get rid of the possibly partial library.
File.Delete(OutputPath);
File.Delete(OutputPath + EXT_SQLITE_JOURNAL);
}
}
return isComplete;
}
}
}
| 1 | 12,314 | We should figure out why so many of these files have an invisible change on the first line: Are we writing out some sort of byte order mark? | ProteoWizard-pwiz | .cs |
@@ -1,19 +1,3 @@
-/*
-Copyright 2018 The Kubernetes Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
package resource
import ( | 1 | /*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package resource
import (
"io/ioutil"
log "github.com/sirupsen/logrus"
"k8s.io/client-go/rest"
configapi "k8s.io/client-go/tools/clientcmd/api"
)
const (
tokenFile = "/var/run/secrets/kubernetes.io/serviceaccount/token"
)
// GenerateClientConfigFromRESTConfig generates a new kubeconfig using a given rest.Config.
// The rest.Config may come from in-cluster config (as in a pod) or an existing kubeconfig.
func GenerateClientConfigFromRESTConfig(name string, restConfig *rest.Config) *configapi.Config {
cfg := &configapi.Config{
Kind: "Config",
APIVersion: "v1",
Clusters: map[string]*configapi.Cluster{},
AuthInfos: map[string]*configapi.AuthInfo{},
Contexts: map[string]*configapi.Context{},
CurrentContext: name,
}
cluster := &configapi.Cluster{
Server: restConfig.Host,
InsecureSkipTLSVerify: restConfig.Insecure,
CertificateAuthority: restConfig.CAFile,
CertificateAuthorityData: restConfig.CAData,
}
authInfo := &configapi.AuthInfo{
ClientCertificate: restConfig.CertFile,
ClientCertificateData: restConfig.CertData,
ClientKey: restConfig.KeyFile,
ClientKeyData: restConfig.KeyData,
Token: restConfig.BearerToken,
Username: restConfig.Username,
Password: restConfig.Password,
}
if restConfig.WrapTransport != nil && len(restConfig.BearerToken) == 0 {
token, err := ioutil.ReadFile(tokenFile)
if err != nil {
log.WithError(err).Warning("empty bearer token and cannot read token file")
} else {
authInfo.Token = string(token)
}
}
context := &configapi.Context{
Cluster: name,
AuthInfo: name,
}
cfg.Clusters[name] = cluster
cfg.AuthInfos[name] = authInfo
cfg.Contexts[name] = context
return cfg
}
| 1 | 6,592 | Was this our code @csrwng | openshift-hive | go |
@@ -24,6 +24,7 @@ module Travis
end
sh.echo "Build id: #{Shellwords.escape(data.build[:id])}"
sh.echo "Job id: #{Shellwords.escape(data.job[:id])}"
+ sh.echo "Runtime kernel version: #{`uname -r`.strip}"
end
def show_travis_build_version | 1 | require 'travis/build/appliances/base'
require 'shellwords'
module Travis
module Build
module Appliances
class ShowSystemInfo < Base
def apply
sh.fold 'system_info' do
header
show_travis_build_version
show_system_info_file
end
sh.newline
end
private
def header
sh.echo 'Build system information', ansi: :yellow
[:language, :group, :dist].each do |name|
value = data.send(name)
sh.echo "Build #{name}: #{Shellwords.escape(value)}" if value
end
sh.echo "Build id: #{Shellwords.escape(data.build[:id])}"
sh.echo "Job id: #{Shellwords.escape(data.job[:id])}"
end
def show_travis_build_version
if ENV['HEROKU_SLUG_COMMIT']
sh.echo "travis-build version: #{ENV['HEROKU_SLUG_COMMIT']}".untaint
end
end
def show_system_info_file
sh.if "-f #{info_file}" do
sh.cmd "cat #{info_file}"
end
end
def info_file
'/usr/share/travis/system_info'
end
end
end
end
end
| 1 | 15,570 | I think you need `.untaint` here. | travis-ci-travis-build | rb |
@@ -227,7 +227,10 @@ module Bolt
raise Bolt::ValidationError, "The project '#{name}' will not be loaded. The project name conflicts "\
"with a built-in Bolt module of the same name."
end
- else
+ elsif name.nil? &&
+ (File.directory?(plans_path) ||
+ File.directory?(@path + 'tasks') ||
+ File.directory?(@path + 'files'))
message = "No project name is specified in bolt-project.yaml. Project-level content will not be available."
@logs << { warn: message }
end | 1 | # frozen_string_literal: true
require 'pathname'
require 'bolt/config'
require 'bolt/validator'
require 'bolt/pal'
require 'bolt/module'
module Bolt
class Project
BOLTDIR_NAME = 'Boltdir'
CONFIG_NAME = 'bolt-project.yaml'
attr_reader :path, :data, :config_file, :inventory_file, :hiera_config,
:puppetfile, :rerunfile, :type, :resource_types, :logs, :project_file,
:deprecations, :downloads, :plans_path, :modulepath, :managed_moduledir,
:backup_dir, :cache_file
def self.default_project(logs = [])
create_project(File.expand_path(File.join('~', '.puppetlabs', 'bolt')), 'user', logs)
# If homedir isn't defined use the system config path
rescue ArgumentError
create_project(Bolt::Config.system_path, 'system', logs)
end
# Search recursively up the directory hierarchy for the Project. Look for a
# directory called Boltdir or a file called bolt.yaml (for a control repo
# type Project). Otherwise, repeat the check on each directory up the
# hierarchy, falling back to the default if we reach the root.
def self.find_boltdir(dir, logs = [], deprecations = [])
dir = Pathname.new(dir)
if (dir + BOLTDIR_NAME).directory?
create_project(dir + BOLTDIR_NAME, 'embedded', logs)
elsif (dir + 'bolt.yaml').file?
command = Bolt::Util.powershell? ? 'Update-BoltProject' : 'bolt project migrate'
msg = "Configuration file #{dir + 'bolt.yaml'} is deprecated and will be "\
"removed in Bolt 3.0.\nUpdate your Bolt project to the latest Bolt practices "\
"using #{command}"
deprecations << { type: "Project level bolt.yaml",
msg: msg }
create_project(dir, 'local', logs, deprecations)
elsif (dir + CONFIG_NAME).file?
create_project(dir, 'local', logs)
elsif dir.root?
default_project(logs)
else
logs << { debug: "Did not detect Boltdir, bolt.yaml, or bolt-project.yaml at '#{dir}'. "\
"This directory won't be loaded as a project." }
find_boltdir(dir.parent, logs, deprecations)
end
end
def self.create_project(path, type = 'option', logs = [], deprecations = [])
fullpath = Pathname.new(path).expand_path
if type == 'user'
begin
# This is already expanded if the type is user
FileUtils.mkdir_p(path)
rescue StandardError
logs << { warn: "Could not create default project at #{path}. Continuing without a writeable project. "\
"Log and rerun files will not be written." }
end
end
if type == 'option' && !File.directory?(path)
raise Bolt::Error.new("Could not find project at #{path}", "bolt/project-error")
end
if !Bolt::Util.windows? && type != 'environment' && fullpath.world_writable?
raise Bolt::Error.new(
"Project directory '#{fullpath}' is world-writable which poses a security risk. Set "\
"BOLT_PROJECT='#{fullpath}' to force the use of this project directory.",
"bolt/world-writable-error"
)
end
project_file = File.join(fullpath, CONFIG_NAME)
data = Bolt::Util.read_optional_yaml_hash(File.expand_path(project_file), 'project')
default = type =~ /user|system/ ? 'default ' : ''
exist = File.exist?(File.expand_path(project_file))
logs << { info: "Loaded #{default}project from '#{fullpath}'" } if exist
Bolt::Validator.new.tap do |validator|
validator.validate(data, schema, project_file)
validator.warnings.each { |warning| logs << { warn: warning } }
validator.deprecations.each do |dep|
deprecations << { type: "#{CONFIG_NAME} #{dep[:option]}", msg: dep[:message] }
end
end
new(data, path, type, logs, deprecations)
end
# Builds the schema for bolt-project.yaml used by the validator.
#
def self.schema
{
type: Hash,
properties: Bolt::Config::BOLT_PROJECT_OPTIONS.map { |opt| [opt, _ref: opt] }.to_h,
definitions: Bolt::Config::OPTIONS
}
end
def initialize(raw_data, path, type = 'option', logs = [], deprecations = [])
@path = Pathname.new(path).expand_path
@project_file = @path + CONFIG_NAME
@logs = logs
@deprecations = deprecations
if (@path + 'bolt.yaml').file? && project_file?
msg = "Project-level configuration in bolt.yaml is deprecated if using bolt-project.yaml. "\
"Transport config should be set in inventory.yaml, all other config should be set in "\
"bolt-project.yaml."
@deprecations << { type: 'Using bolt.yaml for project configuration', msg: msg }
end
@inventory_file = @path + 'inventory.yaml'
@hiera_config = @path + 'hiera.yaml'
@puppetfile = @path + 'Puppetfile'
@rerunfile = @path + '.rerun.json'
@resource_types = @path + '.resource_types'
@type = type
@downloads = @path + 'downloads'
@plans_path = @path + 'plans'
@managed_moduledir = @path + '.modules'
@backup_dir = @path + '.bolt-bak'
@cache_file = @path + '.plugin_cache.json'
tc = Bolt::Config::INVENTORY_OPTIONS.keys & raw_data.keys
if tc.any?
msg = "Transport configuration isn't supported in bolt-project.yaml. Ignoring keys #{tc}"
@logs << { warn: msg }
end
@data = raw_data.reject { |k, _| Bolt::Config::INVENTORY_OPTIONS.include?(k) }
# If the 'modules' key is present in the project configuration file,
# use the new, shorter modulepath.
@modulepath = if @data.key?('modules')
[(@path + 'modules').to_s]
else
[(@path + 'modules').to_s, (@path + 'site-modules').to_s, (@path + 'site').to_s]
end
# Once bolt.yaml deprecation is removed, this attribute should be removed
# and replaced with .project_file in lib/bolt/config.rb
@config_file = if (Bolt::Config::BOLT_OPTIONS & @data.keys).any?
if (@path + 'bolt.yaml').file?
msg = "bolt-project.yaml contains valid config keys, bolt.yaml will be ignored"
@logs << { warn: msg }
end
@project_file
else
@path + 'bolt.yaml'
end
validate if project_file?
end
def to_s
@path.to_s
end
# This API is used to prepend the project as a module to Puppet's internal
# module_references list. CHANGE AT YOUR OWN RISK
def to_h
{ path: @path.to_s,
name: name,
load_as_module?: load_as_module? }
end
def eql?(other)
path == other.path
end
alias == eql?
def project_file?
@project_file.file?
end
def load_as_module?
!name.nil?
end
def name
@data['name']
end
def tasks
@data['tasks']
end
def plans
@data['plans']
end
def plugin_cache
@data['plugin-cache']
end
def module_install
@data['module-install']
end
def modules
@modules ||= @data['modules']&.map do |mod|
if mod.is_a?(String)
{ 'name' => mod }
else
mod
end
end
end
def validate
if name
if name !~ Bolt::Module::MODULE_NAME_REGEX
raise Bolt::ValidationError, <<~ERROR_STRING
Invalid project name '#{name}' in bolt-project.yaml; project name must begin with a lowercase letter
and can include lowercase letters, numbers, and underscores.
ERROR_STRING
elsif Dir.children(Bolt::Config::Modulepath::BOLTLIB_PATH).include?(name)
raise Bolt::ValidationError, "The project '#{name}' will not be loaded. The project name conflicts "\
"with a built-in Bolt module of the same name."
end
else
message = "No project name is specified in bolt-project.yaml. Project-level content will not be available."
@logs << { warn: message }
end
end
def check_deprecated_file
if (@path + 'project.yaml').file?
msg = "Project configuration file 'project.yaml' is deprecated; use 'bolt-project.yaml' instead."
Bolt::Logger.deprecation_warning('Using project.yaml instead of bolt-project.yaml', msg)
end
end
end
end
| 1 | 17,318 | Why are we including the `files/` directory in this check? I know `tasks/` and `plans/` make sense, since you can reference content in those directories from the CLI, but I don't think you can for `files/` (unless I'm missing a command). | puppetlabs-bolt | rb |
@@ -19,6 +19,8 @@ package org.openqa.grid.web;
import com.google.common.collect.Maps;
+import com.sun.org.glassfish.gmbal.ManagedObject;
+
import org.openqa.grid.internal.Registry;
import org.openqa.grid.internal.utils.GridHubConfiguration;
import org.openqa.grid.web.servlet.DisplayHelpServlet; | 1 | /*
Copyright 2011 Selenium committers
Copyright 2011 Software Freedom Conservancy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.grid.web;
import com.google.common.collect.Maps;
import org.openqa.grid.internal.Registry;
import org.openqa.grid.internal.utils.GridHubConfiguration;
import org.openqa.grid.web.servlet.DisplayHelpServlet;
import org.openqa.grid.web.servlet.DriverServlet;
import org.openqa.grid.web.servlet.Grid1HeartbeatServlet;
import org.openqa.grid.web.servlet.HubStatusServlet;
import org.openqa.grid.web.servlet.LifecycleServlet;
import org.openqa.grid.web.servlet.ProxyStatusServlet;
import org.openqa.grid.web.servlet.RegistrationServlet;
import org.openqa.grid.web.servlet.ResourceServlet;
import org.openqa.grid.web.servlet.TestSessionStatusServlet;
import org.openqa.grid.web.servlet.beta.ConsoleServlet;
import org.openqa.grid.web.utils.ExtraServletUtil;
import org.openqa.selenium.net.NetworkUtils;
import org.seleniumhq.jetty7.server.Server;
import org.seleniumhq.jetty7.server.bio.SocketConnector;
import org.seleniumhq.jetty7.servlet.ServletContextHandler;
import org.seleniumhq.jetty7.util.thread.QueuedThreadPool;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.logging.Logger;
import javax.servlet.Servlet;
/**
* Jetty server. Main entry point for everything about the grid. <p/> Except for unit tests, this
* should be a singleton.
*/
public class Hub {
private static final Logger log = Logger.getLogger(Hub.class.getName());
private final int port;
private final String host;
private final int maxThread;
private final boolean isHostRestricted;
private final Registry registry;
private final Map<String, Class<? extends Servlet>> extraServlet = Maps.newHashMap();
private Server server;
private void addServlet(String key, Class<? extends Servlet> s) {
extraServlet.put(key, s);
}
/**
* get the registry backing up the hub state.
*
* @return The registry
*/
public Registry getRegistry() {
return registry;
}
public Hub(GridHubConfiguration config) {
registry = Registry.newInstance(this, config);
maxThread = config.getJettyMaxThreads();
if (config.getHost() != null) {
host = config.getHost();
isHostRestricted = true;
} else {
NetworkUtils utils = new NetworkUtils();
host = utils.getIp4NonLoopbackAddressOfThisMachine().getHostAddress();
isHostRestricted = false;
}
this.port = config.getPort();
for (String s : config.getServlets()) {
Class<? extends Servlet> servletClass = ExtraServletUtil.createServlet(s);
if (servletClass != null) {
String path = "/grid/admin/" + servletClass.getSimpleName() + "/*";
log.info("binding " + servletClass.getCanonicalName() + " to " + path);
addServlet(path, servletClass);
}
}
initServer();
}
private void initServer() {
try {
server = new Server();
SocketConnector socketListener = new SocketConnector();
socketListener.setMaxIdleTime(60000);
if (isHostRestricted) {
socketListener.setHost(host);
}
socketListener.setPort(port);
socketListener.setLowResourcesMaxIdleTime(6000);
server.addConnector(socketListener);
ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS);
root.setContextPath("/");
server.setHandler(root);
root.setAttribute(Registry.KEY, registry);
root.addServlet(DisplayHelpServlet.class.getName(), "/*");
root.addServlet(ConsoleServlet.class.getName(), "/grid/console/*");
root.addServlet(ConsoleServlet.class.getName(), "/grid/beta/console/*");
root.addServlet(org.openqa.grid.web.servlet.ConsoleServlet.class.getName(), "/grid/old/console/*");
root.addServlet(RegistrationServlet.class.getName(), "/grid/register/*");
// TODO remove at some point. Here for backward compatibility of
// tests etc.
root.addServlet(DriverServlet.class.getName(), "/grid/driver/*");
root.addServlet(DriverServlet.class.getName(), "/wd/hub/*");
root.addServlet(DriverServlet.class.getName(), "/selenium-server/driver/*");
root.addServlet(ResourceServlet.class.getName(), "/grid/resources/*");
root.addServlet(ProxyStatusServlet.class.getName(), "/grid/api/proxy/*");
root.addServlet(HubStatusServlet.class.getName(), "/grid/api/hub/*");
root.addServlet(TestSessionStatusServlet.class.getName(), "/grid/api/testsession/*");
root.addServlet(LifecycleServlet.class.getName(), "/lifecycle-manager/*");
// Selenium Grid 1.0 compatibility routes for older nodes trying to
// work with the newer hub.
root.addServlet(RegistrationServlet.class.getName(), "/registration-manager/register/*");
root.addServlet(Grid1HeartbeatServlet.class.getName(), "/heartbeat");
// Load any additional servlets provided by the user.
for (Map.Entry<String, Class<? extends Servlet>> entry : extraServlet.entrySet()) {
root.addServlet(entry.getValue().getName(), entry.getKey());
}
} catch (Throwable e) {
throw new RuntimeException("Error initializing the hub" + e.getMessage(), e);
}
}
public int getPort() {
return port;
}
public String getHost() {
return host;
}
public void start() throws Exception {
initServer();
if (maxThread>0){
QueuedThreadPool pool = new QueuedThreadPool();
pool.setMaxThreads(maxThread);
server.setThreadPool(pool);
}
server.start();
}
public void stop() throws Exception {
server.stop();
}
public URL getUrl() {
try {
return new URL("http://" + getHost() + ":" + getPort());
} catch (MalformedURLException e) {
throw new RuntimeException(e.getMessage());
}
}
public URL getRegistrationURL() {
String uri = "http://" + getHost() + ":" + getPort() + "/grid/register/";
try {
return new URL(uri);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
| 1 | 11,533 | And again. The reason it's bad is that if someone uses a JDK not produced by Oracle they won't have this class. | SeleniumHQ-selenium | java |
@@ -72,6 +72,11 @@ const (
// A valid Certificate requires at least one of a CommonName, DNSName, or
// URISAN to be valid.
type CertificateSpec struct {
+ // Full X509 name specification (https://golang.org/pkg/crypto/x509/pkix/#Name).
+ // If specified, overrides any other name elements below.
+ // +optional
+ X509Name *X509DistinguishedName `json:"x509Name,omitempty"`
+
// CommonName is a common name to be used on the Certificate.
// The CommonName should have a length of 64 characters or fewer to avoid
// generating invalid CSRs. | 1 | /*
Copyright 2019 The Jetstack cert-manager contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha2
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
cmmeta "github.com/jetstack/cert-manager/pkg/apis/meta/v1"
)
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// Certificate is a type to represent a Certificate from ACME
// +k8s:openapi-gen=true
// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=".status.conditions[?(@.type==\"Ready\")].status",description=""
// +kubebuilder:printcolumn:name="Secret",type="string",JSONPath=".spec.secretName",description=""
// +kubebuilder:printcolumn:name="Issuer",type="string",JSONPath=".spec.issuerRef.name",description="",priority=1
// +kubebuilder:printcolumn:name="Status",type="string",JSONPath=".status.conditions[?(@.type==\"Ready\")].message",priority=1
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="CreationTimestamp is a timestamp representing the server time when this object was created. It is not guaranteed to be set in happens-before order across separate operations. Clients may not set this value. It is represented in RFC3339 form and is in UTC."
// +kubebuilder:subresource:status
// +kubebuilder:resource:path=certificates,shortName=cert;certs
type Certificate struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec CertificateSpec `json:"spec,omitempty"`
Status CertificateStatus `json:"status,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// CertificateList is a list of Certificates
type CertificateList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata"`
Items []Certificate `json:"items"`
}
// +kubebuilder:validation:Enum=rsa;ecdsa
type KeyAlgorithm string
const (
RSAKeyAlgorithm KeyAlgorithm = "rsa"
ECDSAKeyAlgorithm KeyAlgorithm = "ecdsa"
)
// +kubebuilder:validation:Enum=pkcs1;pkcs8
type KeyEncoding string
const (
PKCS1 KeyEncoding = "pkcs1"
PKCS8 KeyEncoding = "pkcs8"
)
// CertificateSpec defines the desired state of Certificate.
// A valid Certificate requires at least one of a CommonName, DNSName, or
// URISAN to be valid.
type CertificateSpec struct {
// CommonName is a common name to be used on the Certificate.
// The CommonName should have a length of 64 characters or fewer to avoid
// generating invalid CSRs.
// +optional
CommonName string `json:"commonName,omitempty"`
// Organization is the organization to be used on the Certificate
// +optional
Organization []string `json:"organization,omitempty"`
// Certificate default Duration
// +optional
Duration *metav1.Duration `json:"duration,omitempty"`
// Certificate renew before expiration duration
// +optional
RenewBefore *metav1.Duration `json:"renewBefore,omitempty"`
// DNSNames is a list of subject alt names to be used on the Certificate.
// +optional
DNSNames []string `json:"dnsNames,omitempty"`
// IPAddresses is a list of IP addresses to be used on the Certificate
// +optional
IPAddresses []string `json:"ipAddresses,omitempty"`
// URISANs is a list of URI Subject Alternative Names to be set on this
// Certificate.
// +optional
URISANs []string `json:"uriSANs,omitempty"`
// SecretName is the name of the secret resource to store this secret in
SecretName string `json:"secretName"`
// IssuerRef is a reference to the issuer for this certificate.
// If the 'kind' field is not set, or set to 'Issuer', an Issuer resource
// with the given name in the same namespace as the Certificate will be used.
// If the 'kind' field is set to 'ClusterIssuer', a ClusterIssuer with the
// provided name will be used.
// The 'name' field in this stanza is required at all times.
IssuerRef cmmeta.ObjectReference `json:"issuerRef"`
// IsCA will mark this Certificate as valid for signing.
// This implies that the 'cert sign' usage is set
// +optional
IsCA bool `json:"isCA,omitempty"`
// Usages is the set of x509 actions that are enabled for a given key. Defaults are ('digital signature', 'key encipherment') if empty
// +optional
Usages []KeyUsage `json:"usages,omitempty"`
// KeySize is the key bit size of the corresponding private key for this certificate.
// If provided, value must be between 2048 and 8192 inclusive when KeyAlgorithm is
// empty or is set to "rsa", and value must be one of (256, 384, 521) when
// KeyAlgorithm is set to "ecdsa".
// +optional
KeySize int `json:"keySize,omitempty"`
// KeyAlgorithm is the private key algorithm of the corresponding private key
// for this certificate. If provided, allowed values are either "rsa" or "ecdsa"
// If KeyAlgorithm is specified and KeySize is not provided,
// key size of 256 will be used for "ecdsa" key algorithm and
// key size of 2048 will be used for "rsa" key algorithm.
// +optional
KeyAlgorithm KeyAlgorithm `json:"keyAlgorithm,omitempty"`
// KeyEncoding is the private key cryptography standards (PKCS)
// for this certificate's private key to be encoded in. If provided, allowed
// values are "pkcs1" and "pkcs8" standing for PKCS#1 and PKCS#8, respectively.
// If KeyEncoding is not specified, then PKCS#1 will be used by default.
KeyEncoding KeyEncoding `json:"keyEncoding,omitempty"`
}
// CertificateStatus defines the observed state of Certificate
type CertificateStatus struct {
// +optional
Conditions []CertificateCondition `json:"conditions,omitempty"`
// +optional
LastFailureTime *metav1.Time `json:"lastFailureTime,omitempty"`
// The expiration time of the certificate stored in the secret named
// by this resource in spec.secretName.
// +optional
NotAfter *metav1.Time `json:"notAfter,omitempty"`
}
// CertificateCondition contains condition information for an Certificate.
type CertificateCondition struct {
// Type of the condition, currently ('Ready').
Type CertificateConditionType `json:"type"`
// Status of the condition, one of ('True', 'False', 'Unknown').
Status cmmeta.ConditionStatus `json:"status"`
// LastTransitionTime is the timestamp corresponding to the last status
// change of this condition.
// +optional
LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"`
// Reason is a brief machine readable explanation for the condition's last
// transition.
// +optional
Reason string `json:"reason,omitempty"`
// Message is a human readable description of the details of the last
// transition, complementing reason.
// +optional
Message string `json:"message,omitempty"`
}
// CertificateConditionType represents an Certificate condition value.
type CertificateConditionType string
const (
// CertificateConditionReady indicates that a certificate is ready for use.
// This is defined as:
// - The target secret exists
// - The target secret contains a certificate that has not expired
// - The target secret contains a private key valid for the certificate
// - The commonName and dnsNames attributes match those specified on the Certificate
CertificateConditionReady CertificateConditionType = "Ready"
)
| 1 | 20,163 | Can we rename this field to `Subject`? Looking around, it seems like 'subject' is the standard terminology for this stanza | jetstack-cert-manager | go |
@@ -15,7 +15,7 @@ was persisted in the address book and the node has been restarted).
So the information has been changed, and potentially upon disconnection,
the depth can travel to a shallower depth in result.
-If a peer gets added through AddPeer, this does not necessarily infer
+If a peer gets added through AddPeers , this does not necessarily infer
an immediate depth change, since the peer might end up in the backlog for
a long time until we actually need to connect to her.
| 1 | // Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package kademlia provides an implementation of the topology.Driver interface
in a way that a kademlia connectivity is actively maintained by the node.
A thorough explanation of the logic in the `manage()` forever loop:
The `manageC` channel gets triggered every time there's a change in the
information regarding peers we know about. This can be a result of: (1) A peer
has disconnected from us (2) A peer has been added to the list of
known peers (from discovery, debugapi, bootnode flag or just because it
was persisted in the address book and the node has been restarted).
So the information has been changed, and potentially upon disconnection,
the depth can travel to a shallower depth in result.
If a peer gets added through AddPeer, this does not necessarily infer
an immediate depth change, since the peer might end up in the backlog for
a long time until we actually need to connect to her.
The `manage()` forever-loop will connect to peers in order from shallower
to deeper depths. This is because of depth calculation method that prioritizes empty bins
That are shallower than depth. An in-depth look at `recalcDepth()` method
will clarify this (more below). So if we will connect to peers from deeper
to shallower depths, all peers in all bins will qualify as peers we'd like
to connect to (see `binSaturated` method), ending up connecting to everyone we know about.
Another important notion one must observe while inspecting how `manage()`
works, is that when we connect to peers depth can only move in one direction,
which is deeper. So this becomes our strategy and we operate with this in mind,
this is also why we iterate from shallower to deeper - since additional
connections to peers for whatever reason can only result in increasing depth.
Empty intermediate bins should be eliminated by the `binSaturated` method indicating
a bin size too short, which in turn means that connections should be established
within this bin. Empty bins have special status in terms of depth calculation
and as mentioned before they are prioritized over deeper, non empty bins and
they constitute as the node's depth when the latter is recalculated.
For the rationale behind this please refer to the appropriate chapters in the book of Swarm.
A special case of the `manage()` functionality is that when we iterate over
peers and we come across a peer that has PO >= depth, we would always like
to connect to that peer. This should always be enforced within the bounds of
the `binSaturated` function and guarantees an ever increasing kademlia depth
in an ever-increasing size of Swarm, resulting in smaller areas of responsibility
for the nodes, maintaining a general upper bound of the assigned nominal
area of responsibility in terms of actual storage requirement. See book of Swarm for more details.
Worth to note is that `manage()` will always try to initiate connections when
a bin is not saturated, however currently it will not try to eliminate connections
on bins which might be over-saturated. Ideally it should be very cheap to maintain a
connection to a peer in a bin, so we should theoretically not aspire to eliminate connections prematurely.
It is also safe to assume we will always have more than the lower bound of peers in a bin, why?
(1) Initially, we will always try to satisfy our own connectivity requirement to saturate the bin
(2) Later on, other peers will get notified about our advertised address and
will try to connect to us in order to satisfy their own connectivity thresholds
We should allow other nodes to dial in, in order to help them maintain a healthy topolgy.
It could be, however, that we would need to mark-and-sweep certain connections once a
theorical upper bound has been reached.
Depth calculation explained:
When we calculate depth we must keep in mind the following constraints:
(1) A nearest-neighborhood constitutes of an arbitrary lower bound of the
closest peers we know about, this is defined in `nnLowWatermark` and is currently set to `2`
(2) Empty bins which are shallower than depth constitute as the node's area of responsibility
As of such, we would calculate depth in the following manner:
(1) Iterate over all peers we know about, from deepest (closest) to shallowest, and count until we reach `nnLowWatermark`
(2) Once we reach `nnLowWatermark`, mark current bin as depth candidate
(3) Iterate over all bins from shallowest to deepest, and look for the shallowest empty bin
(4) If the shallowest empty bin is shallower than the depth candidate - select shallowest bin as depth, otherwise select the candidate
Note: when we are connected to less or equal to `nnLowWatermark` peers, the
depth will always be considered `0`, thus a short-circuit is handling this edge
case explicitly in the `recalcDepth` method.
TODO: add pseudo-code how to calculate depth.
A few examples to depth calculation:
1. empty kademlia
bin | nodes
-------------
==DEPTH==
0 0
1 0
2 0
3 0
4 0
depth: 0
2. less or equal to two peers (nnLowWatermark=2) (a)
bin | nodes
-------------
==DEPTH==
0 1
1 1
2 0
3 0
4 0
depth: 0
3. less or equal to two peers (nnLowWatermark=2) (b)
bin | nodes
-------------
==DEPTH==
0 1
1 0
2 1
3 0
4 0
depth: 0
4. less or equal to two peers (nnLowWatermark=2) (c)
bin | nodes
-------------
==DEPTH==
0 2
1 0
2 0
3 0
4 0
depth: 0
5. empty shallow bin
bin | nodes
-------------
0 1
==DEPTH==
1 0
2 1
3 1
4 0
depth: 1 (depth candidate is 2, but 1 is shallower and empty)
6. no empty shallower bin, depth after nnLowerWatermark found
bin | nodes
-------------
0 1
1 1
==DEPTH==
2 1
3 1
4 0
depth: 2 (depth candidate is 2, shallowest empty bin is 4)
7. last bin size >= nnLowWatermark
bin | nodes
-------------
0 1
1 1
2 1
==DEPTH==
3 3
4 0
depth: 3 (depth candidate is 3, shallowest empty bin is 4)
8. all bins full
bin | nodes
-------------
0 1
1 1
2 1
3 3
==DEPTH==
4 2
depth: 4 (depth candidate is 4, no empty bins)
*/
package kademlia
| 1 | 11,864 | Remove additional whitespace. | ethersphere-bee | go |
@@ -171,6 +171,16 @@ func customResponseForwarder(ctx context.Context, w http.ResponseWriter, resp pr
http.SetCookie(w, cookie)
}
+ if cookies := md.HeaderMD.Get("Set-Cookie-Refresh-Token"); len(cookies) > 0 {
+ cookie := &http.Cookie{
+ Name: "refreshToken",
+ Value: cookies[0],
+ Path: "/v1/authn/login",
+ HttpOnly: true, // Client cannot access refresh token, it is sent by browser only if login is attempted.
+ }
+ http.SetCookie(w, cookie)
+ }
+
// Redirect if it's the browser (non-XHR).
redirects := md.HeaderMD.Get("Location")
if len(redirects) > 0 && isBrowser(requestHeadersFromResponseWriter(w)) { | 1 | package mux
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/http/pprof"
"net/textproto"
"net/url"
"path"
"regexp"
"strconv"
"strings"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
gatewayv1 "github.com/lyft/clutch/backend/api/config/gateway/v1"
"github.com/lyft/clutch/backend/service"
awsservice "github.com/lyft/clutch/backend/service/aws"
)
const (
xHeader = "X-"
xForwardedFor = "X-Forwarded-For"
xForwardedHost = "X-Forwarded-Host"
)
var apiPattern = regexp.MustCompile(`^/v\d+/`)
type assetHandler struct {
assetCfg *gatewayv1.Assets
next http.Handler
fileSystem http.FileSystem
fileServer http.Handler
}
func copyHTTPResponse(resp *http.Response, w http.ResponseWriter) {
for key, values := range resp.Header {
for _, val := range values {
w.Header().Add(key, val)
}
}
w.WriteHeader(resp.StatusCode)
_, _ = io.Copy(w, resp.Body)
}
func (a *assetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if apiPattern.MatchString(r.URL.Path) || r.URL.Path == "/healthcheck" {
// Serve from the embedded API handler.
a.next.ServeHTTP(w, r)
return
}
// Check if assets are okay to serve by calling the Fetch endpoint and verifying it returns a 200.
rec := httptest.NewRecorder()
origPath := r.URL.Path
r.URL.Path = "/v1/assets/fetch"
a.next.ServeHTTP(rec, r)
if rec.Code != http.StatusOK {
copyHTTPResponse(rec.Result(), w)
return
}
// Set the original path.
r.URL.Path = origPath
// Serve!
if f, err := a.fileSystem.Open(r.URL.Path); err != nil {
// If not a known static asset and an asset provider is configured, try streaming from the configured provider.
if a.assetCfg != nil && a.assetCfg.Provider != nil && strings.HasPrefix(r.URL.Path, "/static/") {
// We attach this header simply for observability purposes.
// Otherwise its difficult to know if the assets are being served from the configured provider.
w.Header().Set("x-clutch-asset-passthrough", "true")
asset, err := a.assetProviderHandler(r.Context(), r.URL.Path)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(fmt.Sprintf("Error getting assets from the configured asset provider: %v", err)))
return
}
defer asset.Close()
_, err = io.Copy(w, asset)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(fmt.Sprintf("Error getting assets from the configured asset provider: %v", err)))
return
}
return
}
// If not a known static asset serve the SPA.
r.URL.Path = "/"
} else {
_ = f.Close()
}
a.fileServer.ServeHTTP(w, r)
}
func (a *assetHandler) assetProviderHandler(ctx context.Context, urlPath string) (io.ReadCloser, error) {
switch a.assetCfg.Provider.(type) {
case *gatewayv1.Assets_S3:
aws, err := getAssetProviderService(a.assetCfg)
if err != nil {
return nil, err
}
awsClient, ok := aws.(awsservice.Client)
if !ok {
return nil, fmt.Errorf("Unable to aquire the aws client")
}
return awsClient.S3StreamingGet(
ctx,
a.assetCfg.GetS3().Region,
a.assetCfg.GetS3().Bucket,
path.Join(a.assetCfg.GetS3().Key, strings.TrimPrefix(urlPath, "/static")),
)
default:
return nil, fmt.Errorf("configured asset provider has not been implemented")
}
}
// getAssetProviderService is used in two different contexts
// Its invoked in the mux constructor which checks if the necessary service has been configured,
// if there is an asset provider which requires ones.
//
// Otherwise its used to get the service for an asset provider in assetProviderHandler() if necessary.
func getAssetProviderService(assetCfg *gatewayv1.Assets) (service.Service, error) {
switch assetCfg.Provider.(type) {
case *gatewayv1.Assets_S3:
aws, ok := service.Registry[awsservice.Name]
if !ok {
return nil, fmt.Errorf("The AWS service must be configured to use the asset s3 provider.")
}
return aws, nil
default:
// An asset provider does not necessarily require a service to function properly
// if there is nothing configured for a provider type we cant necessarily throw an error here.
return nil, nil
}
}
func customResponseForwarder(ctx context.Context, w http.ResponseWriter, resp proto.Message) error {
md, ok := runtime.ServerMetadataFromContext(ctx)
if !ok {
return nil
}
if cookies := md.HeaderMD.Get("Set-Cookie-Token"); len(cookies) > 0 {
cookie := &http.Cookie{
Name: "token",
Value: cookies[0],
Path: "/",
HttpOnly: false,
}
http.SetCookie(w, cookie)
}
// Redirect if it's the browser (non-XHR).
redirects := md.HeaderMD.Get("Location")
if len(redirects) > 0 && isBrowser(requestHeadersFromResponseWriter(w)) {
code := http.StatusFound
if st := md.HeaderMD.Get("Location-Status"); len(st) > 0 {
headerCodeOverride, err := strconv.Atoi(st[0])
if err != nil {
return err
}
code = headerCodeOverride
}
w.Header().Set("Location", redirects[0])
w.WriteHeader(code)
}
return nil
}
func customHeaderMatcher(key string) (string, bool) {
key = textproto.CanonicalMIMEHeaderKey(key)
if strings.HasPrefix(key, xHeader) {
// exclude handling these headers as they are looked up by grpc's annotate context flow and added to the context
// metadata if they're not found
if key != xForwardedFor && key != xForwardedHost {
return runtime.MetadataPrefix + key, true
}
}
// the the default header mapping rule
return runtime.DefaultHeaderMatcher(key)
}
func customErrorHandler(ctx context.Context, mux *runtime.ServeMux, m runtime.Marshaler, w http.ResponseWriter, req *http.Request, err error) {
if isBrowser(req.Header) { // Redirect if it's the browser (non-XHR).
if s, ok := status.FromError(err); ok && s.Code() == codes.Unauthenticated {
redirectPath := fmt.Sprintf("/v1/authn/login?redirect_url=%s", url.QueryEscape(req.RequestURI))
http.Redirect(w, req, redirectPath, http.StatusFound)
return
}
}
runtime.DefaultHTTPErrorHandler(ctx, mux, m, w, req, err)
}
func New(unaryInterceptors []grpc.UnaryServerInterceptor, assets http.FileSystem, gatewayCfg *gatewayv1.GatewayOptions) (*Mux, error) {
grpcServer := grpc.NewServer(grpc.ChainUnaryInterceptor(unaryInterceptors...))
jsonGateway := runtime.NewServeMux(
runtime.WithForwardResponseOption(customResponseForwarder),
runtime.WithErrorHandler(customErrorHandler),
runtime.WithMarshalerOption(
runtime.MIMEWildcard,
&runtime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
// Use camelCase for the JSON version.
UseProtoNames: false,
// Transmit zero-values over the wire.
EmitUnpopulated: true,
},
UnmarshalOptions: protojson.UnmarshalOptions{},
},
),
runtime.WithIncomingHeaderMatcher(customHeaderMatcher),
)
// If there is a configured asset provider, we check to see if the service is configured before proceeding.
// Bailing out early during the startup process instead of hitting this error at runtime when serving assets.
if gatewayCfg.Assets != nil && gatewayCfg.Assets.Provider != nil {
_, err := getAssetProviderService(gatewayCfg.Assets)
if err != nil {
return nil, err
}
}
httpMux := http.NewServeMux()
httpMux.Handle("/", &assetHandler{
assetCfg: gatewayCfg.Assets,
next: jsonGateway,
fileSystem: assets,
fileServer: http.FileServer(assets),
})
if gatewayCfg.EnablePprof {
httpMux.HandleFunc("/debug/pprof/", pprof.Index)
}
mux := &Mux{
GRPCServer: grpcServer,
JSONGateway: jsonGateway,
HTTPMux: httpMux,
}
return mux, nil
}
// Mux allows sharing one port between gRPC and the corresponding JSON gateway via header-based multiplexing.
type Mux struct {
// Create empty handlers for gRPC and grpc-gateway (JSON) traffic.
JSONGateway *runtime.ServeMux
HTTPMux http.Handler
GRPCServer *grpc.Server
}
// Adapted from https://github.com/grpc/grpc-go/blob/197c621/server.go#L760-L778.
func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 2 && strings.HasPrefix(r.Header.Get("Content-Type"), "application/grpc") {
m.GRPCServer.ServeHTTP(w, r)
} else {
m.HTTPMux.ServeHTTP(w, r)
}
}
func (m *Mux) EnableGRPCReflection() {
reflection.Register(m.GRPCServer)
}
// "h2c" is the unencrypted form of HTTP/2.
func InsecureHandler(handler http.Handler) http.Handler {
return h2c.NewHandler(handler, &http2.Server{})
}
| 1 | 11,202 | We should add `Secure` as well | lyft-clutch | go |
@@ -12,7 +12,7 @@ import (
// TestIntegration runs integration tests against the remote
func TestIntegration(t *testing.T) {
fstests.Run(t, &fstests.Opt{
- RemoteName: "TestWebdavNexcloud:",
+ RemoteName: "TestWebdavNextcloud:",
NilObject: (*webdav.Object)(nil),
})
} | 1 | // Test Webdav filesystem interface
package webdav_test
import (
"testing"
"github.com/rclone/rclone/backend/webdav"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/fstests"
)
// TestIntegration runs integration tests against the remote
func TestIntegration(t *testing.T) {
fstests.Run(t, &fstests.Opt{
RemoteName: "TestWebdavNexcloud:",
NilObject: (*webdav.Object)(nil),
})
}
// TestIntegration runs integration tests against the remote
func TestIntegration2(t *testing.T) {
if *fstest.RemoteName != "" {
t.Skip("skipping as -remote is set")
}
fstests.Run(t, &fstests.Opt{
RemoteName: "TestWebdavOwncloud:",
NilObject: (*webdav.Object)(nil),
})
}
// TestIntegration runs integration tests against the remote
func TestIntegration3(t *testing.T) {
if *fstest.RemoteName != "" {
t.Skip("skipping as -remote is set")
}
fstests.Run(t, &fstests.Opt{
RemoteName: "TestWebdavRclone:",
NilObject: (*webdav.Object)(nil),
})
}
| 1 | 12,081 | I presume this isn't a big deal | rclone-rclone | go |
@@ -2974,7 +2974,8 @@ raw_mem_alloc(size_t size, uint prot, void *addr, dr_alloc_flags_t flags)
: (TEST(DR_ALLOC_COMMIT_ONLY, flags) ? RAW_ALLOC_COMMIT_ONLY : 0);
# endif
if (IF_WINDOWS(TEST(DR_ALLOC_COMMIT_ONLY, flags) &&) addr != NULL &&
- !app_memory_pre_alloc(get_thread_private_dcontext(), addr, size, prot, false))
+ !app_memory_pre_alloc(get_thread_private_dcontext(), addr, size, prot, false,
+ true /*update*/, false /*!image*/))
p = NULL;
else
p = os_raw_mem_alloc(addr, size, prot, os_flags, &error_code); | 1 | /* ******************************************************************************
* Copyright (c) 2010-2019 Google, Inc. All rights reserved.
* Copyright (c) 2010-2011 Massachusetts Institute of Technology All rights reserved.
* Copyright (c) 2002-2010 VMware, Inc. All rights reserved.
* ******************************************************************************/
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of VMware, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
/* Copyright (c) 2003-2007 Determina Corp. */
/* Copyright (c) 2002-2003 Massachusetts Institute of Technology */
/* Copyright (c) 2002 Hewlett-Packard Company */
/*
* instrument.c - interface for instrumentation
*/
#include "../globals.h" /* just to disable warning C4206 about an empty file */
#include "instrument.h"
#include "arch.h"
#include "instr.h"
#include "instr_create.h"
#include "instrlist.h"
#include "decode.h"
#include "disassemble.h"
#include "../fragment.h"
#include "../fcache.h"
#include "../emit.h"
#include "../link.h"
#include "../monitor.h" /* for mark_trace_head */
#include <stdarg.h> /* for varargs */
#include "../nudge.h" /* for nudge_internal() */
#include "../synch.h"
#include "../annotations.h"
#include "../translate.h"
#ifdef UNIX
# include <sys/time.h> /* ITIMER_* */
# include "../unix/module.h" /* redirect_* functions */
#endif
#ifdef CLIENT_INTERFACE
/* in utils.c, not exported to everyone */
extern ssize_t
do_file_write(file_t f, const char *fmt, va_list ap);
# ifdef DEBUG
/* case 10450: give messages to clients */
/* we can't undef ASSERT b/c of DYNAMO_OPTION */
# undef ASSERT_TRUNCATE
# undef ASSERT_BITFIELD_TRUNCATE
# undef ASSERT_NOT_REACHED
# define ASSERT_TRUNCATE DO_NOT_USE_ASSERT_USE_CLIENT_ASSERT_INSTEAD
# define ASSERT_BITFIELD_TRUNCATE DO_NOT_USE_ASSERT_USE_CLIENT_ASSERT_INSTEAD
# define ASSERT_NOT_REACHED DO_NOT_USE_ASSERT_USE_CLIENT_ASSERT_INSTEAD
# endif
/* PR 200065: User passes us the shared library, we look up "dr_init"
* or "dr_client_main" and call it. From there, the client can register which events
* it wishes to receive.
*/
# define INSTRUMENT_INIT_NAME_LEGACY "dr_init"
# define INSTRUMENT_INIT_NAME "dr_client_main"
/* PR 250952: version check
* If changing this, don't forget to update:
* - lib/dr_defines.h _USES_DR_VERSION_
* - api/docs/footer.html
*/
# define USES_DR_VERSION_NAME "_USES_DR_VERSION_"
/* Should we expose this for use in samples/tracedump.c?
* Also, if we change this, need to change the symlink generation
* in core/CMakeLists.txt: at that point should share single define.
*/
/* OLDEST_COMPATIBLE_VERSION now comes from configure.h */
/* The 3rd version number, the bugfix/patch number, should not affect
* compatibility, so our version check number simply uses:
* major*100 + minor
* Which gives us room for 100 minor versions per major.
*/
# define NEWEST_COMPATIBLE_VERSION CURRENT_API_VERSION
/* Store the unique not-part-of-version build number (the version
* BUILD_NUMBER is limited to 64K and is not guaranteed to be unique)
* somewhere accessible at a customer site. We could alternatively
* pull it out of our DYNAMORIO_DEFINES string.
*/
DR_API const char *unique_build_number = STRINGIFY(UNIQUE_BUILD_NUMBER);
/* The flag d_r_client_avx512_code_in_use is described in arch.h. */
# define DR_CLIENT_AVX512_CODE_IN_USE_NAME "_DR_CLIENT_AVX512_CODE_IN_USE_"
/* Acquire when registering or unregistering event callbacks
* Also held when invoking events, which happens much more often
* than registration changes, so we use rwlock
*/
DECLARE_CXTSWPROT_VAR(static read_write_lock_t callback_registration_lock,
INIT_READWRITE_LOCK(callback_registration_lock));
/* Structures for maintaining lists of event callbacks */
typedef void (*callback_t)(void);
typedef struct _callback_list_t {
callback_t *callbacks; /* array of callback functions */
size_t num; /* number of callbacks registered */
size_t size; /* allocated space (may be larger than num) */
} callback_list_t;
/* This is a little convoluted. The following is a macro to iterate
* over a list of callbacks and call each function. We use a macro
* instead of a function so we can pass the function type and perform
* a typecast. We need to copy the callback list before iterating to
* support the possibility of one callback unregistering another and
* messing up the list while we're iterating. We'll optimize the case
* for 5 or fewer registered callbacks and stack-allocate the temp
* list. Otherwise, we'll heap-allocate the temp.
*
* We allow the args to use the var "idx" to access the client index.
*
* We consider the first registered callback to have the highest
* priority and call it last. If we gave the last registered callback
* the highest priority, a client could re-register a routine to
* increase its priority. That seems a little weird.
*/
/*
*/
# define FAST_COPY_SIZE 5
# define call_all_ret(ret, retop, postop, vec, type, ...) \
do { \
size_t idx, num; \
/* we will be called even if no callbacks (i.e., (vec).num == 0) */ \
/* we guarantee we're in DR state at all callbacks and clean calls */ \
/* XXX: add CLIENT_ASSERT here */ \
d_r_read_lock(&callback_registration_lock); \
num = (vec).num; \
if (num == 0) { \
d_r_read_unlock(&callback_registration_lock); \
} else if (num <= FAST_COPY_SIZE) { \
callback_t tmp[FAST_COPY_SIZE]; \
memcpy(tmp, (vec).callbacks, num * sizeof(callback_t)); \
d_r_read_unlock(&callback_registration_lock); \
for (idx = 0; idx < num; idx++) { \
ret retop(((type)tmp[num - idx - 1])(__VA_ARGS__)) postop; \
} \
} else { \
callback_t *tmp = HEAP_ARRAY_ALLOC(GLOBAL_DCONTEXT, callback_t, num, \
ACCT_OTHER, UNPROTECTED); \
memcpy(tmp, (vec).callbacks, num * sizeof(callback_t)); \
d_r_read_unlock(&callback_registration_lock); \
for (idx = 0; idx < num; idx++) { \
ret retop(((type)tmp[num - idx - 1])(__VA_ARGS__)) postop; \
} \
HEAP_ARRAY_FREE(GLOBAL_DCONTEXT, tmp, callback_t, num, ACCT_OTHER, \
UNPROTECTED); \
} \
} while (0)
/* It's less error-prone if we just have one call_all macro. We'll
* reuse call_all_ret above for callbacks that don't have a return
* value by assigning to a dummy var. Note that this means we'll
* have to pass an int-returning type to call_all()
*/
# define call_all(vec, type, ...) \
do { \
int dummy; \
call_all_ret(dummy, =, , vec, type, __VA_ARGS__); \
} while (0)
/* Lists of callbacks for each event type. Note that init and nudge
* callback lists are kept in the client_lib_t data structure below.
* We could store all lists on a per-client basis, but we can iterate
* over these lists slightly more efficiently if we store all
* callbacks for a specific event in a single list.
*/
static callback_list_t exit_callbacks = {
0,
};
static callback_list_t thread_init_callbacks = {
0,
};
static callback_list_t thread_exit_callbacks = {
0,
};
# ifdef UNIX
static callback_list_t fork_init_callbacks = {
0,
};
# endif
static callback_list_t bb_callbacks = {
0,
};
static callback_list_t trace_callbacks = {
0,
};
# ifdef CUSTOM_TRACES
static callback_list_t end_trace_callbacks = {
0,
};
# endif
static callback_list_t fragdel_callbacks = {
0,
};
static callback_list_t restore_state_callbacks = {
0,
};
static callback_list_t restore_state_ex_callbacks = {
0,
};
static callback_list_t module_load_callbacks = {
0,
};
static callback_list_t module_unload_callbacks = {
0,
};
static callback_list_t filter_syscall_callbacks = {
0,
};
static callback_list_t pre_syscall_callbacks = {
0,
};
static callback_list_t post_syscall_callbacks = {
0,
};
static callback_list_t kernel_xfer_callbacks = {
0,
};
# ifdef WINDOWS
static callback_list_t exception_callbacks = {
0,
};
# else
static callback_list_t signal_callbacks = {
0,
};
# endif
# ifdef PROGRAM_SHEPHERDING
static callback_list_t security_violation_callbacks = {
0,
};
# endif
static callback_list_t persist_ro_size_callbacks = {
0,
};
static callback_list_t persist_ro_callbacks = {
0,
};
static callback_list_t resurrect_ro_callbacks = {
0,
};
static callback_list_t persist_rx_size_callbacks = {
0,
};
static callback_list_t persist_rx_callbacks = {
0,
};
static callback_list_t resurrect_rx_callbacks = {
0,
};
static callback_list_t persist_rw_size_callbacks = {
0,
};
static callback_list_t persist_rw_callbacks = {
0,
};
static callback_list_t resurrect_rw_callbacks = {
0,
};
static callback_list_t persist_patch_callbacks = {
0,
};
/* An array of client libraries. We use a static array instead of a
* heap-allocated list so we can load the client libs before
* initializing DR's heap.
*/
typedef struct _client_lib_t {
client_id_t id;
char path[MAXIMUM_PATH];
/* PR 366195: dlopen() handle truly is opaque: != start */
shlib_handle_t lib;
app_pc start;
app_pc end;
/* The raw option string, which after i#1736 contains token-delimiting quotes */
char options[MAX_OPTION_LENGTH];
/* The option string with token-delimiting quotes removed for backward compat */
char legacy_options[MAX_OPTION_LENGTH];
/* The parsed options: */
int argc;
const char **argv;
/* We need to associate nudge events with a specific client so we
* store that list here in the client_lib_t instead of using a
* single global list.
*/
callback_list_t nudge_callbacks;
} client_lib_t;
/* these should only be modified prior to instrument_init(), since no
* readers of the client_libs array (event handlers, etc.) use synch
*/
static client_lib_t client_libs[MAX_CLIENT_LIBS] = { {
0,
} };
static size_t num_client_libs = 0;
static void *persist_user_data[MAX_CLIENT_LIBS];
# ifdef WINDOWS
/* private kernel32 lib, used to print to console */
static bool print_to_console;
static shlib_handle_t priv_kernel32;
typedef BOOL(WINAPI *kernel32_WriteFile_t)(HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED);
static kernel32_WriteFile_t kernel32_WriteFile;
static ssize_t
dr_write_to_console_varg(bool to_stdout, const char *fmt, ...);
# endif
bool client_requested_exit;
# ifdef WINDOWS
/* used for nudge support */
static bool block_client_nudge_threads = false;
DECLARE_CXTSWPROT_VAR(static int num_client_nudge_threads, 0);
# endif
# ifdef CLIENT_SIDELINE
/* # of sideline threads */
DECLARE_CXTSWPROT_VAR(static int num_client_sideline_threads, 0);
# endif
# if defined(WINDOWS) || defined(CLIENT_SIDELINE)
/* protects block_client_nudge_threads and incrementing num_client_nudge_threads */
DECLARE_CXTSWPROT_VAR(static mutex_t client_thread_count_lock,
INIT_LOCK_FREE(client_thread_count_lock));
# endif
static vm_area_vector_t *client_aux_libs;
static bool track_where_am_i;
# ifdef WINDOWS
DECLARE_CXTSWPROT_VAR(static mutex_t client_aux_lib64_lock,
INIT_LOCK_FREE(client_aux_lib64_lock));
# endif
/****************************************************************************/
/* INTERNAL ROUTINES */
static bool
char_is_quote(char c)
{
return c == '"' || c == '\'' || c == '`';
}
static void
parse_option_array(client_id_t client_id, const char *opstr, int *argc OUT,
const char ***argv OUT, size_t max_token_size)
{
const char **a;
int cnt;
const char *s;
char *token =
HEAP_ARRAY_ALLOC(GLOBAL_DCONTEXT, char, max_token_size, ACCT_CLIENT, UNPROTECTED);
for (cnt = 0, s = dr_get_token(opstr, token, max_token_size); s != NULL;
s = dr_get_token(s, token, max_token_size)) {
cnt++;
}
cnt++; /* add 1 so 0 can be "app" */
a = HEAP_ARRAY_ALLOC(GLOBAL_DCONTEXT, const char *, cnt, ACCT_CLIENT, UNPROTECTED);
cnt = 0;
a[cnt] = dr_strdup(dr_get_client_path(client_id) HEAPACCT(ACCT_CLIENT));
cnt++;
for (s = dr_get_token(opstr, token, max_token_size); s != NULL;
s = dr_get_token(s, token, max_token_size)) {
a[cnt] = dr_strdup(token HEAPACCT(ACCT_CLIENT));
cnt++;
}
HEAP_ARRAY_FREE(GLOBAL_DCONTEXT, token, char, max_token_size, ACCT_CLIENT,
UNPROTECTED);
*argc = cnt;
*argv = a;
}
static bool
free_option_array(int argc, const char **argv)
{
int i;
for (i = 0; i < argc; i++) {
dr_strfree(argv[i] HEAPACCT(ACCT_CLIENT));
}
HEAP_ARRAY_FREE(GLOBAL_DCONTEXT, argv, char *, argc, ACCT_CLIENT, UNPROTECTED);
return true;
}
static void
add_callback(callback_list_t *vec, void (*func)(void), bool unprotect)
{
if (func == NULL) {
CLIENT_ASSERT(false, "trying to register a NULL callback");
return;
}
if (standalone_library) {
CLIENT_ASSERT(false, "events not supported in standalone library mode");
return;
}
d_r_write_lock(&callback_registration_lock);
/* Although we're receiving a pointer to a callback_list_t, we're
* usually modifying a static var.
*/
if (unprotect) {
SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT);
}
/* We may already have an open slot since we allocate in twos and
* because we don't bother to free the storage when we remove the
* callback. Check and only allocate if necessary.
*/
if (vec->num == vec->size) {
callback_t *tmp = HEAP_ARRAY_ALLOC(GLOBAL_DCONTEXT, callback_t,
vec->size + 2, /* Let's allocate 2 */
ACCT_OTHER, UNPROTECTED);
if (tmp == NULL) {
CLIENT_ASSERT(false, "out of memory: can't register callback");
d_r_write_unlock(&callback_registration_lock);
return;
}
if (vec->callbacks != NULL) {
memcpy(tmp, vec->callbacks, vec->num * sizeof(callback_t));
HEAP_ARRAY_FREE(GLOBAL_DCONTEXT, vec->callbacks, callback_t, vec->size,
ACCT_OTHER, UNPROTECTED);
}
vec->callbacks = tmp;
vec->size += 2;
}
vec->callbacks[vec->num] = func;
vec->num++;
if (unprotect) {
SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT);
}
d_r_write_unlock(&callback_registration_lock);
}
static bool
remove_callback(callback_list_t *vec, void (*func)(void), bool unprotect)
{
size_t i;
bool found = false;
if (func == NULL) {
CLIENT_ASSERT(false, "trying to unregister a NULL callback");
return false;
}
d_r_write_lock(&callback_registration_lock);
/* Although we're receiving a pointer to a callback_list_t, we're
* usually modifying a static var.
*/
if (unprotect) {
SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT);
}
for (i = 0; i < vec->num; i++) {
if (vec->callbacks[i] == func) {
size_t j;
/* shift down the entries on the tail */
for (j = i; j < vec->num - 1; j++) {
vec->callbacks[j] = vec->callbacks[j + 1];
}
vec->num -= 1;
found = true;
break;
}
}
if (unprotect) {
SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT);
}
d_r_write_unlock(&callback_registration_lock);
return found;
}
/* This should only be called prior to instrument_init(),
* since no readers of the client_libs array use synch
* and since this routine assumes .data is writable.
*/
static void
add_client_lib(const char *path, const char *id_str, const char *options)
{
client_id_t id;
shlib_handle_t client_lib;
DEBUG_DECLARE(size_t i);
ASSERT(!dynamo_initialized);
/* if ID not specified, we'll default to 0 */
id = (id_str == NULL) ? 0 : strtoul(id_str, NULL, 16);
# ifdef DEBUG
/* Check for conflicting IDs */
for (i = 0; i < num_client_libs; i++) {
CLIENT_ASSERT(client_libs[i].id != id, "Clients have the same ID");
}
# endif
if (num_client_libs == MAX_CLIENT_LIBS) {
CLIENT_ASSERT(false, "Max number of clients reached");
return;
}
LOG(GLOBAL, LOG_INTERP, 4, "about to load client library %s\n", path);
client_lib =
load_shared_library(path, IF_X64_ELSE(DYNAMO_OPTION(reachable_client), true));
if (client_lib == NULL) {
char msg[MAXIMUM_PATH * 4];
char err[MAXIMUM_PATH * 2];
shared_library_error(err, BUFFER_SIZE_ELEMENTS(err));
snprintf(msg, BUFFER_SIZE_ELEMENTS(msg),
".\n\tError opening instrumentation library %s:\n\t%s", path, err);
NULL_TERMINATE_BUFFER(msg);
/* PR 232490 - malformed library names or incorrect
* permissions shouldn't blow up an app in release builds as
* they may happen at customer sites with a third party
* client.
*/
/* PR 408318: 32-vs-64 errors should NOT be fatal to continue
* in debug build across execve chains. Xref i#147.
* XXX: w/ -private_loader, err always equals "error in private loader"
* and so we never match here!
*/
IF_UNIX(if (strstr(err, "wrong ELF class") == NULL))
CLIENT_ASSERT(false, msg);
SYSLOG(SYSLOG_ERROR, CLIENT_LIBRARY_UNLOADABLE, 4, get_application_name(),
get_application_pid(), path, msg);
} else {
/* PR 250952: version check */
int *uses_dr_version =
(int *)lookup_library_routine(client_lib, USES_DR_VERSION_NAME);
if (uses_dr_version == NULL || *uses_dr_version < OLDEST_COMPATIBLE_VERSION ||
*uses_dr_version > NEWEST_COMPATIBLE_VERSION) {
/* not a fatal usage error since we want release build to continue */
CLIENT_ASSERT(false,
"client library is incompatible with this version of DR");
SYSLOG(SYSLOG_ERROR, CLIENT_VERSION_INCOMPATIBLE, 2, get_application_name(),
get_application_pid());
} else {
size_t idx = num_client_libs++;
client_libs[idx].id = id;
client_libs[idx].lib = client_lib;
app_pc client_start, client_end;
# if defined(STATIC_LIBRARY) && defined(LINUX)
// For DR under static+linux we know that the client and DR core
// code are built into the app itself. To avoid various edge cases
// in finding the "library" bounds, delegate this boundary discovery
// to the dll bounds functions. xref i#3387.
client_start = get_dynamorio_dll_start();
client_end = get_dynamorio_dll_end();
ASSERT(client_start <= (app_pc)uses_dr_version &&
(app_pc)uses_dr_version < client_end);
# else
DEBUG_DECLARE(bool ok =)
shared_library_bounds(client_lib, (byte *)uses_dr_version, NULL,
&client_start, &client_end);
ASSERT(ok);
# endif
client_libs[idx].start = client_start;
client_libs[idx].end = client_end;
LOG(GLOBAL, LOG_INTERP, 1, "loaded %s at " PFX "-" PFX "\n", path,
client_libs[idx].start, client_libs[idx].end);
# ifdef X64
/* Now that we map the client within the constraints, this request
* should always succeed.
*/
if (DYNAMO_OPTION(reachable_client)) {
request_region_be_heap_reachable(client_libs[idx].start,
client_libs[idx].end -
client_libs[idx].start);
}
# endif
strncpy(client_libs[idx].path, path,
BUFFER_SIZE_ELEMENTS(client_libs[idx].path));
NULL_TERMINATE_BUFFER(client_libs[idx].path);
if (options != NULL) {
strncpy(client_libs[idx].options, options,
BUFFER_SIZE_ELEMENTS(client_libs[idx].options));
NULL_TERMINATE_BUFFER(client_libs[idx].options);
}
# ifdef X86
bool *client_avx512_code_in_use = (bool *)lookup_library_routine(
client_lib, DR_CLIENT_AVX512_CODE_IN_USE_NAME);
if (client_avx512_code_in_use != NULL) {
if (*client_avx512_code_in_use)
d_r_set_client_avx512_code_in_use();
}
# endif
/* We'll look up dr_client_main and call it in instrument_init */
}
}
}
void
instrument_load_client_libs(void)
{
if (CLIENTS_EXIST()) {
char buf[MAX_LIST_OPTION_LENGTH];
char *path;
string_option_read_lock();
strncpy(buf, INTERNAL_OPTION(client_lib), BUFFER_SIZE_ELEMENTS(buf));
string_option_read_unlock();
NULL_TERMINATE_BUFFER(buf);
/* We're expecting path;ID;options triples */
path = buf;
do {
char *id = NULL;
char *options = NULL;
char *next_path = NULL;
id = strstr(path, ";");
if (id != NULL) {
id[0] = '\0';
id++;
options = strstr(id, ";");
if (options != NULL) {
options[0] = '\0';
options++;
next_path = strstr(options, ";");
if (next_path != NULL) {
next_path[0] = '\0';
next_path++;
}
}
}
# ifdef STATIC_LIBRARY
/* We ignore client library paths and allow client code anywhere in the app.
* We have a check in load_shared_library() to avoid loading
* a 2nd copy of the app.
* We do support passing client ID and options via the first -client_lib.
*/
add_client_lib(get_application_name(), id == NULL ? "0" : id,
options == NULL ? "" : options);
break;
# endif
add_client_lib(path, id, options);
path = next_path;
} while (path != NULL);
}
}
static void
init_client_aux_libs(void)
{
if (client_aux_libs == NULL) {
VMVECTOR_ALLOC_VECTOR(client_aux_libs, GLOBAL_DCONTEXT, VECTOR_SHARED,
client_aux_libs);
}
}
void
instrument_init(void)
{
size_t i;
init_client_aux_libs();
# ifdef X86
if (IF_WINDOWS_ELSE(!dr_earliest_injected, !DYNAMO_OPTION(early_inject))) {
/* A client that had been compiled with AVX-512 may clobber an application's
* state. AVX-512 context switching will not be lazy in this case.
*/
if (d_r_is_client_avx512_code_in_use())
d_r_set_avx512_code_in_use(true);
}
# endif
if (num_client_libs > 0) {
/* We no longer distinguish in-DR vs in-client crashes, as many crashes in
* the DR lib are really client bugs.
* We expect most end-user tools to call dr_set_client_name() so we
* have generic defaults here:
*/
set_exception_strings("Tool", "your tool's issue tracker");
}
/* Iterate over the client libs and call each init routine */
for (i = 0; i < num_client_libs; i++) {
void (*init)(client_id_t, int, const char **) =
(void (*)(client_id_t, int, const char **))(
lookup_library_routine(client_libs[i].lib, INSTRUMENT_INIT_NAME));
void (*legacy)(client_id_t) = (void (*)(client_id_t))(
lookup_library_routine(client_libs[i].lib, INSTRUMENT_INIT_NAME_LEGACY));
/* we can't do this in instrument_load_client_libs() b/c vmheap
* is not set up at that point
*/
all_memory_areas_lock();
update_all_memory_areas(client_libs[i].start, client_libs[i].end,
/* FIXME: need to walk the sections: but may be
* better to obfuscate from clients anyway.
* We can't set as MEMPROT_NONE as that leads to
* bugs if the app wants to interpret part of
* its code section (xref PR 504629).
*/
MEMPROT_READ, DR_MEMTYPE_IMAGE);
all_memory_areas_unlock();
/* i#1736: parse the options up front */
parse_option_array(client_libs[i].id, client_libs[i].options,
&client_libs[i].argc, &client_libs[i].argv, MAX_OPTION_LENGTH);
# ifdef STATIC_LIBRARY
/* We support the app having client code anywhere, so there does not
* have to be an init routine that we call. This means the app
* may have to iterate modules on its own.
*/
# else
/* Since the user has to register all other events, it
* doesn't make sense to provide the -client_lib
* option for a module that doesn't export an init routine.
*/
CLIENT_ASSERT(init != NULL || legacy != NULL,
"client does not export a dr_client_main or dr_init routine");
# endif
if (init != NULL)
(*init)(client_libs[i].id, client_libs[i].argc, client_libs[i].argv);
else if (legacy != NULL)
(*legacy)(client_libs[i].id);
}
/* We now initialize the 1st thread before coming here, so we can
* hand the client a dcontext; so we need to specially generate
* the thread init event now. An alternative is to have
* dr_get_global_drcontext(), but that's extra complexity for no
* real reason.
* We raise the thread init event prior to the module load events
* so the client can access a dcontext in module load events (i#1339).
*/
if (thread_init_callbacks.num > 0) {
instrument_thread_init(get_thread_private_dcontext(), false, false);
}
/* If the client just registered the module-load event, let's
* assume it wants to be informed of *all* modules and tell it
* which modules are already loaded. If the client registers the
* event later, it will need to use the module iterator routines
* to retrieve currently loaded modules. We use the dr_module_iterator
* exposed to the client to avoid locking issues.
*/
if (module_load_callbacks.num > 0) {
dr_module_iterator_t *mi = dr_module_iterator_start();
while (dr_module_iterator_hasnext(mi)) {
module_data_t *data = dr_module_iterator_next(mi);
instrument_module_load(data, true /*already loaded*/);
/* XXX; more efficient to set this flag during dr_module_iterator_start */
os_module_set_flag(data->start, MODULE_LOAD_EVENT);
dr_free_module_data(data);
}
dr_module_iterator_stop(mi);
}
}
static void
free_callback_list(callback_list_t *vec)
{
if (vec->callbacks != NULL) {
HEAP_ARRAY_FREE(GLOBAL_DCONTEXT, vec->callbacks, callback_t, vec->size,
ACCT_OTHER, UNPROTECTED);
vec->callbacks = NULL;
}
vec->size = 0;
vec->num = 0;
}
static void
free_all_callback_lists()
{
free_callback_list(&exit_callbacks);
free_callback_list(&thread_init_callbacks);
free_callback_list(&thread_exit_callbacks);
# ifdef UNIX
free_callback_list(&fork_init_callbacks);
# endif
free_callback_list(&bb_callbacks);
free_callback_list(&trace_callbacks);
# ifdef CUSTOM_TRACES
free_callback_list(&end_trace_callbacks);
# endif
free_callback_list(&fragdel_callbacks);
free_callback_list(&restore_state_callbacks);
free_callback_list(&restore_state_ex_callbacks);
free_callback_list(&module_load_callbacks);
free_callback_list(&module_unload_callbacks);
free_callback_list(&filter_syscall_callbacks);
free_callback_list(&pre_syscall_callbacks);
free_callback_list(&post_syscall_callbacks);
free_callback_list(&kernel_xfer_callbacks);
# ifdef WINDOWS
free_callback_list(&exception_callbacks);
# else
free_callback_list(&signal_callbacks);
# endif
# ifdef PROGRAM_SHEPHERDING
free_callback_list(&security_violation_callbacks);
# endif
free_callback_list(&persist_ro_size_callbacks);
free_callback_list(&persist_ro_callbacks);
free_callback_list(&resurrect_ro_callbacks);
free_callback_list(&persist_rx_size_callbacks);
free_callback_list(&persist_rx_callbacks);
free_callback_list(&resurrect_rx_callbacks);
free_callback_list(&persist_rw_size_callbacks);
free_callback_list(&persist_rw_callbacks);
free_callback_list(&resurrect_rw_callbacks);
free_callback_list(&persist_patch_callbacks);
}
void
instrument_exit_post_sideline(void)
{
# if defined(WINDOWS) || defined(CLIENT_SIDELINE)
DELETE_LOCK(client_thread_count_lock);
# endif
}
void
instrument_exit(void)
{
/* Note - currently own initexit lock when this is called (see PR 227619). */
/* support dr_get_mcontext() from the exit event */
if (!standalone_library)
get_thread_private_dcontext()->client_data->mcontext_in_dcontext = true;
call_all(exit_callbacks, int (*)(),
/* It seems the compiler is confused if we pass no var args
* to the call_all macro. Bogus NULL arg */
NULL);
if (IF_DEBUG_ELSE(true, doing_detach)) {
/* Unload all client libs and free any allocated storage */
size_t i;
for (i = 0; i < num_client_libs; i++) {
free_callback_list(&client_libs[i].nudge_callbacks);
unload_shared_library(client_libs[i].lib);
if (client_libs[i].argv != NULL)
free_option_array(client_libs[i].argc, client_libs[i].argv);
}
free_all_callback_lists();
}
vmvector_delete_vector(GLOBAL_DCONTEXT, client_aux_libs);
client_aux_libs = NULL;
num_client_libs = 0;
# ifdef WINDOWS
DELETE_LOCK(client_aux_lib64_lock);
# endif
DELETE_READWRITE_LOCK(callback_registration_lock);
}
bool
is_in_client_lib(app_pc addr)
{
/* NOTE: we use this routine for detecting exceptions in
* clients. If we add a callback on that event we'll have to be
* sure to deliver it only to the right client.
*/
size_t i;
for (i = 0; i < num_client_libs; i++) {
if ((addr >= (app_pc)client_libs[i].start) && (addr < client_libs[i].end)) {
return true;
}
}
if (client_aux_libs != NULL && vmvector_overlap(client_aux_libs, addr, addr + 1))
return true;
return false;
}
bool
get_client_bounds(client_id_t client_id, app_pc *start /*OUT*/, app_pc *end /*OUT*/)
{
if (client_id >= num_client_libs)
return false;
if (start != NULL)
*start = (app_pc)client_libs[client_id].start;
if (end != NULL)
*end = (app_pc)client_libs[client_id].end;
return true;
}
const char *
get_client_path_from_addr(app_pc addr)
{
size_t i;
for (i = 0; i < num_client_libs; i++) {
if ((addr >= (app_pc)client_libs[i].start) && (addr < client_libs[i].end)) {
return client_libs[i].path;
}
}
return "";
}
bool
is_valid_client_id(client_id_t id)
{
size_t i;
for (i = 0; i < num_client_libs; i++) {
if (client_libs[i].id == id) {
return true;
}
}
return false;
}
void
dr_register_exit_event(void (*func)(void))
{
add_callback(&exit_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_exit_event(void (*func)(void))
{
return remove_callback(&exit_callbacks, (void (*)(void))func, true);
}
void dr_register_bb_event(dr_emit_flags_t (*func)(void *drcontext, void *tag,
instrlist_t *bb, bool for_trace,
bool translating))
{
if (!INTERNAL_OPTION(code_api)) {
CLIENT_ASSERT(false, "asking for bb event when code_api is disabled");
return;
}
add_callback(&bb_callbacks, (void (*)(void))func, true);
}
bool dr_unregister_bb_event(dr_emit_flags_t (*func)(void *drcontext, void *tag,
instrlist_t *bb, bool for_trace,
bool translating))
{
return remove_callback(&bb_callbacks, (void (*)(void))func, true);
}
void dr_register_trace_event(dr_emit_flags_t (*func)(void *drcontext, void *tag,
instrlist_t *trace,
bool translating))
{
if (!INTERNAL_OPTION(code_api)) {
CLIENT_ASSERT(false, "asking for trace event when code_api is disabled");
return;
}
add_callback(&trace_callbacks, (void (*)(void))func, true);
}
bool dr_unregister_trace_event(dr_emit_flags_t (*func)(void *drcontext, void *tag,
instrlist_t *trace,
bool translating))
{
return remove_callback(&trace_callbacks, (void (*)(void))func, true);
}
# ifdef CUSTOM_TRACES
void dr_register_end_trace_event(dr_custom_trace_action_t (*func)(void *drcontext,
void *tag,
void *next_tag))
{
if (!INTERNAL_OPTION(code_api)) {
CLIENT_ASSERT(false, "asking for end-trace event when code_api is disabled");
return;
}
add_callback(&end_trace_callbacks, (void (*)(void))func, true);
}
bool dr_unregister_end_trace_event(dr_custom_trace_action_t (*func)(void *drcontext,
void *tag,
void *next_tag))
{
return remove_callback(&end_trace_callbacks, (void (*)(void))func, true);
}
# endif
void
dr_register_delete_event(void (*func)(void *drcontext, void *tag))
{
if (!INTERNAL_OPTION(code_api)) {
CLIENT_ASSERT(false, "asking for delete event when code_api is disabled");
return;
}
add_callback(&fragdel_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_delete_event(void (*func)(void *drcontext, void *tag))
{
return remove_callback(&fragdel_callbacks, (void (*)(void))func, true);
}
void
dr_register_restore_state_event(void (*func)(void *drcontext, void *tag,
dr_mcontext_t *mcontext, bool restore_memory,
bool app_code_consistent))
{
if (!INTERNAL_OPTION(code_api)) {
CLIENT_ASSERT(false, "asking for restore state event when code_api is disabled");
return;
}
add_callback(&restore_state_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_restore_state_event(void (*func)(void *drcontext, void *tag,
dr_mcontext_t *mcontext,
bool restore_memory,
bool app_code_consistent))
{
return remove_callback(&restore_state_callbacks, (void (*)(void))func, true);
}
void
dr_register_restore_state_ex_event(bool (*func)(void *drcontext, bool restore_memory,
dr_restore_state_info_t *info))
{
if (!INTERNAL_OPTION(code_api)) {
CLIENT_ASSERT(false, "asking for restore_state_ex event when code_api disabled");
return;
}
add_callback(&restore_state_ex_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_restore_state_ex_event(bool (*func)(void *drcontext, bool restore_memory,
dr_restore_state_info_t *info))
{
return remove_callback(&restore_state_ex_callbacks, (void (*)(void))func, true);
}
void
dr_register_thread_init_event(void (*func)(void *drcontext))
{
add_callback(&thread_init_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_thread_init_event(void (*func)(void *drcontext))
{
return remove_callback(&thread_init_callbacks, (void (*)(void))func, true);
}
void
dr_register_thread_exit_event(void (*func)(void *drcontext))
{
add_callback(&thread_exit_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_thread_exit_event(void (*func)(void *drcontext))
{
return remove_callback(&thread_exit_callbacks, (void (*)(void))func, true);
}
# ifdef UNIX
void
dr_register_fork_init_event(void (*func)(void *drcontext))
{
add_callback(&fork_init_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_fork_init_event(void (*func)(void *drcontext))
{
return remove_callback(&fork_init_callbacks, (void (*)(void))func, true);
}
# endif
void
dr_register_module_load_event(void (*func)(void *drcontext, const module_data_t *info,
bool loaded))
{
add_callback(&module_load_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_module_load_event(void (*func)(void *drcontext, const module_data_t *info,
bool loaded))
{
return remove_callback(&module_load_callbacks, (void (*)(void))func, true);
}
void
dr_register_module_unload_event(void (*func)(void *drcontext, const module_data_t *info))
{
add_callback(&module_unload_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_module_unload_event(void (*func)(void *drcontext,
const module_data_t *info))
{
return remove_callback(&module_unload_callbacks, (void (*)(void))func, true);
}
# ifdef WINDOWS
void
dr_register_exception_event(bool (*func)(void *drcontext, dr_exception_t *excpt))
{
add_callback(&exception_callbacks, (bool (*)(void))func, true);
}
bool
dr_unregister_exception_event(bool (*func)(void *drcontext, dr_exception_t *excpt))
{
return remove_callback(&exception_callbacks, (bool (*)(void))func, true);
}
# else
void dr_register_signal_event(dr_signal_action_t (*func)(void *drcontext,
dr_siginfo_t *siginfo))
{
add_callback(&signal_callbacks, (void (*)(void))func, true);
}
bool dr_unregister_signal_event(dr_signal_action_t (*func)(void *drcontext,
dr_siginfo_t *siginfo))
{
return remove_callback(&signal_callbacks, (void (*)(void))func, true);
}
# endif /* WINDOWS */
void
dr_register_filter_syscall_event(bool (*func)(void *drcontext, int sysnum))
{
add_callback(&filter_syscall_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_filter_syscall_event(bool (*func)(void *drcontext, int sysnum))
{
return remove_callback(&filter_syscall_callbacks, (void (*)(void))func, true);
}
void
dr_register_pre_syscall_event(bool (*func)(void *drcontext, int sysnum))
{
add_callback(&pre_syscall_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_pre_syscall_event(bool (*func)(void *drcontext, int sysnum))
{
return remove_callback(&pre_syscall_callbacks, (void (*)(void))func, true);
}
void
dr_register_post_syscall_event(void (*func)(void *drcontext, int sysnum))
{
add_callback(&post_syscall_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_post_syscall_event(void (*func)(void *drcontext, int sysnum))
{
return remove_callback(&post_syscall_callbacks, (void (*)(void))func, true);
}
void
dr_register_kernel_xfer_event(void (*func)(void *drcontext,
const dr_kernel_xfer_info_t *info))
{
add_callback(&kernel_xfer_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_kernel_xfer_event(void (*func)(void *drcontext,
const dr_kernel_xfer_info_t *info))
{
return remove_callback(&kernel_xfer_callbacks, (void (*)(void))func, true);
}
# ifdef PROGRAM_SHEPHERDING
void
dr_register_security_event(void (*func)(void *drcontext, void *source_tag,
app_pc source_pc, app_pc target_pc,
dr_security_violation_type_t violation,
dr_mcontext_t *mcontext,
dr_security_violation_action_t *action))
{
add_callback(&security_violation_callbacks, (void (*)(void))func, true);
}
bool
dr_unregister_security_event(void (*func)(void *drcontext, void *source_tag,
app_pc source_pc, app_pc target_pc,
dr_security_violation_type_t violation,
dr_mcontext_t *mcontext,
dr_security_violation_action_t *action))
{
return remove_callback(&security_violation_callbacks, (void (*)(void))func, true);
}
# endif
void
dr_register_nudge_event(void (*func)(void *drcontext, uint64 argument), client_id_t id)
{
size_t i;
for (i = 0; i < num_client_libs; i++) {
if (client_libs[i].id == id) {
add_callback(&client_libs[i].nudge_callbacks, (void (*)(void))func,
/* the nudge callback list is stored on the heap, so
* we don't need to unprotect the .data section when
* we update the list */
false);
return;
}
}
CLIENT_ASSERT(false, "dr_register_nudge_event: invalid client ID");
}
bool
dr_unregister_nudge_event(void (*func)(void *drcontext, uint64 argument), client_id_t id)
{
size_t i;
for (i = 0; i < num_client_libs; i++) {
if (client_libs[i].id == id) {
return remove_callback(&client_libs[i].nudge_callbacks, (void (*)(void))func,
/* the nudge callback list is stored on the heap, so
* we don't need to unprotect the .data section when
* we update the list */
false);
}
}
CLIENT_ASSERT(false, "dr_unregister_nudge_event: invalid client ID");
return false;
}
dr_config_status_t
dr_nudge_client_ex(process_id_t process_id, client_id_t client_id, uint64 argument,
uint timeout_ms)
{
if (process_id == get_process_id()) {
size_t i;
# ifdef WINDOWS
pre_second_thread();
# endif
for (i = 0; i < num_client_libs; i++) {
if (client_libs[i].id == client_id) {
if (client_libs[i].nudge_callbacks.num == 0) {
CLIENT_ASSERT(false, "dr_nudge_client: no nudge handler registered");
return false;
}
return nudge_internal(process_id, NUDGE_GENERIC(client), argument,
client_id, timeout_ms);
}
}
return false;
} else {
return nudge_internal(process_id, NUDGE_GENERIC(client), argument, client_id,
timeout_ms);
}
}
bool
dr_nudge_client(client_id_t client_id, uint64 argument)
{
return dr_nudge_client_ex(get_process_id(), client_id, argument, 0) == DR_SUCCESS;
}
# ifdef WINDOWS
DR_API
bool
dr_is_nudge_thread(void *drcontext)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "invalid parameter to dr_is_nudge_thread");
return dcontext->nudge_target != NULL;
}
# endif
void
instrument_client_thread_init(dcontext_t *dcontext, bool client_thread)
{
if (dcontext->client_data == NULL) {
dcontext->client_data =
HEAP_TYPE_ALLOC(dcontext, client_data_t, ACCT_OTHER, UNPROTECTED);
memset(dcontext->client_data, 0x0, sizeof(client_data_t));
# ifdef CLIENT_SIDELINE
ASSIGN_INIT_LOCK_FREE(dcontext->client_data->sideline_mutex, sideline_mutex);
# endif
CLIENT_ASSERT(dynamo_initialized || thread_init_callbacks.num == 0 ||
client_thread,
"1st call to instrument_thread_init should have no cbs");
}
# ifdef CLIENT_SIDELINE
if (client_thread) {
ATOMIC_INC(int, num_client_sideline_threads);
/* We don't call dynamo_thread_not_under_dynamo() b/c we want itimers. */
dcontext->thread_record->under_dynamo_control = false;
dcontext->client_data->is_client_thread = true;
dcontext->client_data->suspendable = true;
}
# endif /* CLIENT_SIDELINE */
}
void
instrument_thread_init(dcontext_t *dcontext, bool client_thread, bool valid_mc)
{
/* Note that we're called twice for the initial thread: once prior
* to instrument_init() (PR 216936) to set up the dcontext client
* field (at which point there should be no callbacks since client
* has not had a chance to register any) (now split out, but both
* routines are called prior to instrument_init()), and once after
* instrument_init() to call the client event.
*/
# if defined(CLIENT_INTERFACE) && defined(WINDOWS)
bool swap_peb = false;
# endif
if (client_thread) {
/* no init event */
return;
}
# if defined(CLIENT_INTERFACE) && defined(WINDOWS)
/* i#996: we might be in app's state.
* It is simpler to check and swap here than earlier on thread init paths.
*/
if (dr_using_app_state(dcontext)) {
swap_peb_pointer(dcontext, true /*to priv*/);
swap_peb = true;
}
# endif
/* i#117/PR 395156: support dr_get_mcontext() from the thread init event */
if (valid_mc)
dcontext->client_data->mcontext_in_dcontext = true;
call_all(thread_init_callbacks, int (*)(void *), (void *)dcontext);
if (valid_mc)
dcontext->client_data->mcontext_in_dcontext = false;
# if defined(CLIENT_INTERFACE) && defined(WINDOWS)
if (swap_peb)
swap_peb_pointer(dcontext, false /*to app*/);
# endif
}
# ifdef UNIX
void
instrument_fork_init(dcontext_t *dcontext)
{
call_all(fork_init_callbacks, int (*)(void *), (void *)dcontext);
}
# endif
/* PR 536058: split the exit event from thread cleanup, to provide a
* dcontext in the process exit event
*/
void
instrument_thread_exit_event(dcontext_t *dcontext)
{
# ifdef CLIENT_SIDELINE
if (IS_CLIENT_THREAD(dcontext)
/* if nudge thread calls dr_exit_process() it will be marked as a client
* thread: rule it out here so we properly clean it up
*/
IF_WINDOWS(&&dcontext->nudge_target == NULL)) {
ATOMIC_DEC(int, num_client_sideline_threads);
/* no exit event */
return;
}
# endif
/* i#1394: best-effort to try to avoid crashing thread exit events
* where thread init was never called.
*/
if (!dynamo_initialized)
return;
/* support dr_get_mcontext() from the exit event */
dcontext->client_data->mcontext_in_dcontext = true;
/* Note - currently own initexit lock when this is called (see PR 227619). */
call_all(thread_exit_callbacks, int (*)(void *), (void *)dcontext);
}
void
instrument_thread_exit(dcontext_t *dcontext)
{
# ifdef DEBUG
client_todo_list_t *todo;
client_flush_req_t *flush;
# endif
# ifdef DEBUG
/* PR 470957: avoid racy crashes by not freeing in release build */
# ifdef CLIENT_SIDELINE
DELETE_LOCK(dcontext->client_data->sideline_mutex);
# endif
/* could be heap space allocated for the todo list */
todo = dcontext->client_data->to_do;
while (todo != NULL) {
client_todo_list_t *next_todo = todo->next;
if (todo->ilist != NULL) {
instrlist_clear_and_destroy(dcontext, todo->ilist);
}
HEAP_TYPE_FREE(dcontext, todo, client_todo_list_t, ACCT_CLIENT, UNPROTECTED);
todo = next_todo;
}
/* could be heap space allocated for the flush list */
flush = dcontext->client_data->flush_list;
while (flush != NULL) {
client_flush_req_t *next_flush = flush->next;
HEAP_TYPE_FREE(dcontext, flush, client_flush_req_t, ACCT_CLIENT, UNPROTECTED);
flush = next_flush;
}
HEAP_TYPE_FREE(dcontext, dcontext->client_data, client_data_t, ACCT_OTHER,
UNPROTECTED);
dcontext->client_data = NULL; /* for mutex_wait_contended_lock() */
dcontext->is_client_thread_exiting = true; /* for is_using_app_peb() */
# endif /* DEBUG */
}
bool
dr_bb_hook_exists(void)
{
return (bb_callbacks.num > 0);
}
bool
dr_trace_hook_exists(void)
{
return (trace_callbacks.num > 0);
}
bool
dr_fragment_deleted_hook_exists(void)
{
return (fragdel_callbacks.num > 0);
}
bool
dr_end_trace_hook_exists(void)
{
return (end_trace_callbacks.num > 0);
}
bool
dr_thread_exit_hook_exists(void)
{
return (thread_exit_callbacks.num > 0);
}
bool
dr_exit_hook_exists(void)
{
return (exit_callbacks.num > 0);
}
bool
dr_xl8_hook_exists(void)
{
return (restore_state_callbacks.num > 0 || restore_state_ex_callbacks.num > 0);
}
#endif /* CLIENT_INTERFACE */
/* needed outside of CLIENT_INTERFACE for simpler USE_BB_BUILDING_LOCK_STEADY_STATE() */
bool
dr_modload_hook_exists(void)
{
/* We do not support (as documented in the module event doxygen)
* the client changing this during bb building, as that will mess
* up USE_BB_BUILDING_LOCK_STEADY_STATE().
*/
return IF_CLIENT_INTERFACE_ELSE(module_load_callbacks.num > 0, false);
}
#ifdef CLIENT_INTERFACE
bool
hide_tag_from_client(app_pc tag)
{
# ifdef WINDOWS
/* Case 10009: Basic blocks that consist of a single jump into the
* interception buffer should be obscured from clients. Clients
* will see the displaced code, so we'll provide the address of this
* block if the client asks for the address of the displaced code.
*
* Note that we assume the jump is the first instruction in the
* BB for any blocks that jump to the interception buffer.
*/
if (is_intercepted_app_pc(tag, NULL) ||
/* Displaced app code is now in the landing pad, so skip the
* jump from the interception buffer to the landing pad
*/
is_in_interception_buffer(tag) ||
/* Landing pads that exist between hook points and the trampolines
* shouldn't be seen by the client too. PR 250294.
*/
is_on_interception_initial_route(tag) ||
/* PR 219351: if we lose control on a callback and get it back on
* one of our syscall trampolines, we'll appear at the jmp out of
* the interception buffer to the int/sysenter instruction. The
* problem is that our syscall trampolines, unlike our other
* intercepted code, are hooked earlier than the real action point
* and we have displaced app code at the start of the interception
* buffer: we hook at the wrapper entrance and return w/ a jmp to
* the sysenter/int instr. When creating bbs at the start we hack
* it to make it look like there is no hook. But on retaking control
* we end up w/ this jmp out that won't be solved w/ our normal
* mechanism for other hook jmp-outs: so we just suppress and the
* client next sees the post-syscall bb. It already saw a gap.
*/
is_syscall_trampoline(tag, NULL))
return true;
# endif
return false;
}
# ifdef DEBUG
/* PR 214962: client must set translation fields */
static void
check_ilist_translations(instrlist_t *ilist)
{
/* Ensure client set the translation field for all non-meta
* instrs, even if it didn't return DR_EMIT_STORE_TRANSLATIONS
* (since we may decide ourselves to store)
*/
instr_t *in;
for (in = instrlist_first(ilist); in != NULL; in = instr_get_next(in)) {
if (!instr_opcode_valid(in)) {
CLIENT_ASSERT(INTERNAL_OPTION(fast_client_decode), "level 0 instr found");
} else if (instr_is_app(in)) {
DOLOG(LOG_INTERP, 1, {
if (instr_get_translation(in) == NULL) {
d_r_loginst(get_thread_private_dcontext(), 1, in,
"translation is NULL");
}
});
CLIENT_ASSERT(instr_get_translation(in) != NULL,
"translation field must be set for every app instruction");
} else {
/* The meta instr could indeed not affect app state, but
* better I think to assert and make them put in an
* empty restore event callback in that case. */
DOLOG(LOG_INTERP, 1, {
if (instr_get_translation(in) != NULL && !instr_is_our_mangling(in) &&
!dr_xl8_hook_exists()) {
d_r_loginst(get_thread_private_dcontext(), 1, in,
"translation != NULL");
}
});
CLIENT_ASSERT(instr_get_translation(in) == NULL ||
instr_is_our_mangling(in) || dr_xl8_hook_exists(),
/* FIXME: if multiple clients, we need to check that this
* particular client has the callback: but we have
* no way to do that other than looking at library
* bounds...punting for now */
"a meta instr should not have its translation field "
"set without also having a restore_state callback");
}
}
}
# endif
/* Returns true if the bb hook is called */
bool
instrument_basic_block(dcontext_t *dcontext, app_pc tag, instrlist_t *bb, bool for_trace,
bool translating, dr_emit_flags_t *emitflags)
{
dr_emit_flags_t ret = DR_EMIT_DEFAULT;
/* return false if no BB hooks are registered */
if (bb_callbacks.num == 0)
return false;
if (hide_tag_from_client(tag)) {
LOG(THREAD, LOG_INTERP, 3, "hiding tag " PFX " from client\n", tag);
return false;
}
/* do not expand or up-decode the instrlist, client gets to choose
* whether and how to do that
*/
# ifdef DEBUG
LOG(THREAD, LOG_INTERP, 3, "\ninstrument_basic_block ******************\n");
LOG(THREAD, LOG_INTERP, 3, "\nbefore instrumentation:\n");
if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_INTERP) != 0)
instrlist_disassemble(dcontext, tag, bb, THREAD);
# endif
/* i#117/PR 395156: allow dr_[gs]et_mcontext where accurate */
if (!translating && !for_trace)
dcontext->client_data->mcontext_in_dcontext = true;
/* Note - currently we are couldbelinking and hold the
* bb_building lock when this is called (see PR 227619).
*/
/* We or together the return values */
call_all_ret(ret, |=, , bb_callbacks,
int (*)(void *, void *, instrlist_t *, bool, bool), (void *)dcontext,
(void *)tag, bb, for_trace, translating);
if (emitflags != NULL)
*emitflags = ret;
DOCHECK(1, { check_ilist_translations(bb); });
dcontext->client_data->mcontext_in_dcontext = false;
if (IF_DEBUG_ELSE(for_trace, false)) {
CLIENT_ASSERT(instrlist_get_return_target(bb) == NULL &&
instrlist_get_fall_through_target(bb) == NULL,
"instrlist_set_return/fall_through_target"
" cannot be used on traces");
}
# ifdef DEBUG
LOG(THREAD, LOG_INTERP, 3, "\nafter instrumentation:\n");
if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_INTERP) != 0)
instrlist_disassemble(dcontext, tag, bb, THREAD);
# endif
return true;
}
/* Give the user the completely mangled and optimized trace just prior
* to emitting into code cache, user gets final crack at it
*/
dr_emit_flags_t
instrument_trace(dcontext_t *dcontext, app_pc tag, instrlist_t *trace, bool translating)
{
dr_emit_flags_t ret = DR_EMIT_DEFAULT;
# ifdef UNSUPPORTED_API
instr_t *instr;
# endif
if (trace_callbacks.num == 0)
return DR_EMIT_DEFAULT;
/* do not expand or up-decode the instrlist, client gets to choose
* whether and how to do that
*/
# ifdef DEBUG
LOG(THREAD, LOG_INTERP, 3, "\ninstrument_trace ******************\n");
LOG(THREAD, LOG_INTERP, 3, "\nbefore instrumentation:\n");
if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_INTERP) != 0)
instrlist_disassemble(dcontext, tag, trace, THREAD);
# endif
/* We always pass Level 3 instrs to the client, since we no longer
* expose the expansion routines.
*/
# ifdef UNSUPPORTED_API
for (instr = instrlist_first_expanded(dcontext, trace); instr != NULL;
instr = instr_get_next_expanded(dcontext, trace, instr)) {
instr_decode(dcontext, instr);
}
/* ASSUMPTION: all ctis are already at Level 3, so we don't have
* to do a separate pass to fix up intra-list targets like
* instrlist_decode_cti() does
*/
# endif
/* i#117/PR 395156: allow dr_[gs]et_mcontext where accurate */
if (!translating)
dcontext->client_data->mcontext_in_dcontext = true;
/* We or together the return values */
call_all_ret(ret, |=, , trace_callbacks, int (*)(void *, void *, instrlist_t *, bool),
(void *)dcontext, (void *)tag, trace, translating);
DOCHECK(1, { check_ilist_translations(trace); });
CLIENT_ASSERT(instrlist_get_return_target(trace) == NULL &&
instrlist_get_fall_through_target(trace) == NULL,
"instrlist_set_return/fall_through_target"
" cannot be used on traces");
dcontext->client_data->mcontext_in_dcontext = false;
# ifdef DEBUG
LOG(THREAD, LOG_INTERP, 3, "\nafter instrumentation:\n");
if (d_r_stats->loglevel >= 3 && (d_r_stats->logmask & LOG_INTERP) != 0)
instrlist_disassemble(dcontext, tag, trace, THREAD);
# endif
return ret;
}
/* Notify user when a fragment is deleted from the cache
* FIXME PR 242544: how does user know whether this is a shadowed copy or the
* real thing? The user might free memory that shouldn't be freed!
*/
void
instrument_fragment_deleted(dcontext_t *dcontext, app_pc tag, uint flags)
{
if (fragdel_callbacks.num == 0)
return;
# ifdef WINDOWS
/* Case 10009: We don't call the basic block hook for blocks that
* are jumps to the interception buffer, so we'll hide them here
* as well.
*/
if (!TEST(FRAG_IS_TRACE, flags) && hide_tag_from_client(tag))
return;
# endif
/* PR 243008: we don't expose GLOBAL_DCONTEXT, so change to NULL.
* Our comments warn the user about this.
*/
if (dcontext == GLOBAL_DCONTEXT)
dcontext = NULL;
call_all(fragdel_callbacks, int (*)(void *, void *), (void *)dcontext, (void *)tag);
}
bool
instrument_restore_state(dcontext_t *dcontext, bool restore_memory,
dr_restore_state_info_t *info)
{
bool res = true;
/* Support both legacy and extended handlers */
if (restore_state_callbacks.num > 0) {
call_all(restore_state_callbacks,
int (*)(void *, void *, dr_mcontext_t *, bool, bool), (void *)dcontext,
info->fragment_info.tag, info->mcontext, restore_memory,
info->fragment_info.app_code_consistent);
}
if (restore_state_ex_callbacks.num > 0) {
/* i#220/PR 480565: client has option of failing the translation.
* We fail it if any client wants to, short-circuiting in that case.
* This does violate the "priority order" of events where the
* last one is supposed to have final say b/c it won't even
* see the event (xref i#424).
*/
call_all_ret(res, = res &&, , restore_state_ex_callbacks,
int (*)(void *, bool, dr_restore_state_info_t *), (void *)dcontext,
restore_memory, info);
}
CLIENT_ASSERT(!restore_memory || res,
"translation should not fail for restore_memory=true");
return res;
}
# ifdef CUSTOM_TRACES
/* Ask whether to end trace prior to adding next_tag fragment.
* Return values:
* CUSTOM_TRACE_DR_DECIDES = use standard termination criteria
* CUSTOM_TRACE_END_NOW = end trace
* CUSTOM_TRACE_CONTINUE = do not end trace
*/
dr_custom_trace_action_t
instrument_end_trace(dcontext_t *dcontext, app_pc trace_tag, app_pc next_tag)
{
dr_custom_trace_action_t ret = CUSTOM_TRACE_DR_DECIDES;
if (end_trace_callbacks.num == 0)
return ret;
/* Highest priority callback decides how to end the trace (see
* call_all_ret implementation)
*/
call_all_ret(ret, =, , end_trace_callbacks, int (*)(void *, void *, void *),
(void *)dcontext, (void *)trace_tag, (void *)next_tag);
return ret;
}
# endif
static module_data_t *
create_and_initialize_module_data(app_pc start, app_pc end, app_pc entry_point,
uint flags, const module_names_t *names,
const char *full_path
# ifdef WINDOWS
,
version_number_t file_version,
version_number_t product_version, uint checksum,
uint timestamp, size_t mod_size
# else
,
bool contiguous, uint num_segments,
module_segment_t *os_segments,
module_segment_data_t *segments, uint timestamp
# ifdef MACOS
,
uint current_version, uint compatibility_version,
const byte uuid[16]
# endif
# endif
)
{
# ifndef WINDOWS
uint i;
# endif
module_data_t *copy = (module_data_t *)HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, module_data_t,
ACCT_CLIENT, UNPROTECTED);
memset(copy, 0, sizeof(module_data_t));
copy->start = start;
copy->end = end;
copy->entry_point = entry_point;
copy->flags = flags;
if (full_path != NULL)
copy->full_path = dr_strdup(full_path HEAPACCT(ACCT_CLIENT));
if (names->module_name != NULL)
copy->names.module_name = dr_strdup(names->module_name HEAPACCT(ACCT_CLIENT));
if (names->file_name != NULL)
copy->names.file_name = dr_strdup(names->file_name HEAPACCT(ACCT_CLIENT));
# ifdef WINDOWS
if (names->exe_name != NULL)
copy->names.exe_name = dr_strdup(names->exe_name HEAPACCT(ACCT_CLIENT));
if (names->rsrc_name != NULL)
copy->names.rsrc_name = dr_strdup(names->rsrc_name HEAPACCT(ACCT_CLIENT));
copy->file_version = file_version;
copy->product_version = product_version;
copy->checksum = checksum;
copy->timestamp = timestamp;
copy->module_internal_size = mod_size;
# else
copy->contiguous = contiguous;
copy->num_segments = num_segments;
copy->segments = (module_segment_data_t *)HEAP_ARRAY_ALLOC(
GLOBAL_DCONTEXT, module_segment_data_t, num_segments, ACCT_VMAREAS, PROTECTED);
if (os_segments != NULL) {
ASSERT(segments == NULL);
for (i = 0; i < num_segments; i++) {
copy->segments[i].start = os_segments[i].start;
copy->segments[i].end = os_segments[i].end;
copy->segments[i].prot = os_segments[i].prot;
copy->segments[i].offset = os_segments[i].offset;
}
} else {
ASSERT(segments != NULL);
if (segments != NULL) {
memcpy(copy->segments, segments,
num_segments * sizeof(module_segment_data_t));
}
}
copy->timestamp = timestamp;
# ifdef MACOS
copy->current_version = current_version;
copy->compatibility_version = compatibility_version;
memcpy(copy->uuid, uuid, sizeof(copy->uuid));
# endif
# endif
return copy;
}
module_data_t *
copy_module_area_to_module_data(const module_area_t *area)
{
if (area == NULL)
return NULL;
return create_and_initialize_module_data(
area->start, area->end, area->entry_point, 0, &area->names, area->full_path
# ifdef WINDOWS
,
area->os_data.file_version, area->os_data.product_version, area->os_data.checksum,
area->os_data.timestamp, area->os_data.module_internal_size
# else
,
area->os_data.contiguous, area->os_data.num_segments, area->os_data.segments,
NULL, area->os_data.timestamp
# ifdef MACOS
,
area->os_data.current_version, area->os_data.compatibility_version,
area->os_data.uuid
# endif
# endif
);
}
DR_API
/* Makes a copy of a module_data_t for returning to the client. We return a copy so
* we don't have to hold the module areas list lock while in the client (xref PR 225020).
* Note - dr_data is allowed to be NULL. */
module_data_t *
dr_copy_module_data(const module_data_t *data)
{
if (data == NULL)
return NULL;
return create_and_initialize_module_data(
data->start, data->end, data->entry_point, 0, &data->names, data->full_path
# ifdef WINDOWS
,
data->file_version, data->product_version, data->checksum, data->timestamp,
data->module_internal_size
# else
,
data->contiguous, data->num_segments, NULL, data->segments, data->timestamp
# ifdef MACOS
,
data->current_version, data->compatibility_version, data->uuid
# endif
# endif
);
}
DR_API
/* Used to free a module_data_t created by dr_copy_module_data() */
void
dr_free_module_data(module_data_t *data)
{
dcontext_t *dcontext = get_thread_private_dcontext();
if (data == NULL)
return;
if (dcontext != NULL && data == dcontext->client_data->no_delete_mod_data) {
CLIENT_ASSERT(false,
"dr_free_module_data: don\'t free module_data passed to "
"the image load or image unload event callbacks.");
return;
}
# ifdef UNIX
HEAP_ARRAY_FREE(GLOBAL_DCONTEXT, data->segments, module_segment_data_t,
data->num_segments, ACCT_VMAREAS, PROTECTED);
# endif
if (data->full_path != NULL)
dr_strfree(data->full_path HEAPACCT(ACCT_CLIENT));
free_module_names(&data->names HEAPACCT(ACCT_CLIENT));
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, data, module_data_t, ACCT_CLIENT, UNPROTECTED);
}
DR_API
bool
dr_module_contains_addr(const module_data_t *data, app_pc addr)
{
/* XXX: this duplicates module_contains_addr(), but we have two different
* data structures (module_area_t and module_data_t) so it's hard to share.
*/
# ifdef WINDOWS
return (addr >= data->start && addr < data->end);
# else
if (data->contiguous)
return (addr >= data->start && addr < data->end);
else {
uint i;
for (i = 0; i < data->num_segments; i++) {
if (addr >= data->segments[i].start && addr < data->segments[i].end)
return true;
}
}
return false;
# endif
}
/* Looks up module containing pc (assumed to be fully loaded).
* If it exists and its client module load event has not been called, calls it.
*/
void
instrument_module_load_trigger(app_pc pc)
{
if (CLIENTS_EXIST()) {
module_area_t *ma;
module_data_t *client_data = NULL;
os_get_module_info_lock();
ma = module_pc_lookup(pc);
if (ma != NULL && !TEST(MODULE_LOAD_EVENT, ma->flags)) {
/* switch to write lock */
os_get_module_info_unlock();
os_get_module_info_write_lock();
ma = module_pc_lookup(pc);
if (ma != NULL && !TEST(MODULE_LOAD_EVENT, ma->flags)) {
ma->flags |= MODULE_LOAD_EVENT;
client_data = copy_module_area_to_module_data(ma);
os_get_module_info_write_unlock();
instrument_module_load(client_data, true /*i#884: already loaded*/);
dr_free_module_data(client_data);
} else
os_get_module_info_write_unlock();
} else
os_get_module_info_unlock();
}
}
/* Notify user when a module is loaded */
void
instrument_module_load(module_data_t *data, bool previously_loaded)
{
/* Note - during DR initialization this routine is called before we've set up a
* dcontext for the main thread and before we've called instrument_init. It's okay
* since there's no way a callback will be registered and we'll return immediately. */
dcontext_t *dcontext;
if (module_load_callbacks.num == 0)
return;
dcontext = get_thread_private_dcontext();
/* client shouldn't delete this */
dcontext->client_data->no_delete_mod_data = data;
call_all(module_load_callbacks, int (*)(void *, module_data_t *, bool),
(void *)dcontext, data, previously_loaded);
dcontext->client_data->no_delete_mod_data = NULL;
}
/* Notify user when a module is unloaded */
void
instrument_module_unload(module_data_t *data)
{
dcontext_t *dcontext;
if (module_unload_callbacks.num == 0)
return;
dcontext = get_thread_private_dcontext();
/* client shouldn't delete this */
dcontext->client_data->no_delete_mod_data = data;
call_all(module_unload_callbacks, int (*)(void *, module_data_t *), (void *)dcontext,
data);
dcontext->client_data->no_delete_mod_data = NULL;
}
/* returns whether this sysnum should be intercepted */
bool
instrument_filter_syscall(dcontext_t *dcontext, int sysnum)
{
bool ret = false;
/* if client does not filter then we don't intercept anything */
if (filter_syscall_callbacks.num == 0)
return ret;
/* if any client wants to intercept, then we intercept */
call_all_ret(ret, =, || ret, filter_syscall_callbacks, bool (*)(void *, int),
(void *)dcontext, sysnum);
return ret;
}
/* returns whether this syscall should execute */
bool
instrument_pre_syscall(dcontext_t *dcontext, int sysnum)
{
bool exec = true;
dcontext->client_data->in_pre_syscall = true;
/* clear flag from dr_syscall_invoke_another() */
dcontext->client_data->invoke_another_syscall = false;
if (pre_syscall_callbacks.num > 0) {
dr_where_am_i_t old_whereami = dcontext->whereami;
dcontext->whereami = DR_WHERE_SYSCALL_HANDLER;
DODEBUG({
/* Avoid the common mistake of forgetting a filter event. */
CLIENT_ASSERT(filter_syscall_callbacks.num > 0,
"A filter event must be "
"provided when using pre- and post-syscall events");
});
/* Skip syscall if any client wants to skip it, but don't short-circuit,
* as skipping syscalls is usually done when the effect of the syscall
* will be emulated in some other way. The app is typically meant to
* think that the syscall succeeded. Thus, other tool components
* should see the syscall as well (xref i#424).
*/
call_all_ret(exec, =, &&exec, pre_syscall_callbacks, bool (*)(void *, int),
(void *)dcontext, sysnum);
dcontext->whereami = old_whereami;
}
dcontext->client_data->in_pre_syscall = false;
return exec;
}
void
instrument_post_syscall(dcontext_t *dcontext, int sysnum)
{
dr_where_am_i_t old_whereami = dcontext->whereami;
if (post_syscall_callbacks.num == 0)
return;
DODEBUG({
/* Avoid the common mistake of forgetting a filter event. */
CLIENT_ASSERT(filter_syscall_callbacks.num > 0,
"A filter event must be "
"provided when using pre- and post-syscall events");
});
dcontext->whereami = DR_WHERE_SYSCALL_HANDLER;
dcontext->client_data->in_post_syscall = true;
call_all(post_syscall_callbacks, int (*)(void *, int), (void *)dcontext, sysnum);
dcontext->client_data->in_post_syscall = false;
dcontext->whereami = old_whereami;
}
bool
instrument_invoke_another_syscall(dcontext_t *dcontext)
{
return dcontext->client_data->invoke_another_syscall;
}
bool
instrument_kernel_xfer(dcontext_t *dcontext, dr_kernel_xfer_type_t type,
os_cxt_ptr_t source_os_cxt, dr_mcontext_t *source_dmc,
priv_mcontext_t *source_mc, app_pc target_pc, reg_t target_xsp,
os_cxt_ptr_t target_os_cxt, priv_mcontext_t *target_mc, int sig)
{
if (kernel_xfer_callbacks.num == 0) {
return false;
}
dr_kernel_xfer_info_t info;
info.type = type;
info.source_mcontext = NULL;
info.target_pc = target_pc;
info.target_xsp = target_xsp;
info.sig = sig;
dr_mcontext_t dr_mcontext;
dr_mcontext.size = sizeof(dr_mcontext);
dr_mcontext.flags = DR_MC_CONTROL | DR_MC_INTEGER;
if (source_dmc != NULL)
info.source_mcontext = source_dmc;
else if (source_mc != NULL) {
if (priv_mcontext_to_dr_mcontext(&dr_mcontext, source_mc))
info.source_mcontext = &dr_mcontext;
} else if (!is_os_cxt_ptr_null(source_os_cxt)) {
if (os_context_to_mcontext(&dr_mcontext, NULL, source_os_cxt))
info.source_mcontext = &dr_mcontext;
}
/* Our compromise to reduce context copying is to provide the PC and XSP inline,
* and only get more if the user calls dr_get_mcontext(), which we support again
* without any copying if not used by taking in a raw os_context_t.
*/
dcontext->client_data->os_cxt = target_os_cxt;
dcontext->client_data->cur_mc = target_mc;
call_all(kernel_xfer_callbacks, int (*)(void *, const dr_kernel_xfer_info_t *),
(void *)dcontext, &info);
set_os_cxt_ptr_null(&dcontext->client_data->os_cxt);
dcontext->client_data->cur_mc = NULL;
return true;
}
# ifdef WINDOWS
/* Notify user of exceptions. Note: not called for RaiseException */
bool
instrument_exception(dcontext_t *dcontext, dr_exception_t *exception)
{
bool res = true;
/* Ensure that dr_get_mcontext() called from instrument_kernel_xfer() from
* dr_redirect_execution() will get the source context.
* cur_mc will later be clobbered by instrument_kernel_xfer() which is ok:
* the redirect ends the callback calling.
*/
dcontext->client_data->cur_mc = dr_mcontext_as_priv_mcontext(exception->mcontext);
/* We short-circuit if any client wants to "own" the fault and not pass on.
* This does violate the "priority order" of events where the last one is
* supposed to have final say b/c it won't even see the event: but only one
* registrant should own it (xref i#424).
*/
call_all_ret(res, = res &&, , exception_callbacks, bool (*)(void *, dr_exception_t *),
(void *)dcontext, exception);
dcontext->client_data->cur_mc = NULL;
return res;
}
# else
dr_signal_action_t
instrument_signal(dcontext_t *dcontext, dr_siginfo_t *siginfo)
{
dr_signal_action_t ret = DR_SIGNAL_DELIVER;
/* We short-circuit if any client wants to do other than deliver to the app.
* This does violate the "priority order" of events where the last one is
* supposed to have final say b/c it won't even see the event: but only one
* registrant should own the signal (xref i#424).
*/
call_all_ret(ret, = ret == DR_SIGNAL_DELIVER ?, : ret, signal_callbacks,
dr_signal_action_t(*)(void *, dr_siginfo_t *), (void *)dcontext,
siginfo);
return ret;
}
bool
dr_signal_hook_exists(void)
{
return (signal_callbacks.num > 0);
}
# endif /* WINDOWS */
# ifdef PROGRAM_SHEPHERDING
/* Notify user when a security violation is detected */
void
instrument_security_violation(dcontext_t *dcontext, app_pc target_pc,
security_violation_t violation, action_type_t *action)
{
dr_security_violation_type_t dr_violation;
dr_security_violation_action_t dr_action, dr_action_original;
app_pc source_pc = NULL;
fragment_t *last;
dr_mcontext_t dr_mcontext;
dr_mcontext_init(&dr_mcontext);
if (security_violation_callbacks.num == 0)
return;
if (!priv_mcontext_to_dr_mcontext(&dr_mcontext, get_mcontext(dcontext)))
return;
/* FIXME - the source_tag, source_pc, and context can all be incorrect if the
* violation ends up occurring in the middle of a bb we're building. See case
* 7380 which we should fix in interp.c.
*/
/* Obtain the source addr to pass to the client. xref case 285 --
* we're using the more heavy-weight solution 2) here, but that
* should be okay since we already have the overhead of calling
* into the client. */
last = dcontext->last_fragment;
if (!TEST(FRAG_FAKE, last->flags)) {
cache_pc pc = EXIT_CTI_PC(last, dcontext->last_exit);
source_pc = recreate_app_pc(dcontext, pc, last);
}
/* FIXME - set pc field of dr_mcontext_t. We'll probably want it
* for thread start and possibly apc/callback events as well.
*/
switch (violation) {
case STACK_EXECUTION_VIOLATION: dr_violation = DR_RCO_STACK_VIOLATION; break;
case HEAP_EXECUTION_VIOLATION: dr_violation = DR_RCO_HEAP_VIOLATION; break;
case RETURN_TARGET_VIOLATION: dr_violation = DR_RCT_RETURN_VIOLATION; break;
case RETURN_DIRECT_RCT_VIOLATION:
ASSERT(false); /* Not a client fault, should be NOT_REACHED(). */
dr_violation = DR_UNKNOWN_VIOLATION;
break;
case INDIRECT_CALL_RCT_VIOLATION:
dr_violation = DR_RCT_INDIRECT_CALL_VIOLATION;
break;
case INDIRECT_JUMP_RCT_VIOLATION:
dr_violation = DR_RCT_INDIRECT_JUMP_VIOLATION;
break;
default:
ASSERT(false); /* Not a client fault, should be NOT_REACHED(). */
dr_violation = DR_UNKNOWN_VIOLATION;
break;
}
switch (*action) {
case ACTION_TERMINATE_PROCESS: dr_action = DR_VIOLATION_ACTION_KILL_PROCESS; break;
case ACTION_CONTINUE: dr_action = DR_VIOLATION_ACTION_CONTINUE; break;
case ACTION_TERMINATE_THREAD: dr_action = DR_VIOLATION_ACTION_KILL_THREAD; break;
case ACTION_THROW_EXCEPTION: dr_action = DR_VIOLATION_ACTION_THROW_EXCEPTION; break;
default:
ASSERT(false); /* Not a client fault, should be NOT_REACHED(). */
dr_action = DR_VIOLATION_ACTION_CONTINUE;
break;
}
dr_action_original = dr_action;
/* NOTE - last->tag should be valid here (even if the frag is fake since the
* coarse wrappers set the tag). FIXME - for traces we really want the bb tag not
* the trace tag, should get that. Of course the only real reason we pass source
* tag is because we can't always give a valid source_pc. */
/* Note that the last registered function gets the final crack at
* changing the action.
*/
call_all(security_violation_callbacks,
int (*)(void *, void *, app_pc, app_pc, dr_security_violation_type_t,
dr_mcontext_t *, dr_security_violation_action_t *),
(void *)dcontext, last->tag, source_pc, target_pc, dr_violation,
&dr_mcontext, &dr_action);
if (dr_action != dr_action_original) {
switch (dr_action) {
case DR_VIOLATION_ACTION_KILL_PROCESS: *action = ACTION_TERMINATE_PROCESS; break;
case DR_VIOLATION_ACTION_KILL_THREAD: *action = ACTION_TERMINATE_THREAD; break;
case DR_VIOLATION_ACTION_THROW_EXCEPTION: *action = ACTION_THROW_EXCEPTION; break;
case DR_VIOLATION_ACTION_CONTINUE_CHANGED_CONTEXT:
/* FIXME - not safe to implement till case 7380 is fixed. */
CLIENT_ASSERT(false,
"action DR_VIOLATION_ACTION_CONTINUE_CHANGED_CONTEXT "
"not yet supported.");
/* note - no break, fall through */
case DR_VIOLATION_ACTION_CONTINUE: *action = ACTION_CONTINUE; break;
default:
CLIENT_ASSERT(false,
"Security violation event callback returned invalid "
"action value.");
}
}
}
# endif
/* Notify the client of a nudge. */
void
instrument_nudge(dcontext_t *dcontext, client_id_t id, uint64 arg)
{
size_t i;
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
ASSERT(dcontext != NULL && dcontext != GLOBAL_DCONTEXT &&
dcontext == get_thread_private_dcontext());
/* synch_with_all_threads and flush API assume that client nudge threads
* hold no dr locks and are !couldbelinking while in client lib code */
ASSERT_OWN_NO_LOCKS();
ASSERT(!is_couldbelinking(dcontext));
/* find the client the nudge is intended for */
for (i = 0; i < num_client_libs; i++) {
/* until we have nudge-arg support (PR 477454), nudges target the 1st client */
if (IF_VMX86_ELSE(true, client_libs[i].id == id)) {
break;
}
}
if (i == num_client_libs || client_libs[i].nudge_callbacks.num == 0)
return;
# ifdef WINDOWS
/* count the number of nudge events so we can make sure they're
* all finished before exiting
*/
d_r_mutex_lock(&client_thread_count_lock);
if (block_client_nudge_threads) {
/* FIXME - would be nice if there was a way to let the external agent know that
* the nudge event wasn't delivered (but this only happens when the process
* is detaching or exiting). */
d_r_mutex_unlock(&client_thread_count_lock);
return;
}
/* atomic to avoid locking around the dec */
ATOMIC_INC(int, num_client_nudge_threads);
d_r_mutex_unlock(&client_thread_count_lock);
/* We need to mark this as a client controlled thread for synch_with_all_threads
* and otherwise treat it as native. Xref PR 230836 on what to do if this
* thread hits native_exec_syscalls hooks.
* XXX: this requires extra checks for "not a nudge thread" after IS_CLIENT_THREAD
* in get_stack_bounds() and instrument_thread_exit_event(): maybe better
* to have synchall checks do extra checks and have IS_CLIENT_THREAD be
* false for nudge threads at exit time?
*/
dcontext->client_data->is_client_thread = true;
dcontext->thread_record->under_dynamo_control = false;
# else
/* support calling dr_get_mcontext() on this thread. the app
* context should be intact in the current mcontext except
* pc which we set from next_tag.
*/
CLIENT_ASSERT(!dcontext->client_data->mcontext_in_dcontext,
"internal inconsistency in where mcontext is");
dcontext->client_data->mcontext_in_dcontext = true;
/* officially get_mcontext() doesn't always set pc: we do anyway */
get_mcontext(dcontext)->pc = dcontext->next_tag;
# endif
call_all(client_libs[i].nudge_callbacks, int (*)(void *, uint64), (void *)dcontext,
arg);
# ifdef UNIX
dcontext->client_data->mcontext_in_dcontext = false;
# else
dcontext->thread_record->under_dynamo_control = true;
dcontext->client_data->is_client_thread = false;
ATOMIC_DEC(int, num_client_nudge_threads);
# endif
}
int
get_num_client_threads(void)
{
int num = IF_WINDOWS_ELSE(num_client_nudge_threads, 0);
# ifdef CLIENT_SIDELINE
num += num_client_sideline_threads;
# endif
return num;
}
# ifdef WINDOWS
/* wait for all nudges to finish */
void
wait_for_outstanding_nudges()
{
/* block any new nudge threads from starting */
d_r_mutex_lock(&client_thread_count_lock);
SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT);
block_client_nudge_threads = true;
SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT);
DOLOG(1, LOG_TOP, {
if (num_client_nudge_threads > 0) {
LOG(GLOBAL, LOG_TOP, 1,
"Waiting for %d nudges to finish - app is about to kill all threads "
"except the current one.\n",
num_client_nudge_threads);
}
});
/* don't wait if the client requested exit: after all the client might
* have done so from a nudge, and if the client does want to exit it's
* its own problem if it misses nudges (and external nudgers should use
* a finite timeout)
*/
if (client_requested_exit) {
d_r_mutex_unlock(&client_thread_count_lock);
return;
}
while (num_client_nudge_threads > 0) {
/* yield with lock released to allow nudges to finish */
d_r_mutex_unlock(&client_thread_count_lock);
dr_thread_yield();
d_r_mutex_lock(&client_thread_count_lock);
}
d_r_mutex_unlock(&client_thread_count_lock);
}
# endif /* WINDOWS */
/****************************************************************************/
/* EXPORTED ROUTINES */
DR_API
/* Creates a DR context that can be used in a standalone program.
* WARNING: this context cannot be used as the drcontext for a thread
* running under DR control! It is only for standalone programs that
* wish to use DR as a library of disassembly, etc. routines.
*/
void *
dr_standalone_init(void)
{
dcontext_t *dcontext = standalone_init();
return (void *)dcontext;
}
DR_API
void
dr_standalone_exit(void)
{
standalone_exit();
}
DR_API
/* Aborts the process immediately */
void
dr_abort(void)
{
if (TEST(DUMPCORE_DR_ABORT, dynamo_options.dumpcore_mask))
os_dump_core("dr_abort");
os_terminate(NULL, TERMINATE_PROCESS);
}
DR_API
void
dr_abort_with_code(int exit_code)
{
if (TEST(DUMPCORE_DR_ABORT, dynamo_options.dumpcore_mask))
os_dump_core("dr_abort");
os_terminate_with_code(NULL, TERMINATE_PROCESS, exit_code);
}
DR_API
void
dr_exit_process(int exit_code)
{
dcontext_t *dcontext = get_thread_private_dcontext();
SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT);
/* Prevent cleanup from waiting for nudges as this may be called
* from a nudge!
* Also suppress leak asserts, as it's hard to clean up from
* some situations (such as DrMem -crash_at_error).
*/
client_requested_exit = true;
SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT);
# ifdef WINDOWS
if (dcontext != NULL && dcontext->nudge_target != NULL) {
/* we need to free the nudge thread stack which may involved
* switching stacks so we have the nudge thread invoke
* os_terminate for us
*/
nudge_thread_cleanup(dcontext, true /*kill process*/, exit_code);
CLIENT_ASSERT(false, "shouldn't get here");
}
# endif
if (!is_currently_on_dstack(dcontext)
IF_UNIX(&&!is_currently_on_sigaltstack(dcontext))) {
/* if on app stack or sigaltstack, avoid incorrect leak assert at exit */
SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT);
dr_api_exit = true;
SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); /* to keep properly nested */
}
os_terminate_with_code(dcontext, /* dcontext is required */
TERMINATE_CLEANUP | TERMINATE_PROCESS, exit_code);
CLIENT_ASSERT(false, "shouldn't get here");
}
DR_API
bool
dr_create_memory_dump(dr_memory_dump_spec_t *spec)
{
if (spec->size != sizeof(dr_memory_dump_spec_t))
return false;
# ifdef WINDOWS
if (TEST(DR_MEMORY_DUMP_LDMP, spec->flags))
return os_dump_core_live(spec->label, spec->ldmp_path, spec->ldmp_path_size);
# endif
return false;
}
DR_API
/* Returns true if all DynamoRIO caches are thread private. */
bool
dr_using_all_private_caches(void)
{
return !SHARED_FRAGMENTS_ENABLED();
}
DR_API
void
dr_request_synchronized_exit(void)
{
SYSLOG_INTERNAL_WARNING_ONCE("dr_request_synchronized_exit deprecated: "
"use dr_set_process_exit_behavior instead");
}
DR_API
void
dr_set_process_exit_behavior(dr_exit_flags_t flags)
{
if ((!DYNAMO_OPTION(multi_thread_exit) && TEST(DR_EXIT_MULTI_THREAD, flags)) ||
(DYNAMO_OPTION(multi_thread_exit) && !TEST(DR_EXIT_MULTI_THREAD, flags))) {
options_make_writable();
dynamo_options.multi_thread_exit = TEST(DR_EXIT_MULTI_THREAD, flags);
options_restore_readonly();
}
if ((!DYNAMO_OPTION(skip_thread_exit_at_exit) &&
TEST(DR_EXIT_SKIP_THREAD_EXIT, flags)) ||
(DYNAMO_OPTION(skip_thread_exit_at_exit) &&
!TEST(DR_EXIT_SKIP_THREAD_EXIT, flags))) {
options_make_writable();
dynamo_options.skip_thread_exit_at_exit = TEST(DR_EXIT_SKIP_THREAD_EXIT, flags);
options_restore_readonly();
}
}
void
dr_allow_unsafe_static_behavior(void)
{
loader_allow_unsafe_static_behavior();
}
DR_API
/* Returns the option string passed along with a client path via DR's
* -client_lib option.
*/
/* i#1736: we now token-delimit with quotes, but for backward compat we need to
* pass a version w/o quotes for dr_get_options().
*/
const char *
dr_get_options(client_id_t id)
{
size_t i;
for (i = 0; i < num_client_libs; i++) {
if (client_libs[i].id == id) {
/* If we already converted, pass the result */
if (client_libs[i].legacy_options[0] != '\0' ||
client_libs[i].options[0] == '\0')
return client_libs[i].legacy_options;
/* For backward compatibility, we need to remove the token-delimiting
* quotes. We tokenize, and then re-assemble the flat string.
* i#1755: however, for legacy custom frontends that are not re-quoting
* like drrun now is, we need to avoid removing any quotes from the
* original strings. We try to detect this by assuming a frontend will
* either re-quote everything or nothing. Ideally we would check all
* args, but that would require plumbing info from getword() or
* duplicating its functionality: so instead our heuristic is just checking
* the first and last chars.
*/
if (!char_is_quote(client_libs[i].options[0]) ||
/* Emptry string already detected above */
!char_is_quote(
client_libs[i].options[strlen(client_libs[i].options) - 1])) {
/* At least one arg is not quoted => better use original */
snprintf(client_libs[i].legacy_options,
BUFFER_SIZE_ELEMENTS(client_libs[i].legacy_options), "%s",
client_libs[i].options);
} else {
int j;
size_t sofar = 0;
for (j = 1 /*skip client lib*/; j < client_libs[i].argc; j++) {
if (!print_to_buffer(
client_libs[i].legacy_options,
BUFFER_SIZE_ELEMENTS(client_libs[i].legacy_options), &sofar,
"%s%s", (j == 1) ? "" : " ", client_libs[i].argv[j]))
break;
}
}
NULL_TERMINATE_BUFFER(client_libs[i].legacy_options);
return client_libs[i].legacy_options;
}
}
CLIENT_ASSERT(false, "dr_get_options(): invalid client id");
return NULL;
}
DR_API
bool
dr_get_option_array(client_id_t id, int *argc OUT, const char ***argv OUT)
{
size_t i;
for (i = 0; i < num_client_libs; i++) {
if (client_libs[i].id == id) {
*argc = client_libs[i].argc;
*argv = client_libs[i].argv;
return true;
}
}
CLIENT_ASSERT(false, "dr_get_option_array(): invalid client id");
return false;
}
DR_API
/* Returns the path to the client library. Client must pass its ID */
const char *
dr_get_client_path(client_id_t id)
{
size_t i;
for (i = 0; i < num_client_libs; i++) {
if (client_libs[i].id == id) {
return client_libs[i].path;
}
}
CLIENT_ASSERT(false, "dr_get_client_path(): invalid client id");
return NULL;
}
DR_API
byte *
dr_get_client_base(client_id_t id)
{
size_t i;
for (i = 0; i < num_client_libs; i++) {
if (client_libs[i].id == id) {
return client_libs[i].start;
}
}
CLIENT_ASSERT(false, "dr_get_client_base(): invalid client id");
return NULL;
}
DR_API
bool
dr_set_client_name(const char *name, const char *report_URL)
{
/* Although set_exception_strings() accepts NULL, clients should pass real vals. */
if (name == NULL || report_URL == NULL)
return false;
set_exception_strings(name, report_URL);
return true;
}
bool
dr_set_client_version_string(const char *version)
{
if (version == NULL)
return false;
set_display_version(version);
return true;
}
DR_API const char *
dr_get_application_name(void)
{
# ifdef UNIX
return get_application_short_name();
# else
return get_application_short_unqualified_name();
# endif
}
DR_API process_id_t
dr_get_process_id(void)
{
return (process_id_t)get_process_id();
}
# ifdef UNIX
DR_API
process_id_t
dr_get_parent_id(void)
{
return get_parent_id();
}
# endif
# ifdef WINDOWS
DR_API
process_id_t
dr_convert_handle_to_pid(HANDLE process_handle)
{
ASSERT(POINTER_MAX == INVALID_PROCESS_ID);
return process_id_from_handle(process_handle);
}
DR_API
HANDLE
dr_convert_pid_to_handle(process_id_t pid)
{
return process_handle_from_id(pid);
}
DR_API
/**
* Returns information about the version of the operating system.
* Returns whether successful.
*/
bool
dr_get_os_version(dr_os_version_info_t *info)
{
int ver;
uint sp_major, sp_minor, build_number;
const char *release_id, *edition;
get_os_version_ex(&ver, &sp_major, &sp_minor, &build_number, &release_id, &edition);
if (info->size > offsetof(dr_os_version_info_t, version)) {
switch (ver) {
case WINDOWS_VERSION_10_1803: info->version = DR_WINDOWS_VERSION_10_1803; break;
case WINDOWS_VERSION_10_1709: info->version = DR_WINDOWS_VERSION_10_1709; break;
case WINDOWS_VERSION_10_1703: info->version = DR_WINDOWS_VERSION_10_1703; break;
case WINDOWS_VERSION_10_1607: info->version = DR_WINDOWS_VERSION_10_1607; break;
case WINDOWS_VERSION_10_1511: info->version = DR_WINDOWS_VERSION_10_1511; break;
case WINDOWS_VERSION_10: info->version = DR_WINDOWS_VERSION_10; break;
case WINDOWS_VERSION_8_1: info->version = DR_WINDOWS_VERSION_8_1; break;
case WINDOWS_VERSION_8: info->version = DR_WINDOWS_VERSION_8; break;
case WINDOWS_VERSION_7: info->version = DR_WINDOWS_VERSION_7; break;
case WINDOWS_VERSION_VISTA: info->version = DR_WINDOWS_VERSION_VISTA; break;
case WINDOWS_VERSION_2003: info->version = DR_WINDOWS_VERSION_2003; break;
case WINDOWS_VERSION_XP: info->version = DR_WINDOWS_VERSION_XP; break;
case WINDOWS_VERSION_2000: info->version = DR_WINDOWS_VERSION_2000; break;
case WINDOWS_VERSION_NT: info->version = DR_WINDOWS_VERSION_NT; break;
default: CLIENT_ASSERT(false, "unsupported windows version");
};
} else
return false; /* struct too small for any info */
if (info->size > offsetof(dr_os_version_info_t, service_pack_major)) {
info->service_pack_major = sp_major;
if (info->size > offsetof(dr_os_version_info_t, service_pack_minor)) {
info->service_pack_minor = sp_minor;
}
}
if (info->size > offsetof(dr_os_version_info_t, build_number)) {
info->build_number = build_number;
}
if (info->size > offsetof(dr_os_version_info_t, release_id)) {
dr_snprintf(info->release_id, BUFFER_SIZE_ELEMENTS(info->release_id), "%s",
release_id);
NULL_TERMINATE_BUFFER(info->release_id);
}
if (info->size > offsetof(dr_os_version_info_t, edition)) {
dr_snprintf(info->edition, BUFFER_SIZE_ELEMENTS(info->edition), "%s", edition);
NULL_TERMINATE_BUFFER(info->edition);
}
return true;
}
DR_API
bool
dr_is_wow64(void)
{
return is_wow64_process(NT_CURRENT_PROCESS);
}
DR_API
void *
dr_get_app_PEB(void)
{
return get_own_peb();
}
# endif
DR_API
/* Retrieves the current time */
void
dr_get_time(dr_time_t *time)
{
convert_millis_to_date(query_time_millis(), time);
}
DR_API
uint64
dr_get_milliseconds(void)
{
return query_time_millis();
}
DR_API
uint64
dr_get_microseconds(void)
{
return query_time_micros();
}
DR_API
uint
dr_get_random_value(uint max)
{
return (uint)get_random_offset(max);
}
DR_API
void
dr_set_random_seed(uint seed)
{
d_r_set_random_seed(seed);
}
DR_API
uint
dr_get_random_seed(void)
{
return d_r_get_random_seed();
}
/***************************************************************************
* MEMORY ALLOCATION
*/
DR_API
/* Allocates memory from DR's memory pool specific to the
* thread associated with drcontext.
*/
void *
dr_thread_alloc(void *drcontext, size_t size)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
/* For back-compat this is guaranteed-reachable. */
return heap_reachable_alloc(dcontext, size HEAPACCT(ACCT_CLIENT));
}
DR_API
/* Frees thread-specific memory allocated by dr_thread_alloc.
* size must be the same size passed to dr_thread_alloc.
*/
void
dr_thread_free(void *drcontext, void *mem, size_t size)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_thread_free: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT, "dr_thread_free: drcontext is invalid");
heap_reachable_free(dcontext, mem, size HEAPACCT(ACCT_CLIENT));
}
DR_API
/* Allocates memory from DR's global memory pool.
*/
void *
dr_global_alloc(size_t size)
{
/* For back-compat this is guaranteed-reachable. */
return heap_reachable_alloc(GLOBAL_DCONTEXT, size HEAPACCT(ACCT_CLIENT));
}
DR_API
/* Frees memory allocated by dr_global_alloc.
* size must be the same size passed to dr_global_alloc.
*/
void
dr_global_free(void *mem, size_t size)
{
heap_reachable_free(GLOBAL_DCONTEXT, mem, size HEAPACCT(ACCT_CLIENT));
}
DR_API
/* PR 352427: API routine to allocate executable memory */
void *
dr_nonheap_alloc(size_t size, uint prot)
{
CLIENT_ASSERT(
!TESTALL(DR_MEMPROT_WRITE | DR_MEMPROT_EXEC, prot) ||
!DYNAMO_OPTION(satisfy_w_xor_x),
"reachable executable client memory is not supported with -satisfy_w_xor_x");
return heap_mmap_ex(size, size, prot, false /*no guard pages*/,
/* For back-compat we preserve reachability. */
VMM_SPECIAL_MMAP | VMM_REACHABLE);
}
DR_API
void
dr_nonheap_free(void *mem, size_t size)
{
heap_munmap_ex(mem, size, false /*no guard pages*/, VMM_SPECIAL_MMAP | VMM_REACHABLE);
}
static void *
raw_mem_alloc(size_t size, uint prot, void *addr, dr_alloc_flags_t flags)
{
byte *p;
heap_error_code_t error_code;
CLIENT_ASSERT(ALIGNED(addr, PAGE_SIZE), "addr is not page size aligned");
if (!TEST(DR_ALLOC_NON_DR, flags)) {
/* memory alloc/dealloc and updating DR list must be atomic */
dynamo_vm_areas_lock(); /* if already hold lock this is a nop */
}
addr = (void *)ALIGN_BACKWARD(addr, PAGE_SIZE);
size = ALIGN_FORWARD(size, PAGE_SIZE);
# ifdef WINDOWS
if (TEST(DR_ALLOC_LOW_2GB, flags)) {
CLIENT_ASSERT(!TEST(DR_ALLOC_COMMIT_ONLY, flags),
"cannot combine commit-only and low-2GB");
p = os_heap_reserve_in_region(NULL, (byte *)(ptr_uint_t)0x80000000, size,
&error_code, TEST(DR_MEMPROT_EXEC, flags));
if (p != NULL && !TEST(DR_ALLOC_RESERVE_ONLY, flags)) {
if (!os_heap_commit(p, size, prot, &error_code)) {
os_heap_free(p, size, &error_code);
p = NULL;
}
}
} else
# endif
{
/* We specify that DR_ALLOC_LOW_2GB only applies to x64, so it's
* ok that the Linux kernel will ignore MAP_32BIT for 32-bit.
*/
# ifdef UNIX
uint os_flags = TEST(DR_ALLOC_LOW_2GB, flags) ? RAW_ALLOC_32BIT : 0;
# else
uint os_flags = TEST(DR_ALLOC_RESERVE_ONLY, flags)
? RAW_ALLOC_RESERVE_ONLY
: (TEST(DR_ALLOC_COMMIT_ONLY, flags) ? RAW_ALLOC_COMMIT_ONLY : 0);
# endif
if (IF_WINDOWS(TEST(DR_ALLOC_COMMIT_ONLY, flags) &&) addr != NULL &&
!app_memory_pre_alloc(get_thread_private_dcontext(), addr, size, prot, false))
p = NULL;
else
p = os_raw_mem_alloc(addr, size, prot, os_flags, &error_code);
}
if (p != NULL) {
if (TEST(DR_ALLOC_NON_DR, flags)) {
all_memory_areas_lock();
update_all_memory_areas(p, p + size, prot, DR_MEMTYPE_DATA);
all_memory_areas_unlock();
} else {
/* this routine updates allmem for us: */
add_dynamo_vm_area((app_pc)p, ((app_pc)p) + size, prot,
true _IF_DEBUG("fls cb in private lib"));
}
RSTATS_ADD_PEAK(client_raw_mmap_size, size);
}
if (!TEST(DR_ALLOC_NON_DR, flags))
dynamo_vm_areas_unlock();
return p;
}
static bool
raw_mem_free(void *addr, size_t size, dr_alloc_flags_t flags)
{
bool res;
heap_error_code_t error_code;
byte *p = addr;
# ifdef UNIX
uint os_flags = TEST(DR_ALLOC_LOW_2GB, flags) ? RAW_ALLOC_32BIT : 0;
# else
uint os_flags = TEST(DR_ALLOC_RESERVE_ONLY, flags)
? RAW_ALLOC_RESERVE_ONLY
: (TEST(DR_ALLOC_COMMIT_ONLY, flags) ? RAW_ALLOC_COMMIT_ONLY : 0);
# endif
size = ALIGN_FORWARD(size, PAGE_SIZE);
if (TEST(DR_ALLOC_NON_DR, flags)) {
/* use lock to avoid racy update on parallel memory allocation,
* e.g. allocation from another thread at p happens after os_heap_free
* but before remove_from_all_memory_areas
*/
all_memory_areas_lock();
} else {
/* memory alloc/dealloc and updating DR list must be atomic */
dynamo_vm_areas_lock(); /* if already hold lock this is a nop */
}
res = os_raw_mem_free(p, size, os_flags, &error_code);
if (TEST(DR_ALLOC_NON_DR, flags)) {
remove_from_all_memory_areas(p, p + size);
all_memory_areas_unlock();
} else {
/* this routine updates allmem for us: */
remove_dynamo_vm_area((app_pc)addr, ((app_pc)addr) + size);
}
if (!TEST(DR_ALLOC_NON_DR, flags))
dynamo_vm_areas_unlock();
if (res)
RSTATS_SUB(client_raw_mmap_size, size);
return res;
}
DR_API
void *
dr_raw_mem_alloc(size_t size, uint prot, void *addr)
{
return raw_mem_alloc(size, prot, addr, DR_ALLOC_NON_DR);
}
DR_API
bool
dr_raw_mem_free(void *addr, size_t size)
{
return raw_mem_free(addr, size, DR_ALLOC_NON_DR);
}
static void *
custom_memory_shared(bool alloc, void *drcontext, dr_alloc_flags_t flags, size_t size,
uint prot, void *addr, bool *free_res)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(alloc || free_res != NULL, "must ask for free_res on free");
CLIENT_ASSERT(alloc || addr != NULL, "cannot free NULL");
CLIENT_ASSERT(!TESTALL(DR_ALLOC_NON_DR | DR_ALLOC_CACHE_REACHABLE, flags),
"dr_custom_alloc: cannot combine non-DR and cache-reachable");
CLIENT_ASSERT(!alloc || TEST(DR_ALLOC_FIXED_LOCATION, flags) || addr == NULL,
"dr_custom_alloc: address only honored for fixed location");
# ifdef WINDOWS
CLIENT_ASSERT(!TESTANY(DR_ALLOC_RESERVE_ONLY | DR_ALLOC_COMMIT_ONLY, flags) ||
TESTALL(DR_ALLOC_NON_HEAP | DR_ALLOC_NON_DR, flags),
"dr_custom_alloc: reserve/commit-only are only for non-DR non-heap");
CLIENT_ASSERT(!TEST(DR_ALLOC_RESERVE_ONLY, flags) ||
!TEST(DR_ALLOC_COMMIT_ONLY, flags),
"dr_custom_alloc: cannot combine reserve-only + commit-only");
# endif
CLIENT_ASSERT(!TEST(DR_ALLOC_CACHE_REACHABLE, flags) ||
!DYNAMO_OPTION(satisfy_w_xor_x),
"dr_custom_alloc: DR_ALLOC_CACHE_REACHABLE memory is not "
"supported with -satisfy_w_xor_x");
if (TEST(DR_ALLOC_NON_HEAP, flags)) {
CLIENT_ASSERT(drcontext == NULL,
"dr_custom_alloc: drcontext must be NULL for non-heap");
CLIENT_ASSERT(!TEST(DR_ALLOC_THREAD_PRIVATE, flags),
"dr_custom_alloc: non-heap cannot be thread-private");
CLIENT_ASSERT(!TESTALL(DR_ALLOC_CACHE_REACHABLE | DR_ALLOC_LOW_2GB, flags),
"dr_custom_alloc: cannot combine low-2GB and cache-reachable");
# ifdef WINDOWS
CLIENT_ASSERT(addr != NULL || !TEST(DR_ALLOC_COMMIT_ONLY, flags),
"dr_custom_alloc: commit-only requires non-NULL addr");
# endif
if (TEST(DR_ALLOC_LOW_2GB, flags)) {
# ifdef WINDOWS
CLIENT_ASSERT(!TEST(DR_ALLOC_COMMIT_ONLY, flags),
"dr_custom_alloc: cannot combine commit-only and low-2GB");
# endif
CLIENT_ASSERT(!alloc || addr == NULL,
"dr_custom_alloc: cannot pass an addr with low-2GB");
/* Even if not non-DR, easier to allocate via raw */
if (alloc)
return raw_mem_alloc(size, prot, addr, flags);
else
*free_res = raw_mem_free(addr, size, flags);
} else if (TEST(DR_ALLOC_NON_DR, flags)) {
/* ok for addr to be NULL */
if (alloc)
return raw_mem_alloc(size, prot, addr, flags);
else
*free_res = raw_mem_free(addr, size, flags);
} else { /* including DR_ALLOC_CACHE_REACHABLE */
CLIENT_ASSERT(!alloc || !TEST(DR_ALLOC_CACHE_REACHABLE, flags) ||
addr == NULL,
"dr_custom_alloc: cannot ask for addr and cache-reachable");
/* This flag is here solely so we know which version of free to call */
if (TEST(DR_ALLOC_FIXED_LOCATION, flags) ||
!TEST(DR_ALLOC_CACHE_REACHABLE, flags)) {
CLIENT_ASSERT(addr != NULL || !TEST(DR_ALLOC_FIXED_LOCATION, flags),
"dr_custom_alloc: fixed location requires an address");
if (alloc)
return raw_mem_alloc(size, prot, addr, 0);
else
*free_res = raw_mem_free(addr, size, 0);
} else {
if (alloc)
return dr_nonheap_alloc(size, prot);
else {
*free_res = true;
dr_nonheap_free(addr, size);
}
}
}
} else {
if (!alloc)
*free_res = true;
CLIENT_ASSERT(!alloc || addr == NULL,
"dr_custom_alloc: cannot pass an addr for heap memory");
CLIENT_ASSERT(drcontext == NULL || TEST(DR_ALLOC_THREAD_PRIVATE, flags),
"dr_custom_alloc: drcontext must be NULL for global heap");
CLIENT_ASSERT(!TEST(DR_ALLOC_LOW_2GB, flags),
"dr_custom_alloc: cannot ask for heap in low 2GB");
CLIENT_ASSERT(!TEST(DR_ALLOC_NON_DR, flags),
"dr_custom_alloc: cannot ask for non-DR heap memory");
if (TEST(DR_ALLOC_CACHE_REACHABLE, flags)) {
if (TEST(DR_ALLOC_THREAD_PRIVATE, flags)) {
if (alloc)
return dr_thread_alloc(drcontext, size);
else
dr_thread_free(drcontext, addr, size);
} else {
if (alloc)
return dr_global_alloc(size);
else
dr_global_free(addr, size);
}
} else {
if (TEST(DR_ALLOC_THREAD_PRIVATE, flags)) {
if (alloc)
return heap_alloc(dcontext, size HEAPACCT(ACCT_CLIENT));
else
heap_free(dcontext, addr, size HEAPACCT(ACCT_CLIENT));
} else {
if (alloc)
return global_heap_alloc(size HEAPACCT(ACCT_CLIENT));
else
global_heap_free(addr, size HEAPACCT(ACCT_CLIENT));
}
}
}
return NULL;
}
DR_API
void *
dr_custom_alloc(void *drcontext, dr_alloc_flags_t flags, size_t size, uint prot,
void *addr)
{
return custom_memory_shared(true, drcontext, flags, size, prot, addr, NULL);
}
DR_API
bool
dr_custom_free(void *drcontext, dr_alloc_flags_t flags, void *addr, size_t size)
{
bool res;
custom_memory_shared(false, drcontext, flags, size, 0, addr, &res);
return res;
}
# ifdef UNIX
DR_API
/* With ld's -wrap option, we can supply a replacement for malloc.
* This routine allocates memory from DR's global memory pool. Unlike
* dr_global_alloc(), however, we store the size of the allocation in
* the first few bytes so __wrap_free() can retrieve it.
*/
void *
__wrap_malloc(size_t size)
{
return redirect_malloc(size);
}
DR_API
/* With ld's -wrap option, we can supply a replacement for realloc.
* This routine allocates memory from DR's global memory pool. Unlike
* dr_global_alloc(), however, we store the size of the allocation in
* the first few bytes so __wrap_free() can retrieve it.
*/
void *
__wrap_realloc(void *mem, size_t size)
{
return redirect_realloc(mem, size);
}
DR_API
/* With ld's -wrap option, we can supply a replacement for calloc.
* This routine allocates memory from DR's global memory pool. Unlike
* dr_global_alloc(), however, we store the size of the allocation in
* the first few bytes so __wrap_free() can retrieve it.
*/
void *
__wrap_calloc(size_t nmemb, size_t size)
{
return redirect_calloc(nmemb, size);
}
DR_API
/* With ld's -wrap option, we can supply a replacement for free. This
* routine frees memory allocated by __wrap_alloc and expects the
* allocation size to be available in the few bytes before 'mem'.
*/
void
__wrap_free(void *mem)
{
redirect_free(mem);
}
# endif
DR_API
bool
dr_memory_protect(void *base, size_t size, uint new_prot)
{
/* We do allow the client to modify DR memory, for allocating a
* region and later making it unwritable. We should probably
* allow modifying ntdll, since our general model is to trust the
* client and let it shoot itself in the foot, but that would require
* passing in extra args to app_memory_protection_change() to ignore
* the patch_proof_list: and maybe it is safer to disallow client
* from putting hooks in ntdll.
*/
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
if (!dynamo_vm_area_overlap(base, ((byte *)base) + size)) {
uint mod_prot = new_prot;
uint res = app_memory_protection_change(get_thread_private_dcontext(), base, size,
new_prot, &mod_prot, NULL);
if (res != DO_APP_MEM_PROT_CHANGE) {
if (res == FAIL_APP_MEM_PROT_CHANGE || res == PRETEND_APP_MEM_PROT_CHANGE) {
return false;
} else {
/* SUBSET_APP_MEM_PROT_CHANGE should only happen for
* PROGRAM_SHEPHERDING. FIXME: not sure how common
* this will be: for now we just fail.
*/
return false;
}
}
CLIENT_ASSERT(mod_prot == new_prot, "internal error on dr_memory_protect()");
}
return set_protection(base, size, new_prot);
}
DR_API
size_t
dr_page_size(void)
{
return os_page_size();
}
DR_API
/* checks to see that all bytes with addresses from pc to pc+size-1
* are readable and that reading from there won't generate an exception.
*/
bool
dr_memory_is_readable(const byte *pc, size_t size)
{
return is_readable_without_exception(pc, size);
}
DR_API
/* OS neutral memory query for clients, just wrapper around our get_memory_info(). */
bool
dr_query_memory(const byte *pc, byte **base_pc, size_t *size, uint *prot)
{
uint real_prot;
bool res;
# if defined(UNIX) && defined(HAVE_MEMINFO)
/* xref PR 246897 - the cached all memory list can have problems when
* out-of-process entities change the mapings. For now we use the from
* os version instead (even though it's slower, and only if we have
* HAVE_MEMINFO_MAPS support). FIXME
* XXX i#853: We could decide allmem vs os with the use_all_memory_areas
* option.
*/
res = get_memory_info_from_os(pc, base_pc, size, &real_prot);
# else
res = get_memory_info(pc, base_pc, size, &real_prot);
# endif
if (prot != NULL) {
if (is_pretend_or_executable_writable((app_pc)pc)) {
/* We can't assert there's no DR_MEMPROT_WRITE b/c we mark selfmod
* as executable-but-writable and we'll come here.
*/
real_prot |= DR_MEMPROT_WRITE | DR_MEMPROT_PRETEND_WRITE;
}
*prot = real_prot;
}
return res;
}
DR_API
bool
dr_query_memory_ex(const byte *pc, OUT dr_mem_info_t *info)
{
bool res;
# if defined(UNIX) && defined(HAVE_MEMINFO)
/* PR 246897: all_memory_areas not ready for prime time */
res = query_memory_ex_from_os(pc, info);
# else
res = query_memory_ex(pc, info);
# endif
if (is_pretend_or_executable_writable((app_pc)pc)) {
/* We can't assert there's no DR_MEMPROT_WRITE b/c we mark selfmod
* as executable-but-writable and we'll come here.
*/
info->prot |= DR_MEMPROT_WRITE | DR_MEMPROT_PRETEND_WRITE;
}
return res;
}
DR_API
/* Wrapper around our safe_read. Xref P4 198875, placeholder till we have try/except */
bool
dr_safe_read(const void *base, size_t size, void *out_buf, size_t *bytes_read)
{
return safe_read_ex(base, size, out_buf, bytes_read);
}
DR_API
/* Wrapper around our safe_write. Xref P4 198875, placeholder till we have try/except */
bool
dr_safe_write(void *base, size_t size, const void *in_buf, size_t *bytes_written)
{
return safe_write_ex(base, size, in_buf, bytes_written);
}
DR_API
void
dr_try_setup(void *drcontext, void **try_cxt)
{
/* Yes we're duplicating the code from the TRY() macro but this
* provides better abstraction and lets us change our impl later
* vs exposing that macro
*/
dcontext_t *dcontext = (dcontext_t *)drcontext;
try_except_context_t *try_state;
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
ASSERT(dcontext != NULL && dcontext == get_thread_private_dcontext());
ASSERT(try_cxt != NULL);
/* We allocate on the heap to avoid having to expose the try_except_context_t
* and dr_jmp_buf_t structs and be tied to their exact layouts.
* The client is likely to allocate memory inside the try anyway
* if doing a decode or something.
*/
try_state = (try_except_context_t *)HEAP_TYPE_ALLOC(dcontext, try_except_context_t,
ACCT_CLIENT, PROTECTED);
*try_cxt = try_state;
try_state->prev_context = dcontext->try_except.try_except_state;
dcontext->try_except.try_except_state = try_state;
}
/* dr_try_start() is in x86.asm since we can't have an extra frame that's
* going to be torn down between the longjmp and the restore point
*/
DR_API
void
dr_try_stop(void *drcontext, void *try_cxt)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
try_except_context_t *try_state = (try_except_context_t *)try_cxt;
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
ASSERT(dcontext != NULL && dcontext == get_thread_private_dcontext());
ASSERT(try_state != NULL);
POP_TRY_BLOCK(&dcontext->try_except, *try_state);
HEAP_TYPE_FREE(dcontext, try_state, try_except_context_t, ACCT_CLIENT, PROTECTED);
}
DR_API
bool
dr_memory_is_dr_internal(const byte *pc)
{
return is_dynamo_address((app_pc)pc);
}
DR_API
bool
dr_memory_is_in_client(const byte *pc)
{
return is_in_client_lib((app_pc)pc);
}
void
instrument_client_lib_loaded(byte *start, byte *end)
{
/* i#852: include Extensions as they are really part of the clients and
* aren't like other private libs.
* XXX: we only avoid having the client libs on here b/c they're specified via
* full path and don't go through the loaders' locate routines.
* Not a big deal if they do end up on here: if they always did we could
* remove the linear walk in is_in_client_lib().
*/
/* called prior to instrument_init() */
init_client_aux_libs();
vmvector_add(client_aux_libs, start, end, NULL /*not an auxlib*/);
}
void
instrument_client_lib_unloaded(byte *start, byte *end)
{
/* called after instrument_exit() */
if (client_aux_libs != NULL)
vmvector_remove(client_aux_libs, start, end);
}
/**************************************************
* CLIENT AUXILIARY LIBRARIES
*/
DR_API
dr_auxlib_handle_t
dr_load_aux_library(const char *name, byte **lib_start /*OPTIONAL OUT*/,
byte **lib_end /*OPTIONAL OUT*/)
{
byte *start, *end;
dr_auxlib_handle_t lib = load_shared_library(name, true /*reachable*/);
if (shared_library_bounds(lib, NULL, name, &start, &end)) {
/* be sure to replace b/c i#852 now adds during load w/ empty data */
vmvector_add_replace(client_aux_libs, start, end, (void *)lib);
if (lib_start != NULL)
*lib_start = start;
if (lib_end != NULL)
*lib_end = end;
all_memory_areas_lock();
update_all_memory_areas(start, end,
/* XXX: see comment in instrument_init()
* on walking the sections and what prot to use
*/
MEMPROT_READ, DR_MEMTYPE_IMAGE);
all_memory_areas_unlock();
} else {
unload_shared_library(lib);
lib = NULL;
}
return lib;
}
DR_API
dr_auxlib_routine_ptr_t
dr_lookup_aux_library_routine(dr_auxlib_handle_t lib, const char *name)
{
if (lib == NULL)
return NULL;
return lookup_library_routine(lib, name);
}
DR_API
bool
dr_unload_aux_library(dr_auxlib_handle_t lib)
{
byte *start = NULL, *end = NULL;
/* unfortunately on linux w/ dlopen we cannot find the bounds w/o
* either the path or an address so we iterate.
* once we have our private loader we shouldn't need this:
* XXX i#157
*/
vmvector_iterator_t vmvi;
dr_auxlib_handle_t found = NULL;
if (lib == NULL)
return false;
vmvector_iterator_start(client_aux_libs, &vmvi);
while (vmvector_iterator_hasnext(&vmvi)) {
found = (dr_auxlib_handle_t)vmvector_iterator_next(&vmvi, &start, &end);
if (found == lib)
break;
}
vmvector_iterator_stop(&vmvi);
if (found == lib) {
CLIENT_ASSERT(start != NULL && start < end, "logic error");
vmvector_remove(client_aux_libs, start, end);
unload_shared_library(lib);
all_memory_areas_lock();
update_all_memory_areas(start, end, MEMPROT_NONE, DR_MEMTYPE_FREE);
all_memory_areas_unlock();
return true;
} else {
CLIENT_ASSERT(false, "invalid aux lib");
return false;
}
}
# if defined(WINDOWS) && !defined(X64)
/* XXX i#1633: these routines all have 64-bit handle and routine types for
* handling win8's high ntdll64 in the future. For now the implementation
* treats them as 32-bit types and we do not support win8+.
*/
DR_API
dr_auxlib64_handle_t
dr_load_aux_x64_library(const char *name)
{
HANDLE h;
/* We use the x64 system loader. We assume that x64 state is fine being
* interrupted at arbitrary points during x86 execution, and that there
* is little risk of transparency violations.
*/
/* load_library_64() is racy. We don't expect anyone else to load
* x64 libs, but another thread in this client could, so we
* serialize here.
*/
d_r_mutex_lock(&client_aux_lib64_lock);
/* XXX: if we switch to our private loader we'll need to add custom
* search support to look in 64-bit system dir
*/
/* XXX: I'd add to the client_aux_libs vector, but w/ the system loader
* loading this I don't know all the dependent libs it might load.
* Not bothering for now.
*/
h = load_library_64(name);
d_r_mutex_unlock(&client_aux_lib64_lock);
return (dr_auxlib64_handle_t)h;
}
DR_API
dr_auxlib64_routine_ptr_t
dr_lookup_aux_x64_library_routine(dr_auxlib64_handle_t lib, const char *name)
{
uint64 res = get_proc_address_64((uint64)lib, name);
return (dr_auxlib64_routine_ptr_t)res;
}
DR_API
bool
dr_unload_aux_x64_library(dr_auxlib64_handle_t lib)
{
bool res;
d_r_mutex_lock(&client_aux_lib64_lock);
res = free_library_64((HANDLE)(uint)lib); /* uint cast to avoid cl warning */
d_r_mutex_unlock(&client_aux_lib64_lock);
return res;
}
# endif
/***************************************************************************
* LOCKS
*/
DR_API
/* Initializes a mutex
*/
void *
dr_mutex_create(void)
{
void *mutex =
(void *)HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, mutex_t, ACCT_CLIENT, UNPROTECTED);
ASSIGN_INIT_LOCK_FREE(*((mutex_t *)mutex), dr_client_mutex);
return mutex;
}
DR_API
/* Deletes mutex
*/
void
dr_mutex_destroy(void *mutex)
{
/* Delete mutex so locks_not_closed()==0 test in dynamo.c passes */
DELETE_LOCK(*((mutex_t *)mutex));
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, (mutex_t *)mutex, mutex_t, ACCT_CLIENT, UNPROTECTED);
}
DR_API
/* Locks mutex
*/
void
dr_mutex_lock(void *mutex)
{
dcontext_t *dcontext = get_thread_private_dcontext();
/* set client_grab_mutex so that we know to set client_thread_safe_for_synch
* around the actual wait for the lock */
if (IS_CLIENT_THREAD(dcontext)) {
dcontext->client_data->client_grab_mutex = mutex;
/* We do this on the outside so that we're conservative wrt races
* in the direction of not killing the thread while it has a lock
*/
dcontext->client_data->mutex_count++;
}
d_r_mutex_lock((mutex_t *)mutex);
if (IS_CLIENT_THREAD(dcontext))
dcontext->client_data->client_grab_mutex = NULL;
}
DR_API
/* Unlocks mutex
*/
void
dr_mutex_unlock(void *mutex)
{
dcontext_t *dcontext = get_thread_private_dcontext();
d_r_mutex_unlock((mutex_t *)mutex);
/* We do this on the outside so that we're conservative wrt races
* in the direction of not killing the thread while it has a lock
*/
if (IS_CLIENT_THREAD(dcontext)) {
CLIENT_ASSERT(dcontext->client_data->mutex_count > 0,
"internal client mutex nesting error");
dcontext->client_data->mutex_count--;
}
}
DR_API
/* Tries once to grab the lock, returns whether or not successful
*/
bool
dr_mutex_trylock(void *mutex)
{
bool success = false;
dcontext_t *dcontext = get_thread_private_dcontext();
/* set client_grab_mutex so that we know to set client_thread_safe_for_synch
* around the actual wait for the lock */
if (IS_CLIENT_THREAD(dcontext)) {
dcontext->client_data->client_grab_mutex = mutex;
/* We do this on the outside so that we're conservative wrt races
* in the direction of not killing the thread while it has a lock
*/
dcontext->client_data->mutex_count++;
}
success = d_r_mutex_trylock((mutex_t *)mutex);
if (IS_CLIENT_THREAD(dcontext)) {
if (!success)
dcontext->client_data->mutex_count--;
dcontext->client_data->client_grab_mutex = NULL;
}
return success;
}
DR_API
bool
dr_mutex_self_owns(void *mutex)
{
return IF_DEBUG_ELSE(OWN_MUTEX((mutex_t *)mutex), true);
}
DR_API
bool
dr_mutex_mark_as_app(void *mutex)
{
mutex_t *lock = (mutex_t *)mutex;
d_r_mutex_mark_as_app(lock);
return true;
}
DR_API
void *
dr_rwlock_create(void)
{
void *rwlock = (void *)HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, read_write_lock_t,
ACCT_CLIENT, UNPROTECTED);
ASSIGN_INIT_READWRITE_LOCK_FREE(*((read_write_lock_t *)rwlock), dr_client_mutex);
return rwlock;
}
DR_API
void
dr_rwlock_destroy(void *rwlock)
{
DELETE_READWRITE_LOCK(*((read_write_lock_t *)rwlock));
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, (read_write_lock_t *)rwlock, read_write_lock_t,
ACCT_CLIENT, UNPROTECTED);
}
DR_API
void
dr_rwlock_read_lock(void *rwlock)
{
d_r_read_lock((read_write_lock_t *)rwlock);
}
DR_API
void
dr_rwlock_read_unlock(void *rwlock)
{
d_r_read_unlock((read_write_lock_t *)rwlock);
}
DR_API
void
dr_rwlock_write_lock(void *rwlock)
{
d_r_write_lock((read_write_lock_t *)rwlock);
}
DR_API
void
dr_rwlock_write_unlock(void *rwlock)
{
d_r_write_unlock((read_write_lock_t *)rwlock);
}
DR_API
bool
dr_rwlock_write_trylock(void *rwlock)
{
return d_r_write_trylock((read_write_lock_t *)rwlock);
}
DR_API
bool
dr_rwlock_self_owns_write_lock(void *rwlock)
{
return self_owns_write_lock((read_write_lock_t *)rwlock);
}
DR_API
bool
dr_rwlock_mark_as_app(void *rwlock)
{
read_write_lock_t *lock = (read_write_lock_t *)rwlock;
d_r_mutex_mark_as_app(&lock->lock);
return true;
}
DR_API
void *
dr_recurlock_create(void)
{
void *reclock = (void *)HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, recursive_lock_t,
ACCT_CLIENT, UNPROTECTED);
ASSIGN_INIT_RECURSIVE_LOCK_FREE(*((recursive_lock_t *)reclock), dr_client_mutex);
return reclock;
}
DR_API
void
dr_recurlock_destroy(void *reclock)
{
DELETE_RECURSIVE_LOCK(*((recursive_lock_t *)reclock));
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, (recursive_lock_t *)reclock, recursive_lock_t,
ACCT_CLIENT, UNPROTECTED);
}
DR_API
void
dr_recurlock_lock(void *reclock)
{
acquire_recursive_lock((recursive_lock_t *)reclock);
}
DR_API
void
dr_app_recurlock_lock(void *reclock, dr_mcontext_t *mc)
{
CLIENT_ASSERT(mc->flags == DR_MC_ALL, "mcontext must be for DR_MC_ALL");
acquire_recursive_app_lock((recursive_lock_t *)reclock,
dr_mcontext_as_priv_mcontext(mc));
}
DR_API
void
dr_recurlock_unlock(void *reclock)
{
release_recursive_lock((recursive_lock_t *)reclock);
}
DR_API
bool
dr_recurlock_trylock(void *reclock)
{
return try_recursive_lock((recursive_lock_t *)reclock);
}
DR_API
bool
dr_recurlock_self_owns(void *reclock)
{
return self_owns_recursive_lock((recursive_lock_t *)reclock);
}
DR_API
bool
dr_recurlock_mark_as_app(void *reclock)
{
recursive_lock_t *lock = (recursive_lock_t *)reclock;
d_r_mutex_mark_as_app(&lock->lock);
return true;
}
DR_API
void *
dr_event_create(void)
{
return (void *)create_event();
}
DR_API
bool
dr_event_destroy(void *event)
{
destroy_event((event_t)event);
return true;
}
DR_API
bool
dr_event_wait(void *event)
{
dcontext_t *dcontext = get_thread_private_dcontext();
if (IS_CLIENT_THREAD(dcontext))
dcontext->client_data->client_thread_safe_for_synch = true;
wait_for_event((event_t)event, 0);
if (IS_CLIENT_THREAD(dcontext))
dcontext->client_data->client_thread_safe_for_synch = false;
return true;
}
DR_API
bool
dr_event_signal(void *event)
{
signal_event((event_t)event);
return true;
}
DR_API
bool
dr_event_reset(void *event)
{
reset_event((event_t)event);
return true;
}
DR_API
bool
dr_mark_safe_to_suspend(void *drcontext, bool enter)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
ASSERT_OWN_NO_LOCKS();
/* We need to return so we can't call check_wait_at_safe_spot().
* We don't set mcontext b/c noone should examine it.
*/
if (enter)
set_synch_state(dcontext, THREAD_SYNCH_NO_LOCKS_NO_XFER);
else
set_synch_state(dcontext, THREAD_SYNCH_NONE);
return true;
}
DR_API
int
dr_atomic_add32_return_sum(volatile int *x, int val)
{
return atomic_add_exchange_int(x, val);
}
/***************************************************************************
* MODULES
*/
DR_API
/* Looks up the module data containing pc. Returns NULL if not found.
* Returned module_data_t must be freed with dr_free_module_data(). */
module_data_t *
dr_lookup_module(byte *pc)
{
module_area_t *area;
module_data_t *client_data;
os_get_module_info_lock();
area = module_pc_lookup(pc);
client_data = copy_module_area_to_module_data(area);
os_get_module_info_unlock();
return client_data;
}
DR_API
module_data_t *
dr_get_main_module(void)
{
return dr_lookup_module(get_image_entry());
}
DR_API
/* Looks up the module with name matching name (ignoring case). Returns NULL if not
* found. Returned module_data_t must be freed with dr_free_module_data(). */
module_data_t *
dr_lookup_module_by_name(const char *name)
{
/* We have no quick way of doing this since our module list is indexed by pc. We
* could use get_module_handle() but that's dangerous to call at arbitrary times,
* so we just walk our full list here. */
module_iterator_t *mi = module_iterator_start();
CLIENT_ASSERT((name != NULL), "dr_lookup_module_info_by_name: null name");
while (module_iterator_hasnext(mi)) {
module_area_t *area = module_iterator_next(mi);
module_data_t *client_data;
const char *modname = GET_MODULE_NAME(&area->names);
if (modname != NULL && strcasecmp(modname, name) == 0) {
client_data = copy_module_area_to_module_data(area);
module_iterator_stop(mi);
return client_data;
}
}
module_iterator_stop(mi);
return NULL;
}
typedef struct _client_mod_iterator_list_t {
module_data_t *info;
struct _client_mod_iterator_list_t *next;
} client_mod_iterator_list_t;
typedef struct {
client_mod_iterator_list_t *current;
client_mod_iterator_list_t *full_list;
} client_mod_iterator_t;
DR_API
/* Initialize a new client module iterator. */
dr_module_iterator_t *
dr_module_iterator_start(void)
{
client_mod_iterator_t *client_iterator = (client_mod_iterator_t *)HEAP_TYPE_ALLOC(
GLOBAL_DCONTEXT, client_mod_iterator_t, ACCT_CLIENT, UNPROTECTED);
module_iterator_t *dr_iterator = module_iterator_start();
memset(client_iterator, 0, sizeof(*client_iterator));
while (module_iterator_hasnext(dr_iterator)) {
module_area_t *area = module_iterator_next(dr_iterator);
client_mod_iterator_list_t *list = (client_mod_iterator_list_t *)HEAP_TYPE_ALLOC(
GLOBAL_DCONTEXT, client_mod_iterator_list_t, ACCT_CLIENT, UNPROTECTED);
ASSERT(area != NULL);
list->info = copy_module_area_to_module_data(area);
list->next = NULL;
if (client_iterator->current == NULL) {
client_iterator->current = list;
client_iterator->full_list = client_iterator->current;
} else {
client_iterator->current->next = list;
client_iterator->current = client_iterator->current->next;
}
}
module_iterator_stop(dr_iterator);
client_iterator->current = client_iterator->full_list;
return (dr_module_iterator_t)client_iterator;
}
DR_API
/* Returns true if there is another loaded module in the iterator. */
bool
dr_module_iterator_hasnext(dr_module_iterator_t *mi)
{
CLIENT_ASSERT((mi != NULL), "dr_module_iterator_hasnext: null iterator");
return ((client_mod_iterator_t *)mi)->current != NULL;
}
DR_API
/* Retrieves the module_data_t for the next loaded module in the iterator. */
module_data_t *
dr_module_iterator_next(dr_module_iterator_t *mi)
{
module_data_t *data;
client_mod_iterator_t *ci = (client_mod_iterator_t *)mi;
CLIENT_ASSERT((mi != NULL), "dr_module_iterator_next: null iterator");
CLIENT_ASSERT((ci->current != NULL),
"dr_module_iterator_next: has no next, use "
"dr_module_iterator_hasnext() first");
if (ci->current == NULL)
return NULL;
data = ci->current->info;
ci->current = ci->current->next;
return data;
}
DR_API
/* Free the module iterator. */
void
dr_module_iterator_stop(dr_module_iterator_t *mi)
{
client_mod_iterator_t *ci = (client_mod_iterator_t *)mi;
CLIENT_ASSERT((mi != NULL), "dr_module_iterator_stop: null iterator");
/* free module_data_t's we didn't give to the client */
while (ci->current != NULL) {
dr_free_module_data(ci->current->info);
ci->current = ci->current->next;
}
ci->current = ci->full_list;
while (ci->current != NULL) {
client_mod_iterator_list_t *next = ci->current->next;
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, ci->current, client_mod_iterator_list_t,
ACCT_CLIENT, UNPROTECTED);
ci->current = next;
}
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, ci, client_mod_iterator_t, ACCT_CLIENT, UNPROTECTED);
}
DR_API
/* Get the name dr uses for this module. */
const char *
dr_module_preferred_name(const module_data_t *data)
{
if (data == NULL)
return NULL;
return GET_MODULE_NAME(&data->names);
}
# ifdef WINDOWS
DR_API
/* If pc is within a section of module lib returns true and (optionally) a copy of
* the IMAGE_SECTION_HEADER in section_out. If pc is not within a section of the
* module mod return false. */
bool
dr_lookup_module_section(module_handle_t lib, byte *pc, IMAGE_SECTION_HEADER *section_out)
{
CLIENT_ASSERT((lib != NULL), "dr_lookup_module_section: null module_handle_t");
return module_pc_section_lookup((app_pc)lib, pc, section_out);
}
# endif
/* i#805: Instead of exposing multiple instruction levels, we expose a way for
* clients to turn off instrumentation. Then DR can avoid a full decode and we
* can save some time on modules that are not interesting.
* XXX: This breaks other clients and extensions, in particular drwrap, which
* can miss call and return sites in the uninstrumented module.
*/
DR_API
bool
dr_module_set_should_instrument(module_handle_t handle, bool should_instrument)
{
module_area_t *ma;
DEBUG_DECLARE(dcontext_t *dcontext = get_thread_private_dcontext());
IF_DEBUG(executable_areas_lock());
os_get_module_info_write_lock();
ma = module_pc_lookup((byte *)handle);
if (ma != NULL) {
/* This kind of obviates the need for handle, but it makes the API more
* explicit.
*/
CLIENT_ASSERT(dcontext->client_data->no_delete_mod_data->handle == handle,
"Do not call dr_module_set_should_instrument() outside "
"of the module's own load event");
ASSERT(!executable_vm_area_executed_from(ma->start, ma->end));
if (should_instrument) {
ma->flags &= ~MODULE_NULL_INSTRUMENT;
} else {
ma->flags |= MODULE_NULL_INSTRUMENT;
}
}
os_get_module_info_write_unlock();
IF_DEBUG(executable_areas_unlock());
return (ma != NULL);
}
DR_API
bool
dr_module_should_instrument(module_handle_t handle)
{
bool should_instrument = true;
module_area_t *ma;
os_get_module_info_lock();
ma = module_pc_lookup((byte *)handle);
CLIENT_ASSERT(ma != NULL, "invalid module handle");
if (ma != NULL) {
should_instrument = !TEST(MODULE_NULL_INSTRUMENT, ma->flags);
}
os_get_module_info_unlock();
return should_instrument;
}
DR_API
/* Returns the entry point of the function with the given name in the module
* with the given handle.
* We're not taking in module_data_t to make it simpler for the client
* to iterate or lookup the module_data_t, store the single-field
* handle, and then free the data right away: besides, module_data_t
* is not an opaque type.
*/
generic_func_t
dr_get_proc_address(module_handle_t lib, const char *name)
{
# ifdef WINDOWS
return get_proc_address_resolve_forward(lib, name);
# else
return d_r_get_proc_address(lib, name);
# endif
}
DR_API
bool
dr_get_proc_address_ex(module_handle_t lib, const char *name, dr_export_info_t *info OUT,
size_t info_len)
{
/* If we add new fields we'll check various values of info_len */
if (info == NULL || info_len < sizeof(*info))
return false;
# ifdef WINDOWS
info->address = get_proc_address_resolve_forward(lib, name);
info->is_indirect_code = false;
# else
info->address = get_proc_address_ex(lib, name, &info->is_indirect_code);
# endif
return (info->address != NULL);
}
byte *
dr_map_executable_file(const char *filename, dr_map_executable_flags_t flags,
size_t *size OUT)
{
# ifdef MACOS
/* XXX i#1285: implement private loader on Mac */
return NULL;
# else
modload_flags_t mflags = MODLOAD_NOT_PRIVLIB;
if (TEST(DR_MAPEXE_SKIP_WRITABLE, flags))
mflags |= MODLOAD_SKIP_WRITABLE;
if (filename == NULL)
return NULL;
return privload_map_and_relocate(filename, size, mflags);
# endif
}
bool
dr_unmap_executable_file(byte *base, size_t size)
{
return d_r_unmap_file(base, size);
}
DR_API
/* Creates a new directory. Fails if the directory already exists
* or if it can't be created.
*/
bool
dr_create_dir(const char *fname)
{
return os_create_dir(fname, CREATE_DIR_REQUIRE_NEW);
}
DR_API
bool
dr_delete_dir(const char *fname)
{
return os_delete_dir(fname);
}
DR_API
bool
dr_get_current_directory(char *buf, size_t bufsz)
{
return os_get_current_dir(buf, bufsz);
}
DR_API
/* Checks existence of a directory. */
bool
dr_directory_exists(const char *fname)
{
return os_file_exists(fname, true);
}
DR_API
/* Checks for the existence of a file. */
bool
dr_file_exists(const char *fname)
{
return os_file_exists(fname, false);
}
DR_API
/* Opens a file in the mode specified by mode_flags.
* Returns INVALID_FILE if unsuccessful
*/
file_t
dr_open_file(const char *fname, uint mode_flags)
{
uint flags = 0;
if (TEST(DR_FILE_WRITE_REQUIRE_NEW, mode_flags)) {
flags |= OS_OPEN_WRITE | OS_OPEN_REQUIRE_NEW;
}
if (TEST(DR_FILE_WRITE_APPEND, mode_flags)) {
CLIENT_ASSERT((flags == 0), "dr_open_file: multiple write modes selected");
flags |= OS_OPEN_WRITE | OS_OPEN_APPEND;
}
if (TEST(DR_FILE_WRITE_OVERWRITE, mode_flags)) {
CLIENT_ASSERT((flags == 0), "dr_open_file: multiple write modes selected");
flags |= OS_OPEN_WRITE;
}
if (TEST(DR_FILE_WRITE_ONLY, mode_flags)) {
CLIENT_ASSERT((flags == 0), "dr_open_file: multiple write modes selected");
flags |= OS_OPEN_WRITE_ONLY;
}
if (TEST(DR_FILE_READ, mode_flags))
flags |= OS_OPEN_READ;
CLIENT_ASSERT((flags != 0), "dr_open_file: no mode selected");
if (TEST(DR_FILE_ALLOW_LARGE, mode_flags))
flags |= OS_OPEN_ALLOW_LARGE;
if (TEST(DR_FILE_CLOSE_ON_FORK, mode_flags))
flags |= OS_OPEN_CLOSE_ON_FORK;
/* all client-opened files are protected */
return os_open_protected(fname, flags);
}
DR_API
/* Closes file f
*/
void
dr_close_file(file_t f)
{
/* all client-opened files are protected */
os_close_protected(f);
}
DR_API
/* Renames the file src to dst. */
bool
dr_rename_file(const char *src, const char *dst, bool replace)
{
return os_rename_file(src, dst, replace);
}
DR_API
/* Deletes a file. */
bool
dr_delete_file(const char *filename)
{
/* os_delete_mapped_file should be a superset of os_delete_file, so we use
* it.
*/
return os_delete_mapped_file(filename);
}
DR_API
/* Flushes any buffers for file f
*/
void
dr_flush_file(file_t f)
{
os_flush(f);
}
DR_API
/* Writes count bytes from buf to f.
* Returns the actual number written.
*/
ssize_t
dr_write_file(file_t f, const void *buf, size_t count)
{
# ifdef WINDOWS
if ((f == STDOUT || f == STDERR) && print_to_console)
return dr_write_to_console_varg(f == STDOUT, "%.*s", count, buf);
else
# endif
return os_write(f, buf, count);
}
DR_API
/* Reads up to count bytes from f into buf.
* Returns the actual number read.
*/
ssize_t
dr_read_file(file_t f, void *buf, size_t count)
{
return os_read(f, buf, count);
}
DR_API
/* sets the current file position for file f to offset bytes from the specified origin
* returns true if successful */
bool
dr_file_seek(file_t f, int64 offset, int origin)
{
CLIENT_ASSERT(origin == DR_SEEK_SET || origin == DR_SEEK_CUR || origin == DR_SEEK_END,
"dr_file_seek: invalid origin value");
return os_seek(f, offset, origin);
}
DR_API
/* gets the current file position for file f in bytes from start of file */
int64
dr_file_tell(file_t f)
{
return os_tell(f);
}
DR_API
file_t
dr_dup_file_handle(file_t f)
{
# ifdef UNIX
/* returns -1 on failure == INVALID_FILE */
return dup_syscall(f);
# else
HANDLE ht = INVALID_HANDLE_VALUE;
NTSTATUS res =
duplicate_handle(NT_CURRENT_PROCESS, f, NT_CURRENT_PROCESS, &ht, SYNCHRONIZE, 0,
DUPLICATE_SAME_ACCESS | DUPLICATE_SAME_ATTRIBUTES);
if (!NT_SUCCESS(res))
return INVALID_FILE;
else
return ht;
# endif
}
DR_API
bool
dr_file_size(file_t fd, OUT uint64 *size)
{
return os_get_file_size_by_handle(fd, size);
}
DR_API
void *
dr_map_file(file_t f, size_t *size INOUT, uint64 offs, app_pc addr, uint prot, uint flags)
{
return (void *)d_r_map_file(
f, size, offs, addr, prot,
(TEST(DR_MAP_PRIVATE, flags) ? MAP_FILE_COPY_ON_WRITE : 0) |
IF_WINDOWS((TEST(DR_MAP_IMAGE, flags) ? MAP_FILE_IMAGE : 0) |)
IF_UNIX((TEST(DR_MAP_FIXED, flags) ? MAP_FILE_FIXED : 0) |)(
TEST(DR_MAP_CACHE_REACHABLE, flags) ? MAP_FILE_REACHABLE : 0));
}
DR_API
bool
dr_unmap_file(void *map, size_t size)
{
dr_mem_info_t info;
CLIENT_ASSERT(ALIGNED(map, PAGE_SIZE), "dr_unmap_file: map is not page aligned");
if (!dr_query_memory_ex(map, &info) /* fail to query */ ||
info.type == DR_MEMTYPE_FREE /* not mapped file */) {
CLIENT_ASSERT(false, "dr_unmap_file: incorrect file map");
return false;
}
# ifdef WINDOWS
/* On Windows, the whole file will be unmapped instead, so we adjust
* the bound to make sure vm_areas are updated correctly.
*/
map = info.base_pc;
if (info.type == DR_MEMTYPE_IMAGE) {
size = get_allocation_size(map, NULL);
} else
size = info.size;
# endif
return d_r_unmap_file((byte *)map, size);
}
DR_API
void
dr_log(void *drcontext, uint mask, uint level, const char *fmt, ...)
{
# ifdef DEBUG
dcontext_t *dcontext = (dcontext_t *)drcontext;
va_list ap;
if (d_r_stats != NULL &&
((d_r_stats->logmask & mask) == 0 || d_r_stats->loglevel < level))
return;
va_start(ap, fmt);
if (dcontext != NULL)
do_file_write(dcontext->logfile, fmt, ap);
else
do_file_write(main_logfile, fmt, ap);
va_end(ap);
# else
return; /* no logging if not debug */
# endif
}
DR_API
/* Returns the log file for the drcontext thread.
* If drcontext is NULL, returns the main log file.
*/
file_t
dr_get_logfile(void *drcontext)
{
# ifdef DEBUG
dcontext_t *dcontext = (dcontext_t *)drcontext;
if (dcontext != NULL)
return dcontext->logfile;
else
return main_logfile;
# else
return INVALID_FILE;
# endif
}
DR_API
/* Returns true iff the -stderr_mask runtime option is non-zero, indicating
* that the user wants notification messages printed to stderr.
*/
bool
dr_is_notify_on(void)
{
return (dynamo_options.stderr_mask != 0);
}
# ifdef WINDOWS
DR_API file_t
dr_get_stdout_file(void)
{
return get_stdout_handle();
}
DR_API file_t
dr_get_stderr_file(void)
{
return get_stderr_handle();
}
DR_API file_t
dr_get_stdin_file(void)
{
return get_stdin_handle();
}
# endif
# ifdef PROGRAM_SHEPHERDING
DR_API void
dr_write_forensics_report(void *dcontext, file_t file,
dr_security_violation_type_t violation,
dr_security_violation_action_t action,
const char *violation_name)
{
security_violation_t sec_violation;
action_type_t sec_action;
switch (violation) {
case DR_RCO_STACK_VIOLATION: sec_violation = STACK_EXECUTION_VIOLATION; break;
case DR_RCO_HEAP_VIOLATION: sec_violation = HEAP_EXECUTION_VIOLATION; break;
case DR_RCT_RETURN_VIOLATION: sec_violation = RETURN_TARGET_VIOLATION; break;
case DR_RCT_INDIRECT_CALL_VIOLATION:
sec_violation = INDIRECT_CALL_RCT_VIOLATION;
break;
case DR_RCT_INDIRECT_JUMP_VIOLATION:
sec_violation = INDIRECT_JUMP_RCT_VIOLATION;
break;
default:
CLIENT_ASSERT(false,
"dr_write_forensics_report does not support "
"DR_UNKNOWN_VIOLATION or invalid violation types");
return;
}
switch (action) {
case DR_VIOLATION_ACTION_KILL_PROCESS: sec_action = ACTION_TERMINATE_PROCESS; break;
case DR_VIOLATION_ACTION_CONTINUE:
case DR_VIOLATION_ACTION_CONTINUE_CHANGED_CONTEXT:
sec_action = ACTION_CONTINUE;
break;
case DR_VIOLATION_ACTION_KILL_THREAD: sec_action = ACTION_TERMINATE_THREAD; break;
case DR_VIOLATION_ACTION_THROW_EXCEPTION: sec_action = ACTION_THROW_EXCEPTION; break;
default:
CLIENT_ASSERT(false, "dr_write_forensics_report invalid action selection");
return;
}
/* FIXME - could use a better message. */
append_diagnostics(file, action_message[sec_action], violation_name, sec_violation);
}
# endif /* PROGRAM_SHEPHERDING */
# ifdef WINDOWS
DR_API void
dr_messagebox(const char *fmt, ...)
{
dcontext_t *dcontext = NULL;
if (!standalone_library)
dcontext = get_thread_private_dcontext();
char msg[MAX_LOG_LENGTH];
wchar_t wmsg[MAX_LOG_LENGTH];
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, BUFFER_SIZE_ELEMENTS(msg), fmt, ap);
NULL_TERMINATE_BUFFER(msg);
snwprintf(wmsg, BUFFER_SIZE_ELEMENTS(wmsg), L"%S", msg);
NULL_TERMINATE_BUFFER(wmsg);
if (!standalone_library && IS_CLIENT_THREAD(dcontext))
dcontext->client_data->client_thread_safe_for_synch = true;
nt_messagebox(wmsg, debugbox_get_title());
if (!standalone_library && IS_CLIENT_THREAD(dcontext))
dcontext->client_data->client_thread_safe_for_synch = false;
va_end(ap);
}
static ssize_t
dr_write_to_console(bool to_stdout, const char *fmt, va_list ap)
{
bool res = true;
char msg[MAX_LOG_LENGTH];
uint written = 0;
int len;
HANDLE std;
CLIENT_ASSERT(dr_using_console(), "internal logic error");
ASSERT(priv_kernel32 != NULL && kernel32_WriteFile != NULL);
/* kernel32!GetStdHandle(STD_OUTPUT_HANDLE) == our PEB-based get_stdout_handle */
std = (to_stdout ? get_stdout_handle() : get_stderr_handle());
if (std == INVALID_HANDLE_VALUE)
return false;
len = vsnprintf(msg, BUFFER_SIZE_ELEMENTS(msg), fmt, ap);
/* Let user know if message was truncated */
if (len < 0 || len == BUFFER_SIZE_ELEMENTS(msg))
res = false;
NULL_TERMINATE_BUFFER(msg);
/* Make this routine work in all kinds of windows by going through
* kernel32!WriteFile, which will call WriteConsole for us.
*/
res =
res && kernel32_WriteFile(std, msg, (DWORD)strlen(msg), (LPDWORD)&written, NULL);
return (res ? written : 0);
}
static ssize_t
dr_write_to_console_varg(bool to_stdout, const char *fmt, ...)
{
va_list ap;
ssize_t res;
va_start(ap, fmt);
res = dr_write_to_console(to_stdout, fmt, ap);
va_end(ap);
return res;
}
DR_API
bool
dr_using_console(void)
{
bool res;
if (get_os_version() >= WINDOWS_VERSION_8) {
FILE_FS_DEVICE_INFORMATION device_info;
HANDLE herr = get_stderr_handle();
/* The handle is invalid iff it's a gui app and the parent is a console */
if (herr == INVALID_HANDLE_VALUE) {
module_data_t *app_kernel32 = dr_lookup_module_by_name("kernel32.dll");
if (privload_attach_parent_console(app_kernel32->start) == false) {
dr_free_module_data(app_kernel32);
return false;
}
dr_free_module_data(app_kernel32);
herr = get_stderr_handle();
}
if (nt_query_volume_info(herr, &device_info, sizeof(device_info),
FileFsDeviceInformation) == STATUS_SUCCESS) {
if (device_info.DeviceType == FILE_DEVICE_CONSOLE)
return true;
}
return false;
}
/* We detect cmd window using what kernel32!WriteFile uses: a handle
* having certain bits set.
*/
res = (((ptr_int_t)get_stderr_handle() & 0x10000003) == 0x3);
CLIENT_ASSERT(!res || get_os_version() < WINDOWS_VERSION_8,
"Please report this: Windows 8 does have old-style consoles!");
return res;
}
DR_API
bool
dr_enable_console_printing(void)
{
bool success = false;
/* b/c private loader sets cxt sw code up front based on whether have windows
* priv libs or not, this can only be called during client init()
*/
if (dynamo_initialized) {
CLIENT_ASSERT(false, "dr_enable_console_printing() must be called during init");
return false;
}
/* Direct writes to std handles work on win8+ (xref i#911) but we don't need
* a separate check as the handle is detected as a non-console handle.
*/
if (!dr_using_console())
return true;
if (!INTERNAL_OPTION(private_loader))
return false;
if (!print_to_console) {
if (priv_kernel32 == NULL) {
/* Not using load_shared_library() b/c it won't search paths
* for us. XXX: should add os-shared interface for
* locate-and-load.
*/
priv_kernel32 = (shlib_handle_t)locate_and_load_private_library(
"kernel32.dll", false /*!reachable*/);
}
if (priv_kernel32 != NULL && kernel32_WriteFile == NULL) {
module_data_t *app_kernel32 = dr_lookup_module_by_name("kernel32.dll");
kernel32_WriteFile =
(kernel32_WriteFile_t)lookup_library_routine(priv_kernel32, "WriteFile");
/* There is some problem in loading 32 bit kernel32.dll
* when 64 bit kernel32.dll is already loaded. If kernel32 is
* not loaded we can't call privload_console_share because it
* assumes kernel32 is loaded
*/
if (app_kernel32 == NULL) {
success = false;
} else {
success = privload_console_share(priv_kernel32, app_kernel32->start);
dr_free_module_data(app_kernel32);
}
}
/* We go ahead and cache whether dr_using_console(). If app really
* changes its console, client could call this routine again
* as a workaround. Seems unlikely: better to have better perf.
*/
print_to_console =
(priv_kernel32 != NULL && kernel32_WriteFile != NULL && success);
}
return print_to_console;
}
# endif /* WINDOWS */
DR_API void
dr_printf(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
# ifdef WINDOWS
if (print_to_console)
dr_write_to_console(true /*stdout*/, fmt, ap);
else
# endif
do_file_write(STDOUT, fmt, ap);
va_end(ap);
}
DR_API ssize_t
dr_vfprintf(file_t f, const char *fmt, va_list ap)
{
ssize_t written;
# ifdef WINDOWS
if ((f == STDOUT || f == STDERR) && print_to_console) {
written = dr_write_to_console(f == STDOUT, fmt, ap);
if (written <= 0)
written = -1;
} else
# endif
written = do_file_write(f, fmt, ap);
return written;
}
DR_API ssize_t
dr_fprintf(file_t f, const char *fmt, ...)
{
va_list ap;
ssize_t res;
va_start(ap, fmt);
res = dr_vfprintf(f, fmt, ap);
va_end(ap);
return res;
}
DR_API int
dr_snprintf(char *buf, size_t max, const char *fmt, ...)
{
int res;
va_list ap;
va_start(ap, fmt);
/* PR 219380: we use d_r_vsnprintf instead of ntdll._vsnprintf b/c the
* latter does not support floating point.
* Plus, d_r_vsnprintf returns -1 for > max chars (matching Windows
* behavior, but which Linux libc version does not do).
*/
res = d_r_vsnprintf(buf, max, fmt, ap);
va_end(ap);
return res;
}
DR_API int
dr_vsnprintf(char *buf, size_t max, const char *fmt, va_list ap)
{
return d_r_vsnprintf(buf, max, fmt, ap);
}
DR_API int
dr_snwprintf(wchar_t *buf, size_t max, const wchar_t *fmt, ...)
{
int res;
va_list ap;
va_start(ap, fmt);
res = d_r_vsnprintf_wide(buf, max, fmt, ap);
va_end(ap);
return res;
}
DR_API int
dr_vsnwprintf(wchar_t *buf, size_t max, const wchar_t *fmt, va_list ap)
{
return d_r_vsnprintf_wide(buf, max, fmt, ap);
}
DR_API int
dr_sscanf(const char *str, const char *fmt, ...)
{
int res;
va_list ap;
va_start(ap, fmt);
res = d_r_vsscanf(str, fmt, ap);
va_end(ap);
return res;
}
DR_API const char *
dr_get_token(const char *str, char *buf, size_t buflen)
{
/* We don't indicate whether any truncation happened. The
* reasoning is that this is meant to be used on a string of known
* size ahead of time, so the max size for any one token is known.
*/
const char *pos = str;
CLIENT_ASSERT(CHECK_TRUNCATE_TYPE_uint(buflen), "buflen too large");
if (d_r_parse_word(str, &pos, buf, (uint)buflen) == NULL)
return NULL;
else
return pos;
}
DR_API void
dr_print_instr(void *drcontext, file_t f, instr_t *instr, const char *msg)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_print_instr: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT || standalone_library,
"dr_print_instr: drcontext is invalid");
dr_fprintf(f, "%s " PFX " ", msg, instr_get_translation(instr));
instr_disassemble(dcontext, instr, f);
dr_fprintf(f, "\n");
}
DR_API void
dr_print_opnd(void *drcontext, file_t f, opnd_t opnd, const char *msg)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_print_opnd: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT || standalone_library,
"dr_print_opnd: drcontext is invalid");
dr_fprintf(f, "%s ", msg);
opnd_disassemble(dcontext, opnd, f);
dr_fprintf(f, "\n");
}
/***************************************************************************
* Thread support
*/
DR_API
/* Returns the DR context of the current thread */
void *
dr_get_current_drcontext(void)
{
dcontext_t *dcontext = get_thread_private_dcontext();
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
return (void *)dcontext;
}
DR_API thread_id_t
dr_get_thread_id(void *drcontext)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_get_thread_id: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT, "dr_get_thread_id: drcontext is invalid");
return dcontext->owning_thread;
}
# ifdef WINDOWS
/* Added for DrMem i#1254 */
DR_API HANDLE
dr_get_dr_thread_handle(void *drcontext)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_get_thread_id: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT, "dr_get_thread_id: drcontext is invalid");
return dcontext->thread_record->handle;
}
# endif
DR_API void *
dr_get_tls_field(void *drcontext)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_get_tls_field: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT, "dr_get_tls_field: drcontext is invalid");
return dcontext->client_data->user_field;
}
DR_API void
dr_set_tls_field(void *drcontext, void *value)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_set_tls_field: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT, "dr_set_tls_field: drcontext is invalid");
dcontext->client_data->user_field = value;
}
DR_API void *
dr_get_dr_segment_base(IN reg_id_t seg)
{
# ifdef AARCHXX
if (seg == dr_reg_stolen)
return os_get_dr_tls_base(get_thread_private_dcontext());
else
return NULL;
# else
return get_segment_base(seg);
# endif
}
DR_API
bool
dr_raw_tls_calloc(OUT reg_id_t *tls_register, OUT uint *offset, IN uint num_slots,
IN uint alignment)
{
CLIENT_ASSERT(tls_register != NULL, "dr_raw_tls_calloc: tls_register cannot be NULL");
CLIENT_ASSERT(offset != NULL, "dr_raw_tls_calloc: offset cannot be NULL");
*tls_register = IF_X86_ELSE(SEG_TLS, dr_reg_stolen);
if (num_slots == 0)
return true;
return os_tls_calloc(offset, num_slots, alignment);
}
DR_API
bool
dr_raw_tls_cfree(uint offset, uint num_slots)
{
if (num_slots == 0)
return true;
return os_tls_cfree(offset, num_slots);
}
DR_API
opnd_t
dr_raw_tls_opnd(void *drcontext, reg_id_t tls_register, uint tls_offs)
{
CLIENT_ASSERT(drcontext != NULL, "dr_raw_tls_opnd: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT, "dr_raw_tls_opnd: drcontext is invalid");
IF_X86_ELSE(
{
return opnd_create_far_base_disp_ex(tls_register, DR_REG_NULL, DR_REG_NULL, 0,
tls_offs, OPSZ_PTR,
/* modern processors don't want addr16
* prefixes
*/
false, true, false);
},
{ return OPND_CREATE_MEMPTR(tls_register, tls_offs); });
}
DR_API
void
dr_insert_read_raw_tls(void *drcontext, instrlist_t *ilist, instr_t *where,
reg_id_t tls_register, uint tls_offs, reg_id_t reg)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_insert_read_raw_tls: drcontext cannot be NULL");
CLIENT_ASSERT(reg_is_pointer_sized(reg),
"must use a pointer-sized general-purpose register");
IF_X86_ELSE(
{
MINSERT(
ilist, where,
INSTR_CREATE_mov_ld(dcontext, opnd_create_reg(reg),
dr_raw_tls_opnd(drcontext, tls_register, tls_offs)));
},
{
MINSERT(
ilist, where,
XINST_CREATE_load(dcontext, opnd_create_reg(reg),
dr_raw_tls_opnd(drcontext, tls_register, tls_offs)));
});
}
DR_API
void
dr_insert_write_raw_tls(void *drcontext, instrlist_t *ilist, instr_t *where,
reg_id_t tls_register, uint tls_offs, reg_id_t reg)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_insert_write_raw_tls: drcontext cannot be NULL");
CLIENT_ASSERT(reg_is_pointer_sized(reg),
"must use a pointer-sized general-purpose register");
IF_X86_ELSE(
{
MINSERT(ilist, where,
INSTR_CREATE_mov_st(
dcontext, dr_raw_tls_opnd(drcontext, tls_register, tls_offs),
opnd_create_reg(reg)));
},
{
MINSERT(ilist, where,
XINST_CREATE_store(dcontext,
dr_raw_tls_opnd(drcontext, tls_register, tls_offs),
opnd_create_reg(reg)));
});
}
DR_API
/* Current thread gives up its time quantum. */
void
dr_thread_yield(void)
{
dcontext_t *dcontext = get_thread_private_dcontext();
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
if (IS_CLIENT_THREAD(dcontext))
dcontext->client_data->client_thread_safe_for_synch = true;
else
dcontext->client_data->at_safe_to_terminate_syscall = true;
os_thread_yield();
if (IS_CLIENT_THREAD(dcontext))
dcontext->client_data->client_thread_safe_for_synch = false;
else
dcontext->client_data->at_safe_to_terminate_syscall = false;
}
DR_API
/* Current thread sleeps for time_ms milliseconds. */
void
dr_sleep(int time_ms)
{
dcontext_t *dcontext = get_thread_private_dcontext();
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
if (IS_CLIENT_THREAD(dcontext))
dcontext->client_data->client_thread_safe_for_synch = true;
else
dcontext->client_data->at_safe_to_terminate_syscall = true;
os_thread_sleep(time_ms);
if (IS_CLIENT_THREAD(dcontext))
dcontext->client_data->client_thread_safe_for_synch = false;
else
dcontext->client_data->at_safe_to_terminate_syscall = false;
}
# ifdef CLIENT_SIDELINE
DR_API
bool
dr_client_thread_set_suspendable(bool suspendable)
{
/* see notes in synch_with_all_threads() */
dcontext_t *dcontext = get_thread_private_dcontext();
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
if (!IS_CLIENT_THREAD(dcontext))
return false;
dcontext->client_data->suspendable = suspendable;
return true;
}
# endif
DR_API
bool
dr_suspend_all_other_threads_ex(OUT void ***drcontexts, OUT uint *num_suspended,
OUT uint *num_unsuspended, dr_suspend_flags_t flags)
{
uint out_suspended = 0, out_unsuspended = 0;
thread_record_t **threads;
int num_threads;
dcontext_t *my_dcontext = get_thread_private_dcontext();
int i;
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
CLIENT_ASSERT(OWN_NO_LOCKS(my_dcontext),
"dr_suspend_all_other_threads cannot be called while holding a lock");
CLIENT_ASSERT(drcontexts != NULL && num_suspended != NULL,
"dr_suspend_all_other_threads invalid params");
LOG(GLOBAL, LOG_FRAGMENT, 2,
"\ndr_suspend_all_other_threads: thread " TIDFMT " suspending all threads\n",
d_r_get_thread_id());
/* suspend all DR-controlled threads at safe locations */
if (!synch_with_all_threads(THREAD_SYNCH_SUSPENDED_VALID_MCONTEXT_OR_NO_XFER,
&threads, &num_threads, THREAD_SYNCH_NO_LOCKS_NO_XFER,
/* if we fail to suspend a thread (e.g., for
* privilege reasons), ignore and continue
*/
THREAD_SYNCH_SUSPEND_FAILURE_IGNORE)) {
LOG(GLOBAL, LOG_FRAGMENT, 2,
"\ndr_suspend_all_other_threads: failed to suspend every thread\n");
/* some threads may have been successfully suspended so we must return
* their info so they'll be resumed. I believe there is thus no
* scenario under which we return false.
*/
}
/* now we own the thread_initexit_lock */
CLIENT_ASSERT(OWN_MUTEX(&all_threads_synch_lock) && OWN_MUTEX(&thread_initexit_lock),
"internal locking error");
/* To avoid two passes we allocate the array now. It may be larger than
* necessary if we had suspend failures but taht's ok.
* We hide the threads num and array in extra slots.
*/
*drcontexts = (void **)global_heap_alloc(
(num_threads + 2) * sizeof(dcontext_t *) HEAPACCT(ACCT_THREAD_MGT));
for (i = 0; i < num_threads; i++) {
dcontext_t *dcontext = threads[i]->dcontext;
if (dcontext != NULL) { /* include my_dcontext here */
if (dcontext != my_dcontext) {
/* must translate BEFORE freeing any memory! */
if (!thread_synch_successful(threads[i])) {
out_unsuspended++;
} else if (is_thread_currently_native(threads[i]) &&
!TEST(DR_SUSPEND_NATIVE, flags)) {
out_unsuspended++;
} else if (thread_synch_state_no_xfer(dcontext)) {
/* FIXME: for all other synchall callers, the app
* context should be sitting in their mcontext, even
* though we can't safely get their native context and
* translate it.
*/
(*drcontexts)[out_suspended] = (void *)dcontext;
out_suspended++;
CLIENT_ASSERT(!dcontext->client_data->mcontext_in_dcontext,
"internal inconsistency in where mcontext is");
/* officially get_mcontext() doesn't always set pc: we do anyway */
get_mcontext(dcontext)->pc = dcontext->next_tag;
dcontext->client_data->mcontext_in_dcontext = true;
} else {
(*drcontexts)[out_suspended] = (void *)dcontext;
out_suspended++;
/* It's not safe to clobber the thread's mcontext with
* its own translation b/c for shared_syscall we store
* the continuation pc in the esi slot.
* We could translate here into heap-allocated memory,
* but some clients may just want to stop
* the world but not examine the threads, so we lazily
* translate in dr_get_mcontext().
*/
CLIENT_ASSERT(!dcontext->client_data->suspended,
"inconsistent usage of dr_suspend_all_other_threads");
CLIENT_ASSERT(dcontext->client_data->cur_mc == NULL,
"inconsistent usage of dr_suspend_all_other_threads");
dcontext->client_data->suspended = true;
}
}
}
}
/* Hide the two extra vars we need the client to pass back to us */
(*drcontexts)[out_suspended] = (void *)threads;
(*drcontexts)[out_suspended + 1] = (void *)(ptr_uint_t)num_threads;
*num_suspended = out_suspended;
if (num_unsuspended != NULL)
*num_unsuspended = out_unsuspended;
return true;
}
DR_API
bool
dr_suspend_all_other_threads(OUT void ***drcontexts, OUT uint *num_suspended,
OUT uint *num_unsuspended)
{
return dr_suspend_all_other_threads_ex(drcontexts, num_suspended, num_unsuspended, 0);
}
bool
dr_resume_all_other_threads(IN void **drcontexts, IN uint num_suspended)
{
thread_record_t **threads;
int num_threads;
uint i;
CLIENT_ASSERT(drcontexts != NULL, "dr_suspend_all_other_threads invalid params");
LOG(GLOBAL, LOG_FRAGMENT, 2, "dr_resume_all_other_threads\n");
threads = (thread_record_t **)drcontexts[num_suspended];
num_threads = (int)(ptr_int_t)drcontexts[num_suspended + 1];
for (i = 0; i < num_suspended; i++) {
dcontext_t *dcontext = (dcontext_t *)drcontexts[i];
if (dcontext->client_data->cur_mc != NULL) {
/* clear any cached mc from dr_get_mcontext_priv() */
heap_free(dcontext, dcontext->client_data->cur_mc,
sizeof(*dcontext->client_data->cur_mc) HEAPACCT(ACCT_CLIENT));
dcontext->client_data->cur_mc = NULL;
}
dcontext->client_data->suspended = false;
}
global_heap_free(drcontexts,
(num_threads + 2) * sizeof(dcontext_t *) HEAPACCT(ACCT_THREAD_MGT));
end_synch_with_all_threads(threads, num_threads, true /*resume*/);
return true;
}
DR_API
bool
dr_is_thread_native(void *drcontext)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "invalid param");
return is_thread_currently_native(dcontext->thread_record);
}
DR_API
bool
dr_retakeover_suspended_native_thread(void *drcontext)
{
bool res;
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "invalid param");
/* XXX: I don't quite see why I need to pop these 2 when I'm doing
* what a regular retakeover would do
*/
KSTOP_NOT_MATCHING_DC(dcontext, fcache_default);
KSTOP_NOT_MATCHING_DC(dcontext, dispatch_num_exits);
res = os_thread_take_over_suspended_native(dcontext);
return res;
}
# ifdef UNIX
DR_API
bool
dr_set_itimer(int which, uint millisec,
void (*func)(void *drcontext, dr_mcontext_t *mcontext))
{
dcontext_t *dcontext = get_thread_private_dcontext();
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
if (func == NULL && millisec != 0)
return false;
return set_itimer_callback(dcontext, which, millisec, NULL,
(void (*)(dcontext_t *, dr_mcontext_t *))func);
}
DR_API
uint
dr_get_itimer(int which)
{
dcontext_t *dcontext = get_thread_private_dcontext();
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
return get_itimer_frequency(dcontext, which);
}
# endif /* UNIX */
DR_API
void
dr_track_where_am_i(void)
{
track_where_am_i = true;
}
bool
should_track_where_am_i(void)
{
return track_where_am_i || DYNAMO_OPTION(profile_pcs);
}
DR_API
bool
dr_is_tracking_where_am_i(void)
{
return should_track_where_am_i();
}
DR_API
dr_where_am_i_t
dr_where_am_i(void *drcontext, app_pc pc, OUT void **tag_out)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "invalid param");
void *tag = NULL;
dr_where_am_i_t whereami = dcontext->whereami;
/* Further refine if pc is in the cache. */
if (whereami == DR_WHERE_FCACHE) {
fragment_t *fragment;
whereami = fcache_refine_whereami(dcontext, whereami, pc, &fragment);
if (fragment != NULL)
tag = fragment->tag;
}
if (tag_out != NULL)
*tag_out = tag;
return whereami;
}
#endif /* CLIENT_INTERFACE */
DR_API
void
instrlist_meta_fault_preinsert(instrlist_t *ilist, instr_t *where, instr_t *inst)
{
instr_set_meta_may_fault(inst, true);
instrlist_preinsert(ilist, where, inst);
}
DR_API
void
instrlist_meta_fault_postinsert(instrlist_t *ilist, instr_t *where, instr_t *inst)
{
instr_set_meta_may_fault(inst, true);
instrlist_postinsert(ilist, where, inst);
}
DR_API
void
instrlist_meta_fault_append(instrlist_t *ilist, instr_t *inst)
{
instr_set_meta_may_fault(inst, true);
instrlist_append(ilist, inst);
}
static void
convert_va_list_to_opnd(dcontext_t *dcontext, opnd_t **args, uint num_args, va_list ap)
{
uint i;
ASSERT(num_args > 0);
/* allocate at least one argument opnd */
/* we don't check for GLOBAL_DCONTEXT since DR internally calls this */
*args = HEAP_ARRAY_ALLOC(dcontext, opnd_t, num_args, ACCT_CLEANCALL, UNPROTECTED);
for (i = 0; i < num_args; i++) {
(*args)[i] = va_arg(ap, opnd_t);
CLIENT_ASSERT(opnd_is_valid((*args)[i]),
"Call argument: bad operand. Did you create a valid opnd_t?");
}
}
static void
free_va_opnd_list(dcontext_t *dcontext, uint num_args, opnd_t *args)
{
if (num_args != 0) {
HEAP_ARRAY_FREE(dcontext, args, opnd_t, num_args, ACCT_CLEANCALL, UNPROTECTED);
}
}
/* dr_insert_* are used by general DR */
/* Inserts a complete call to callee with the passed-in arguments */
void
dr_insert_call(void *drcontext, instrlist_t *ilist, instr_t *where, void *callee,
uint num_args, ...)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
opnd_t *args = NULL;
instr_t *label = INSTR_CREATE_label(drcontext);
dr_pred_type_t auto_pred = instrlist_get_auto_predicate(ilist);
va_list ap;
CLIENT_ASSERT(drcontext != NULL, "dr_insert_call: drcontext cannot be NULL");
instrlist_set_auto_predicate(ilist, DR_PRED_NONE);
#ifdef ARM
if (instr_predicate_is_cond(auto_pred)) {
/* auto_predicate is set, though we handle the clean call with a cbr
* because we require inserting instrumentation which modifies cpsr.
*/
MINSERT(ilist, where,
XINST_CREATE_jump_cond(drcontext, instr_invert_predicate(auto_pred),
opnd_create_instr(label)));
}
#endif
if (num_args != 0) {
va_start(ap, num_args);
convert_va_list_to_opnd(dcontext, &args, num_args, ap);
va_end(ap);
}
insert_meta_call_vargs(dcontext, ilist, where, META_CALL_RETURNS, vmcode_get_start(),
callee, num_args, args);
if (num_args != 0)
free_va_opnd_list(dcontext, num_args, args);
MINSERT(ilist, where, label);
instrlist_set_auto_predicate(ilist, auto_pred);
}
bool
dr_insert_call_ex(void *drcontext, instrlist_t *ilist, instr_t *where, byte *encode_pc,
void *callee, uint num_args, ...)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
opnd_t *args = NULL;
bool direct;
va_list ap;
CLIENT_ASSERT(drcontext != NULL, "dr_insert_call: drcontext cannot be NULL");
if (num_args != 0) {
va_start(ap, num_args);
convert_va_list_to_opnd(drcontext, &args, num_args, ap);
va_end(ap);
}
direct = insert_meta_call_vargs(dcontext, ilist, where, META_CALL_RETURNS, encode_pc,
callee, num_args, args);
if (num_args != 0)
free_va_opnd_list(dcontext, num_args, args);
return direct;
}
/* Not exported. Currently used for ARM to avoid storing to %lr. */
void
dr_insert_call_noreturn(void *drcontext, instrlist_t *ilist, instr_t *where, void *callee,
uint num_args, ...)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
opnd_t *args = NULL;
va_list ap;
CLIENT_ASSERT(drcontext != NULL, "dr_insert_call_noreturn: drcontext cannot be NULL");
CLIENT_ASSERT(instrlist_get_auto_predicate(ilist) == DR_PRED_NONE,
"Does not support auto-predication");
if (num_args != 0) {
va_start(ap, num_args);
convert_va_list_to_opnd(dcontext, &args, num_args, ap);
va_end(ap);
}
insert_meta_call_vargs(dcontext, ilist, where, 0, vmcode_get_start(), callee,
num_args, args);
if (num_args != 0)
free_va_opnd_list(dcontext, num_args, args);
}
/* Internal utility routine for inserting context save for a clean call.
* Returns the size of the data stored on the DR stack
* (in case the caller needs to align the stack pointer).
* XSP and XAX are modified by this call.
*/
static uint
prepare_for_call_ex(dcontext_t *dcontext, clean_call_info_t *cci, instrlist_t *ilist,
instr_t *where, byte *encode_pc)
{
instr_t *in;
uint dstack_offs;
in = (where == NULL) ? instrlist_last(ilist) : instr_get_prev(where);
dstack_offs = prepare_for_clean_call(dcontext, cci, ilist, where, encode_pc);
/* now go through and mark inserted instrs as meta */
if (in == NULL)
in = instrlist_first(ilist);
else
in = instr_get_next(in);
while (in != where) {
instr_set_meta(in);
in = instr_get_next(in);
}
return dstack_offs;
}
/* Internal utility routine for inserting context restore for a clean call. */
static void
cleanup_after_call_ex(dcontext_t *dcontext, clean_call_info_t *cci, instrlist_t *ilist,
instr_t *where, uint sizeof_param_area, byte *encode_pc)
{
instr_t *in;
in = (where == NULL) ? instrlist_last(ilist) : instr_get_prev(where);
if (sizeof_param_area > 0) {
/* clean up the parameter area */
CLIENT_ASSERT(sizeof_param_area <= 127,
"cleanup_after_call_ex: sizeof_param_area must be <= 127");
/* mark it meta down below */
instrlist_preinsert(ilist, where,
XINST_CREATE_add(dcontext, opnd_create_reg(REG_XSP),
OPND_CREATE_INT8(sizeof_param_area)));
}
cleanup_after_clean_call(dcontext, cci, ilist, where, encode_pc);
/* now go through and mark inserted instrs as meta */
if (in == NULL)
in = instrlist_first(ilist);
else
in = instr_get_next(in);
while (in != where) {
instr_set_meta(in);
in = instr_get_next(in);
}
}
/* Inserts a complete call to callee with the passed-in arguments, wrapped
* by an app save and restore.
*
* If "save_flags" includes DR_CLEANCALL_SAVE_FLOAT, saves the fp/mmx/sse state.
*
* NOTE : this routine clobbers TLS_XAX_SLOT and the XSP mcontext slot via
* dr_prepare_for_call(). We guarantee to clients that all other slots
* (except the XAX mcontext slot) will remain untouched.
*
* NOTE : dr_insert_cbr_instrumentation has assumption about the clean call
* instrumentation layout, changes to the clean call instrumentation may break
* dr_insert_cbr_instrumentation.
*/
void
dr_insert_clean_call_ex_varg(void *drcontext, instrlist_t *ilist, instr_t *where,
void *callee, dr_cleancall_save_t save_flags, uint num_args,
opnd_t *args)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
uint dstack_offs, pad = 0;
size_t buf_sz = 0;
clean_call_info_t cci; /* information for clean call insertion. */
bool save_fpstate = TEST(DR_CLEANCALL_SAVE_FLOAT, save_flags);
meta_call_flags_t call_flags = META_CALL_CLEAN | META_CALL_RETURNS;
byte *encode_pc;
instr_t *label = INSTR_CREATE_label(drcontext);
dr_pred_type_t auto_pred = instrlist_get_auto_predicate(ilist);
CLIENT_ASSERT(drcontext != NULL, "dr_insert_clean_call: drcontext cannot be NULL");
STATS_INC(cleancall_inserted);
LOG(THREAD, LOG_CLEANCALL, 2, "CLEANCALL: insert clean call to " PFX "\n", callee);
instrlist_set_auto_predicate(ilist, DR_PRED_NONE);
#ifdef ARM
if (instr_predicate_is_cond(auto_pred)) {
/* auto_predicate is set, though we handle the clean call with a cbr
* because we require inserting instrumentation which modifies cpsr.
*/
MINSERT(ilist, where,
XINST_CREATE_jump_cond(drcontext, instr_invert_predicate(auto_pred),
opnd_create_instr(label)));
}
#endif
/* analyze the clean call, return true if clean call can be inlined. */
if (analyze_clean_call(dcontext, &cci, where, callee, save_fpstate,
TEST(DR_CLEANCALL_ALWAYS_OUT_OF_LINE, save_flags), num_args,
args) &&
!TEST(DR_CLEANCALL_ALWAYS_OUT_OF_LINE, save_flags)) {
#ifdef CLIENT_INTERFACE
/* we can perform the inline optimization and return. */
STATS_INC(cleancall_inlined);
LOG(THREAD, LOG_CLEANCALL, 2, "CLEANCALL: inlined callee " PFX "\n", callee);
insert_inline_clean_call(dcontext, &cci, ilist, where, args);
MINSERT(ilist, where, label);
instrlist_set_auto_predicate(ilist, auto_pred);
return;
#else /* CLIENT_INTERFACE */
ASSERT_NOT_REACHED();
#endif /* CLIENT_INTERFACE */
}
/* honor requests from caller */
if (TEST(DR_CLEANCALL_NOSAVE_FLAGS, save_flags)) {
/* even if we remove flag saves we want to keep mcontext shape */
cci.preserve_mcontext = true;
cci.skip_save_flags = true;
/* we assume this implies DF should be 0 already */
cci.skip_clear_flags = true;
/* XXX: should also provide DR_CLEANCALL_NOSAVE_NONAFLAGS to
* preserve just arith flags on return from a call
*/
}
if (TESTANY(DR_CLEANCALL_NOSAVE_XMM | DR_CLEANCALL_NOSAVE_XMM_NONPARAM |
DR_CLEANCALL_NOSAVE_XMM_NONRET,
save_flags)) {
int i;
/* even if we remove xmm saves we want to keep mcontext shape */
cci.preserve_mcontext = true;
/* start w/ all */
#if defined(X64) && defined(WINDOWS)
cci.num_simd_skip = 6;
#else
/* all 8, 16 or 32 are scratch */
cci.num_simd_skip = proc_num_simd_registers();
cci.num_opmask_skip = proc_num_opmask_registers();
#endif
for (i = 0; i < cci.num_simd_skip; i++)
cci.simd_skip[i] = true;
for (i = 0; i < cci.num_opmask_skip; i++)
cci.opmask_skip[i] = true;
/* now remove those used for param/retval */
#ifdef X64
if (TEST(DR_CLEANCALL_NOSAVE_XMM_NONPARAM, save_flags)) {
/* xmm0-3 (-7 for linux) are used for params */
for (i = 0; i < IF_UNIX_ELSE(7, 3); i++)
cci.simd_skip[i] = false;
cci.num_simd_skip -= i;
}
if (TEST(DR_CLEANCALL_NOSAVE_XMM_NONRET, save_flags)) {
/* xmm0 (and xmm1 for linux) are used for retvals */
cci.simd_skip[0] = false;
cci.num_simd_skip--;
# ifdef UNIX
cci.simd_skip[1] = false;
cci.num_simd_skip--;
# endif
}
#endif
}
if (TEST(DR_CLEANCALL_INDIRECT, save_flags))
encode_pc = vmcode_unreachable_pc();
else
encode_pc = vmcode_get_start();
dstack_offs = prepare_for_call_ex(dcontext, &cci, ilist, where, encode_pc);
#ifdef X64
/* PR 218790: we assume that dr_prepare_for_call() leaves stack 16-byte
* aligned, which is what insert_meta_call_vargs requires. */
if (cci.should_align) {
CLIENT_ASSERT(ALIGNED(dstack_offs, 16), "internal error: bad stack alignment");
}
#endif
if (save_fpstate) {
/* save on the stack: xref PR 202669 on clients using more stack */
buf_sz = proc_fpstate_save_size();
/* we need 16-byte-alignment */
pad = ALIGN_FORWARD_UINT(dstack_offs, 16) - dstack_offs;
IF_X64(CLIENT_ASSERT(CHECK_TRUNCATE_TYPE_int(buf_sz + pad),
"dr_insert_clean_call: internal truncation error"));
MINSERT(ilist, where,
XINST_CREATE_sub(dcontext, opnd_create_reg(REG_XSP),
OPND_CREATE_INT32((int)(buf_sz + pad))));
dr_insert_save_fpstate(drcontext, ilist, where,
opnd_create_base_disp(REG_XSP, REG_NULL, 0, 0, OPSZ_512));
}
/* PR 302951: restore state if clean call args reference app memory.
* We use a hack here: this is the only instance where we mark as our-mangling
* but do not have a translation target set, which indicates to the restore
* routines that this is a clean call. If the client adds instrs in the middle
* translation will fail; if the client modifies any instr, the our-mangling
* flag will disappear and translation will fail.
*/
instrlist_set_our_mangling(ilist, true);
if (TEST(DR_CLEANCALL_RETURNS_TO_NATIVE, save_flags))
call_flags |= META_CALL_RETURNS_TO_NATIVE;
insert_meta_call_vargs(dcontext, ilist, where, call_flags, encode_pc, callee,
num_args, args);
instrlist_set_our_mangling(ilist, false);
if (save_fpstate) {
dr_insert_restore_fpstate(
drcontext, ilist, where,
opnd_create_base_disp(REG_XSP, REG_NULL, 0, 0, OPSZ_512));
MINSERT(ilist, where,
XINST_CREATE_add(dcontext, opnd_create_reg(REG_XSP),
OPND_CREATE_INT32(buf_sz + pad)));
}
cleanup_after_call_ex(dcontext, &cci, ilist, where, 0, encode_pc);
MINSERT(ilist, where, label);
instrlist_set_auto_predicate(ilist, auto_pred);
}
void
dr_insert_clean_call_ex(void *drcontext, instrlist_t *ilist, instr_t *where, void *callee,
dr_cleancall_save_t save_flags, uint num_args, ...)
{
opnd_t *args = NULL;
if (num_args != 0) {
va_list ap;
va_start(ap, num_args);
convert_va_list_to_opnd(drcontext, &args, num_args, ap);
va_end(ap);
}
dr_insert_clean_call_ex_varg(drcontext, ilist, where, callee, save_flags, num_args,
args);
if (num_args != 0)
free_va_opnd_list(drcontext, num_args, args);
}
DR_API
void
dr_insert_clean_call(void *drcontext, instrlist_t *ilist, instr_t *where, void *callee,
bool save_fpstate, uint num_args, ...)
{
dr_cleancall_save_t flags = (save_fpstate ? DR_CLEANCALL_SAVE_FLOAT : 0);
opnd_t *args = NULL;
if (num_args != 0) {
va_list ap;
va_start(ap, num_args);
convert_va_list_to_opnd(drcontext, &args, num_args, ap);
va_end(ap);
}
dr_insert_clean_call_ex_varg(drcontext, ilist, where, callee, flags, num_args, args);
if (num_args != 0)
free_va_opnd_list(drcontext, num_args, args);
}
/* Utility routine for inserting a clean call to an instrumentation routine
* Returns the size of the data stored on the DR stack (in case the caller
* needs to align the stack pointer). XSP and XAX are modified by this call.
*
* NOTE : this routine clobbers TLS_XAX_SLOT and the XSP mcontext slot via
* prepare_for_clean_call(). We guarantee to clients that all other slots
* (except the XAX mcontext slot) will remain untouched.
*/
DR_API uint
dr_prepare_for_call(void *drcontext, instrlist_t *ilist, instr_t *where)
{
CLIENT_ASSERT(drcontext != NULL, "dr_prepare_for_call: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_prepare_for_call: drcontext is invalid");
return prepare_for_call_ex((dcontext_t *)drcontext, NULL, ilist, where,
vmcode_get_start());
}
DR_API void
dr_cleanup_after_call(void *drcontext, instrlist_t *ilist, instr_t *where,
uint sizeof_param_area)
{
CLIENT_ASSERT(drcontext != NULL, "dr_cleanup_after_call: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_cleanup_after_call: drcontext is invalid");
cleanup_after_call_ex((dcontext_t *)drcontext, NULL, ilist, where, sizeof_param_area,
vmcode_get_start());
}
#ifdef CLIENT_INTERFACE
DR_API void
dr_swap_to_clean_stack(void *drcontext, instrlist_t *ilist, instr_t *where)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_swap_to_clean_stack: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_swap_to_clean_stack: drcontext is invalid");
/* PR 219620: For thread-shared, we need to get the dcontext
* dynamically rather than use the constant passed in here.
*/
if (SCRATCH_ALWAYS_TLS()) {
MINSERT(ilist, where,
instr_create_save_to_tls(dcontext, SCRATCH_REG0, TLS_REG0_SLOT));
insert_get_mcontext_base(dcontext, ilist, where, SCRATCH_REG0);
/* save app xsp, and then bring in dstack to xsp */
MINSERT(
ilist, where,
instr_create_save_to_dc_via_reg(dcontext, SCRATCH_REG0, REG_XSP, XSP_OFFSET));
/* DSTACK_OFFSET isn't within the upcontext so if it's separate this won't
* work right. FIXME - the dcontext accessing routines are a mess of shared
* vs. no shared support, separate context vs. no separate context support etc. */
ASSERT_NOT_IMPLEMENTED(!TEST(SELFPROT_DCONTEXT, dynamo_options.protect_mask));
MINSERT(ilist, where,
instr_create_restore_from_dc_via_reg(dcontext, SCRATCH_REG0, REG_XSP,
DSTACK_OFFSET));
MINSERT(ilist, where,
instr_create_restore_from_tls(dcontext, SCRATCH_REG0, TLS_REG0_SLOT));
} else {
MINSERT(ilist, where,
instr_create_save_to_dcontext(dcontext, REG_XSP, XSP_OFFSET));
MINSERT(ilist, where, instr_create_restore_dynamo_stack(dcontext));
}
}
DR_API void
dr_restore_app_stack(void *drcontext, instrlist_t *ilist, instr_t *where)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_restore_app_stack: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_restore_app_stack: drcontext is invalid");
/* restore stack */
if (SCRATCH_ALWAYS_TLS()) {
/* use the register we're about to clobber as scratch space */
insert_get_mcontext_base(dcontext, ilist, where, REG_XSP);
MINSERT(
ilist, where,
instr_create_restore_from_dc_via_reg(dcontext, REG_XSP, REG_XSP, XSP_OFFSET));
} else {
MINSERT(ilist, where,
instr_create_restore_from_dcontext(dcontext, REG_XSP, XSP_OFFSET));
}
}
# define SPILL_SLOT_TLS_MAX 2
# define NUM_TLS_SPILL_SLOTS (SPILL_SLOT_TLS_MAX + 1)
# define NUM_SPILL_SLOTS (SPILL_SLOT_MAX + 1)
/* The three tls slots we make available to clients. We reserve TLS_REG0_SLOT for our
* own use in dr convenience routines. Note the +1 is because the max is an array index
* (so zero based) while array size is number of slots. We don't need to +1 in
* SPILL_SLOT_MC_REG because subtracting SPILL_SLOT_TLS_MAX already accounts for it. */
static const ushort SPILL_SLOT_TLS_OFFS[NUM_TLS_SPILL_SLOTS] = { TLS_REG3_SLOT,
TLS_REG2_SLOT,
TLS_REG1_SLOT };
static const reg_id_t SPILL_SLOT_MC_REG[NUM_SPILL_SLOTS - NUM_TLS_SPILL_SLOTS] = {
# ifdef X86
/* The dcontext reg slots we make available to clients. We reserve XAX and XSP
* for our own use in dr convenience routines. */
# ifdef X64
REG_R15, REG_R14, REG_R13, REG_R12, REG_R11, REG_R10, REG_R9, REG_R8,
# endif
REG_XDI, REG_XSI, REG_XBP, REG_XDX, REG_XCX, REG_XBX
# elif defined(AARCHXX)
/* DR_REG_R0 is not used here. See prepare_for_clean_call. */
DR_REG_R6, DR_REG_R5, DR_REG_R4, DR_REG_R3, DR_REG_R2, DR_REG_R1
# endif /* X86/ARM */
};
DR_API void
dr_save_reg(void *drcontext, instrlist_t *ilist, instr_t *where, reg_id_t reg,
dr_spill_slot_t slot)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_save_reg: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT, "dr_save_reg: drcontext is invalid");
CLIENT_ASSERT(slot <= SPILL_SLOT_MAX, "dr_save_reg: invalid spill slot selection");
CLIENT_ASSERT(reg_is_pointer_sized(reg), "dr_save_reg requires pointer-sized gpr");
if (slot <= SPILL_SLOT_TLS_MAX) {
ushort offs = os_tls_offset(SPILL_SLOT_TLS_OFFS[slot]);
MINSERT(ilist, where,
XINST_CREATE_store(dcontext, opnd_create_tls_slot(offs),
opnd_create_reg(reg)));
} else {
reg_id_t reg_slot = SPILL_SLOT_MC_REG[slot - NUM_TLS_SPILL_SLOTS];
int offs = opnd_get_reg_dcontext_offs(reg_slot);
if (SCRATCH_ALWAYS_TLS()) {
/* PR 219620: For thread-shared, we need to get the dcontext
* dynamically rather than use the constant passed in here.
*/
reg_id_t tmp = (reg == SCRATCH_REG0) ? SCRATCH_REG1 : SCRATCH_REG0;
MINSERT(ilist, where, instr_create_save_to_tls(dcontext, tmp, TLS_REG0_SLOT));
insert_get_mcontext_base(dcontext, ilist, where, tmp);
MINSERT(ilist, where,
instr_create_save_to_dc_via_reg(dcontext, tmp, reg, offs));
MINSERT(ilist, where,
instr_create_restore_from_tls(dcontext, tmp, TLS_REG0_SLOT));
} else {
MINSERT(ilist, where, instr_create_save_to_dcontext(dcontext, reg, offs));
}
}
}
/* if want to save 8 or 16-bit reg, must pass in containing ptr-sized reg! */
DR_API void
dr_restore_reg(void *drcontext, instrlist_t *ilist, instr_t *where, reg_id_t reg,
dr_spill_slot_t slot)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_restore_reg: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT, "dr_restore_reg: drcontext is invalid");
CLIENT_ASSERT(slot <= SPILL_SLOT_MAX, "dr_restore_reg: invalid spill slot selection");
CLIENT_ASSERT(reg_is_pointer_sized(reg),
"dr_restore_reg requires a pointer-sized gpr");
if (slot <= SPILL_SLOT_TLS_MAX) {
ushort offs = os_tls_offset(SPILL_SLOT_TLS_OFFS[slot]);
MINSERT(ilist, where,
XINST_CREATE_load(dcontext, opnd_create_reg(reg),
opnd_create_tls_slot(offs)));
} else {
reg_id_t reg_slot = SPILL_SLOT_MC_REG[slot - NUM_TLS_SPILL_SLOTS];
int offs = opnd_get_reg_dcontext_offs(reg_slot);
if (SCRATCH_ALWAYS_TLS()) {
/* PR 219620: For thread-shared, we need to get the dcontext
* dynamically rather than use the constant passed in here.
*/
/* use the register we're about to clobber as scratch space */
insert_get_mcontext_base(dcontext, ilist, where, reg);
MINSERT(ilist, where,
instr_create_restore_from_dc_via_reg(dcontext, reg, reg, offs));
} else {
MINSERT(ilist, where,
instr_create_restore_from_dcontext(dcontext, reg, offs));
}
}
}
DR_API dr_spill_slot_t
dr_max_opnd_accessible_spill_slot()
{
if (SCRATCH_ALWAYS_TLS())
return SPILL_SLOT_TLS_MAX;
else
return SPILL_SLOT_MAX;
}
/* creates an opnd to access spill slot slot, slot must be <=
* dr_max_opnd_accessible_spill_slot() */
opnd_t
reg_spill_slot_opnd(dcontext_t *dcontext, dr_spill_slot_t slot)
{
if (slot <= SPILL_SLOT_TLS_MAX) {
ushort offs = os_tls_offset(SPILL_SLOT_TLS_OFFS[slot]);
return opnd_create_tls_slot(offs);
} else {
reg_id_t reg_slot = SPILL_SLOT_MC_REG[slot - NUM_TLS_SPILL_SLOTS];
int offs = opnd_get_reg_dcontext_offs(reg_slot);
ASSERT(!SCRATCH_ALWAYS_TLS()); /* client assert above should catch */
return opnd_create_dcontext_field(dcontext, offs);
}
}
DR_API
opnd_t
dr_reg_spill_slot_opnd(void *drcontext, dr_spill_slot_t slot)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL, "dr_reg_spill_slot_opnd: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_reg_spill_slot_opnd: drcontext is invalid");
CLIENT_ASSERT(slot <= dr_max_opnd_accessible_spill_slot(),
"dr_reg_spill_slot_opnd: slot must be less than "
"dr_max_opnd_accessible_spill_slot()");
return reg_spill_slot_opnd(dcontext, slot);
}
DR_API
/* used to read a saved register spill slot from a clean call or a restore_state_event */
reg_t
dr_read_saved_reg(void *drcontext, dr_spill_slot_t slot)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
CLIENT_ASSERT(drcontext != NULL, "dr_read_saved_reg: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_read_saved_reg: drcontext is invalid");
CLIENT_ASSERT(slot <= SPILL_SLOT_MAX,
"dr_read_saved_reg: invalid spill slot selection");
/* We do allow drcontext to not belong to the current thread, for state restoration
* during synchall and other scenarios.
*/
if (slot <= SPILL_SLOT_TLS_MAX) {
ushort offs = SPILL_SLOT_TLS_OFFS[slot];
return *(reg_t *)(((byte *)&dcontext->local_state->spill_space) + offs);
} else {
reg_id_t reg_slot = SPILL_SLOT_MC_REG[slot - NUM_TLS_SPILL_SLOTS];
return reg_get_value_priv(reg_slot, get_mcontext(dcontext));
}
}
DR_API
/* used to write a saved register spill slot from a clean call */
void
dr_write_saved_reg(void *drcontext, dr_spill_slot_t slot, reg_t value)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
CLIENT_ASSERT(drcontext != NULL, "dr_write_saved_reg: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_write_saved_reg: drcontext is invalid");
CLIENT_ASSERT(slot <= SPILL_SLOT_MAX,
"dr_write_saved_reg: invalid spill slot selection");
/* We do allow drcontext to not belong to the current thread, for state restoration
* during synchall and other scenarios.
*/
if (slot <= SPILL_SLOT_TLS_MAX) {
ushort offs = SPILL_SLOT_TLS_OFFS[slot];
*(reg_t *)(((byte *)&dcontext->local_state->spill_space) + offs) = value;
} else {
reg_id_t reg_slot = SPILL_SLOT_MC_REG[slot - NUM_TLS_SPILL_SLOTS];
reg_set_value_priv(reg_slot, get_mcontext(dcontext), value);
}
}
DR_API
/**
* Inserts into ilist prior to "where" instruction(s) to read into the
* general-purpose full-size register reg from the user-controlled drcontext
* field for this thread.
*/
void
dr_insert_read_tls_field(void *drcontext, instrlist_t *ilist, instr_t *where,
reg_id_t reg)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL,
"dr_insert_read_tls_field: drcontext cannot be NULL");
CLIENT_ASSERT(reg_is_pointer_sized(reg),
"must use a pointer-sized general-purpose register");
if (SCRATCH_ALWAYS_TLS()) {
/* For thread-shared, since reg must be general-purpose we can
* use it as a base pointer (repeatedly). Plus it's already dead.
*/
MINSERT(ilist, where,
instr_create_restore_from_tls(dcontext, reg, TLS_DCONTEXT_SLOT));
MINSERT(
ilist, where,
instr_create_restore_from_dc_via_reg(dcontext, reg, reg, CLIENT_DATA_OFFSET));
MINSERT(ilist, where,
XINST_CREATE_load(
dcontext, opnd_create_reg(reg),
OPND_CREATE_MEMPTR(reg, offsetof(client_data_t, user_field))));
} else {
MINSERT(ilist, where,
XINST_CREATE_load(
dcontext, opnd_create_reg(reg),
OPND_CREATE_ABSMEM(&dcontext->client_data->user_field, OPSZ_PTR)));
}
}
DR_API
/**
* Inserts into ilist prior to "where" instruction(s) to write the
* general-purpose full-size register reg to the user-controlled drcontext field
* for this thread.
*/
void
dr_insert_write_tls_field(void *drcontext, instrlist_t *ilist, instr_t *where,
reg_id_t reg)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL,
"dr_insert_write_tls_field: drcontext cannot be NULL");
CLIENT_ASSERT(reg_is_pointer_sized(reg),
"must use a pointer-sized general-purpose register");
if (SCRATCH_ALWAYS_TLS()) {
reg_id_t spill = SCRATCH_REG0;
if (reg == spill) /* don't need sub-reg test b/c we know it's pointer-sized */
spill = SCRATCH_REG1;
MINSERT(ilist, where, instr_create_save_to_tls(dcontext, spill, TLS_REG0_SLOT));
MINSERT(ilist, where,
instr_create_restore_from_tls(dcontext, spill, TLS_DCONTEXT_SLOT));
MINSERT(ilist, where,
instr_create_restore_from_dc_via_reg(dcontext, spill, spill,
CLIENT_DATA_OFFSET));
MINSERT(ilist, where,
XINST_CREATE_store(
dcontext,
OPND_CREATE_MEMPTR(spill, offsetof(client_data_t, user_field)),
opnd_create_reg(reg)));
MINSERT(ilist, where,
instr_create_restore_from_tls(dcontext, spill, TLS_REG0_SLOT));
} else {
MINSERT(ilist, where,
XINST_CREATE_store(
dcontext,
OPND_CREATE_ABSMEM(&dcontext->client_data->user_field, OPSZ_PTR),
opnd_create_reg(reg)));
}
}
DR_API void
dr_save_arith_flags(void *drcontext, instrlist_t *ilist, instr_t *where,
dr_spill_slot_t slot)
{
reg_id_t reg = IF_X86_ELSE(DR_REG_XAX, DR_REG_R0);
CLIENT_ASSERT(IF_X86_ELSE(true, false), "X86-only");
CLIENT_ASSERT(drcontext != NULL, "dr_save_arith_flags: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_save_arith_flags: drcontext is invalid");
CLIENT_ASSERT(slot <= SPILL_SLOT_MAX,
"dr_save_arith_flags: invalid spill slot selection");
dr_save_reg(drcontext, ilist, where, reg, slot);
dr_save_arith_flags_to_reg(drcontext, ilist, where, reg);
}
DR_API void
dr_restore_arith_flags(void *drcontext, instrlist_t *ilist, instr_t *where,
dr_spill_slot_t slot)
{
reg_id_t reg = IF_X86_ELSE(DR_REG_XAX, DR_REG_R0);
CLIENT_ASSERT(IF_X86_ELSE(true, false), "X86-only");
CLIENT_ASSERT(drcontext != NULL, "dr_restore_arith_flags: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_restore_arith_flags: drcontext is invalid");
CLIENT_ASSERT(slot <= SPILL_SLOT_MAX,
"dr_restore_arith_flags: invalid spill slot selection");
dr_restore_arith_flags_from_reg(drcontext, ilist, where, reg);
dr_restore_reg(drcontext, ilist, where, reg, slot);
}
DR_API void
dr_save_arith_flags_to_xax(void *drcontext, instrlist_t *ilist, instr_t *where)
{
reg_id_t reg = IF_X86_ELSE(DR_REG_XAX, DR_REG_R0);
CLIENT_ASSERT(IF_X86_ELSE(true, false), "X86-only");
dr_save_arith_flags_to_reg(drcontext, ilist, where, reg);
}
DR_API void
dr_restore_arith_flags_from_xax(void *drcontext, instrlist_t *ilist, instr_t *where)
{
reg_id_t reg = IF_X86_ELSE(DR_REG_XAX, DR_REG_R0);
CLIENT_ASSERT(IF_X86_ELSE(true, false), "X86-only");
dr_restore_arith_flags_from_reg(drcontext, ilist, where, reg);
}
DR_API void
dr_save_arith_flags_to_reg(void *drcontext, instrlist_t *ilist, instr_t *where,
reg_id_t reg)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL,
"dr_save_arith_flags_to_reg: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_save_arith_flags_to_reg: drcontext is invalid");
# ifdef X86
CLIENT_ASSERT(reg == DR_REG_XAX,
"only xax should be used for save arith flags in X86");
/* flag saving code:
* lahf
* seto al
*/
MINSERT(ilist, where, INSTR_CREATE_lahf(dcontext));
MINSERT(ilist, where, INSTR_CREATE_setcc(dcontext, OP_seto, opnd_create_reg(REG_AL)));
# elif defined(ARM)
/* flag saving code: mrs reg, cpsr */
MINSERT(
ilist, where,
INSTR_CREATE_mrs(dcontext, opnd_create_reg(reg), opnd_create_reg(DR_REG_CPSR)));
# elif defined(AARCH64)
/* flag saving code: mrs reg, nzcv */
MINSERT(
ilist, where,
INSTR_CREATE_mrs(dcontext, opnd_create_reg(reg), opnd_create_reg(DR_REG_NZCV)));
# endif /* X86/ARM/AARCH64 */
}
DR_API void
dr_restore_arith_flags_from_reg(void *drcontext, instrlist_t *ilist, instr_t *where,
reg_id_t reg)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL,
"dr_restore_arith_flags_from_reg: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_restore_arith_flags_from_reg: drcontext is invalid");
# ifdef X86
CLIENT_ASSERT(reg == DR_REG_XAX,
"only xax should be used for save arith flags in X86");
/* flag restoring code:
* add 0x7f,%al
* sahf
*/
/* do an add such that OF will be set only if seto set
* the LSB of AL to 1
*/
MINSERT(ilist, where,
INSTR_CREATE_add(dcontext, opnd_create_reg(REG_AL), OPND_CREATE_INT8(0x7f)));
MINSERT(ilist, where, INSTR_CREATE_sahf(dcontext));
# elif defined(ARM)
/* flag restoring code: mrs reg, apsr_nzcvqg */
MINSERT(ilist, where,
INSTR_CREATE_msr(dcontext, opnd_create_reg(DR_REG_CPSR),
OPND_CREATE_INT_MSR_NZCVQG(), opnd_create_reg(reg)));
# elif defined(AARCH64)
/* flag restoring code: mrs reg, nzcv */
MINSERT(
ilist, where,
INSTR_CREATE_msr(dcontext, opnd_create_reg(DR_REG_NZCV), opnd_create_reg(reg)));
# endif /* X86/ARM/AARCH64 */
}
/* providing functionality of old -instr_calls and -instr_branches flags
*
* NOTE : this routine clobbers TLS_XAX_SLOT and the XSP mcontext slot via
* dr_insert_clean_call(). We guarantee to clients that all other slots
* (except the XAX mcontext slot) will remain untouched.
*/
DR_API void
dr_insert_call_instrumentation(void *drcontext, instrlist_t *ilist, instr_t *instr,
void *callee)
{
ptr_uint_t target, address;
CLIENT_ASSERT(drcontext != NULL,
"dr_insert_call_instrumentation: drcontext cannot be NULL");
address = (ptr_uint_t)instr_get_translation(instr);
/* dr_insert_ubr_instrumentation() uses this function */
CLIENT_ASSERT(instr_is_call(instr) || instr_is_ubr(instr),
"dr_insert_{ubr,call}_instrumentation must be applied to a ubr");
CLIENT_ASSERT(address != 0,
"dr_insert_{ubr,call}_instrumentation: can't determine app address");
if (opnd_is_pc(instr_get_target(instr))) {
if (opnd_is_far_pc(instr_get_target(instr))) {
/* FIXME: handle far pc */
CLIENT_ASSERT(false,
"dr_insert_{ubr,call}_instrumentation: far pc not supported");
}
/* In release build for far pc keep going assuming 0 base */
target = (ptr_uint_t)opnd_get_pc(instr_get_target(instr));
} else if (opnd_is_instr(instr_get_target(instr))) {
instr_t *tgt = opnd_get_instr(instr_get_target(instr));
target = (ptr_uint_t)instr_get_translation(tgt);
CLIENT_ASSERT(target != 0,
"dr_insert_{ubr,call}_instrumentation: unknown target");
if (opnd_is_far_instr(instr_get_target(instr))) {
/* FIXME: handle far instr */
CLIENT_ASSERT(false,
"dr_insert_{ubr,call}_instrumentation: far instr "
"not supported");
}
} else {
CLIENT_ASSERT(false, "dr_insert_{ubr,call}_instrumentation: unknown target");
target = 0;
}
dr_insert_clean_call(drcontext, ilist, instr, callee, false /*no fpstate*/, 2,
/* address of call is 1st parameter */
OPND_CREATE_INTPTR(address),
/* call target is 2nd parameter */
OPND_CREATE_INTPTR(target));
}
/* NOTE : this routine clobbers TLS_XAX_SLOT and the XSP mcontext slot via
* dr_insert_clean_call(). We guarantee to clients that all other slots
* (except the XAX mcontext slot) will remain untouched. Since we need another
* tls spill slot in this routine we require the caller to give us one. */
DR_API void
dr_insert_mbr_instrumentation(void *drcontext, instrlist_t *ilist, instr_t *instr,
void *callee, dr_spill_slot_t scratch_slot)
{
# ifdef X86
dcontext_t *dcontext = (dcontext_t *)drcontext;
ptr_uint_t address = (ptr_uint_t)instr_get_translation(instr);
opnd_t tls_opnd;
instr_t *newinst;
reg_id_t reg_target;
/* PR 214051: dr_insert_mbr_instrumentation() broken with -indcall2direct */
CLIENT_ASSERT(!DYNAMO_OPTION(indcall2direct),
"dr_insert_mbr_instrumentation not supported with -opt_speed");
CLIENT_ASSERT(drcontext != NULL,
"dr_insert_mbr_instrumentation: drcontext cannot be NULL");
CLIENT_ASSERT(address != 0,
"dr_insert_mbr_instrumentation: can't determine app address");
CLIENT_ASSERT(instr_is_mbr(instr),
"dr_insert_mbr_instrumentation must be applied to an mbr");
/* We need a TLS spill slot to use. We can use any tls slot that is opnd
* accessible. */
CLIENT_ASSERT(scratch_slot <= dr_max_opnd_accessible_spill_slot(),
"dr_insert_mbr_instrumentation: scratch_slot must be less than "
"dr_max_opnd_accessible_spill_slot()");
/* It is possible for mbr instruction to use XCX register, so we have
* to use an unsed register.
*/
for (reg_target = REG_XAX; reg_target <= REG_XBX; reg_target++) {
if (!instr_uses_reg(instr, reg_target))
break;
}
/* PR 240265: we disallow clients to add post-mbr instrumentation, so we
* avoid doing that here even though it's a little less efficient since
* our mbr mangling will re-grab the target.
* We could keep it post-mbr and mark it w/ a special flag so we allow
* our own but not clients' instrumentation post-mbr: but then we
* hit post-syscall issues for wow64 where post-mbr equals post-syscall
* (PR 240258: though we might solve that some other way).
*/
/* Note that since we're using a client exposed slot we know it will be
* preserved across the clean call. */
tls_opnd = dr_reg_spill_slot_opnd(drcontext, scratch_slot);
newinst = XINST_CREATE_store(dcontext, tls_opnd, opnd_create_reg(reg_target));
/* PR 214962: ensure we'll properly translate the de-ref of app
* memory by marking the spill and de-ref as INSTR_OUR_MANGLING.
*/
instr_set_our_mangling(newinst, true);
MINSERT(ilist, instr, newinst);
if (instr_is_return(instr)) {
/* the retaddr operand is always the final source for all OP_ret* instrs */
opnd_t retaddr = instr_get_src(instr, instr_num_srcs(instr) - 1);
opnd_size_t sz = opnd_get_size(retaddr);
/* Even for far ret and iret, retaddr is at TOS
* but operand size needs to be set to stack size
* since iret pops more than return address.
*/
opnd_set_size(&retaddr, OPSZ_STACK);
newinst = instr_create_1dst_1src(dcontext, sz == OPSZ_2 ? OP_movzx : OP_mov_ld,
opnd_create_reg(reg_target), retaddr);
} else {
/* call* or jmp* */
opnd_t src = instr_get_src(instr, 0);
opnd_size_t sz = opnd_get_size(src);
/* if a far cti, we can't fit it into a register: asserted above.
* in release build we'll get just the address here.
*/
if (instr_is_far_cti(instr)) {
if (sz == OPSZ_10) {
sz = OPSZ_8;
} else if (sz == OPSZ_6) {
sz = OPSZ_4;
# ifdef X64
reg_target = reg_64_to_32(reg_target);
# endif
} else /* target has OPSZ_4 */ {
sz = OPSZ_2;
}
opnd_set_size(&src, sz);
}
# ifdef UNIX
/* xref i#1834 the problem with fs and gs segment is a general problem
* on linux, this fix is specific for mbr_instrumentation, but a general
* solution is needed.
*/
if (INTERNAL_OPTION(mangle_app_seg) && opnd_is_far_base_disp(src)) {
src = mangle_seg_ref_opnd(dcontext, ilist, instr, src, reg_target);
}
# endif
newinst = instr_create_1dst_1src(dcontext, sz == OPSZ_2 ? OP_movzx : OP_mov_ld,
opnd_create_reg(reg_target), src);
}
instr_set_our_mangling(newinst, true);
MINSERT(ilist, instr, newinst);
/* Now we want the true app state saved, for dr_get_mcontext().
* We specially recognize our OP_xchg as a restore in
* instr_is_reg_spill_or_restore().
*/
MINSERT(ilist, instr,
INSTR_CREATE_xchg(dcontext, tls_opnd, opnd_create_reg(reg_target)));
dr_insert_clean_call(drcontext, ilist, instr, callee, false /*no fpstate*/, 2,
/* address of mbr is 1st param */
OPND_CREATE_INTPTR(address),
/* indirect target (in tls, xchg-d from ecx) is 2nd param */
tls_opnd);
# elif defined(ARM)
/* i#1551: NYI on ARM.
* Also, we may want to split these out into arch/{x86,arm}/ files
*/
ASSERT_NOT_IMPLEMENTED(false);
# endif /* X86/ARM */
}
/* NOTE : this routine clobbers TLS_XAX_SLOT and the XSP mcontext slot via
* dr_insert_clean_call(). We guarantee to clients that all other slots
* (except the XAX mcontext slot) will remain untouched.
*
* NOTE : this routine has assumption about the layout of the clean call,
* so any change to clean call instrumentation layout may break this routine.
*/
static void
dr_insert_cbr_instrumentation_help(void *drcontext, instrlist_t *ilist, instr_t *instr,
void *callee, bool has_fallthrough, opnd_t user_data)
{
# ifdef X86
dcontext_t *dcontext = (dcontext_t *)drcontext;
ptr_uint_t address, target;
int opc;
instr_t *app_flags_ok;
bool out_of_line_switch = false;
;
CLIENT_ASSERT(drcontext != NULL,
"dr_insert_cbr_instrumentation: drcontext cannot be NULL");
address = (ptr_uint_t)instr_get_translation(instr);
CLIENT_ASSERT(address != 0,
"dr_insert_cbr_instrumentation: can't determine app address");
CLIENT_ASSERT(instr_is_cbr(instr),
"dr_insert_cbr_instrumentation must be applied to a cbr");
CLIENT_ASSERT(opnd_is_near_pc(instr_get_target(instr)) ||
opnd_is_near_instr(instr_get_target(instr)),
"dr_insert_cbr_instrumentation: target opnd must be a near pc or "
"near instr");
if (opnd_is_near_pc(instr_get_target(instr)))
target = (ptr_uint_t)opnd_get_pc(instr_get_target(instr));
else if (opnd_is_near_instr(instr_get_target(instr))) {
instr_t *tgt = opnd_get_instr(instr_get_target(instr));
target = (ptr_uint_t)instr_get_translation(tgt);
CLIENT_ASSERT(target != 0, "dr_insert_cbr_instrumentation: unknown target");
} else {
CLIENT_ASSERT(false, "dr_insert_cbr_instrumentation: unknown target");
target = 0;
}
app_flags_ok = instr_get_prev(instr);
if (has_fallthrough) {
ptr_uint_t fallthrough = address + instr_length(drcontext, instr);
CLIENT_ASSERT(!opnd_uses_reg(user_data, DR_REG_XBX),
"register ebx should not be used");
CLIENT_ASSERT(fallthrough > address, "wrong fallthrough address");
dr_insert_clean_call(drcontext, ilist, instr, callee, false /*no fpstate*/, 5,
/* push address of mbr onto stack as 1st parameter */
OPND_CREATE_INTPTR(address),
/* target is 2nd parameter */
OPND_CREATE_INTPTR(target),
/* fall-throug is 3rd parameter */
OPND_CREATE_INTPTR(fallthrough),
/* branch direction (put in ebx below) is 4th parameter */
opnd_create_reg(REG_XBX),
/* user defined data is 5th parameter */
opnd_is_null(user_data) ? OPND_CREATE_INT32(0) : user_data);
} else {
dr_insert_clean_call(drcontext, ilist, instr, callee, false /*no fpstate*/, 3,
/* push address of mbr onto stack as 1st parameter */
OPND_CREATE_INTPTR(address),
/* target is 2nd parameter */
OPND_CREATE_INTPTR(target),
/* branch direction (put in ebx below) is 3rd parameter */
opnd_create_reg(REG_XBX));
}
/* calculate whether branch taken or not
* since the clean call mechanism clobbers eflags, we
* must insert our checks prior to that clobbering.
* since we do it AFTER the pusha, we don't have to save; but, we
* can't use a param that's part of any calling convention b/c w/
* PR 250976 our clean call will get it from the pusha.
* ebx is a good choice.
*/
/* We expect:
mov 0x400e5e34 -> %esp
pusha %esp %eax %ebx %ecx %edx %ebp %esi %edi -> %esp (%esp)
pushf %esp -> %esp (%esp)
push $0x00000000 %esp -> %esp (%esp)
popf %esp (%esp) -> %esp
mov 0x400e5e40 -> %eax
push %eax %esp -> %esp (%esp)
* We also assume all clean call instrs are expanded.
*/
/* Because the clean call might be optimized, we cannot assume the sequence.
* We assume that the clean call will not be inlined for having more than one
* arguments, so we scan to find either a call instr or a popf.
* if a popf, do as before.
* if a call, move back to right before push xbx or mov rbx => r3.
*/
if (app_flags_ok == NULL)
app_flags_ok = instrlist_first(ilist);
/* r2065 added out-of-line clean call context switch, so we need to check
* how the context switch code is inserted.
*/
while (!instr_opcode_valid(app_flags_ok) ||
instr_get_opcode(app_flags_ok) != OP_call) {
app_flags_ok = instr_get_next(app_flags_ok);
CLIENT_ASSERT(app_flags_ok != NULL,
"dr_insert_cbr_instrumentation: cannot find call instr");
if (instr_get_opcode(app_flags_ok) == OP_popf)
break;
}
if (instr_get_opcode(app_flags_ok) == OP_call) {
if (opnd_get_pc(instr_get_target(app_flags_ok)) == (app_pc)callee) {
/* call to clean callee
* move a few instrs back till right before push xbx, or mov rbx => r3
*/
while (app_flags_ok != NULL) {
if (instr_reg_in_src(app_flags_ok, DR_REG_XBX))
break;
app_flags_ok = instr_get_prev(app_flags_ok);
}
} else {
/* call to clean call context save */
ASSERT(opnd_get_pc(instr_get_target(app_flags_ok)) ==
get_clean_call_save(dcontext _IF_X64(GENCODE_X64)));
out_of_line_switch = true;
}
ASSERT(app_flags_ok != NULL);
}
/* i#1155: for out-of-line context switch
* we insert two parts of code to setup "taken" arg for clean call:
* - compute "taken" and put it onto the stack right before call to context
* save, where DR already swapped stack and adjusted xsp to point beyond
* mcontext plus temp stack size.
* It is 2 slots away b/c 1st is retaddr.
* - move the "taken" from stack to ebx to compatible with existing code
* right after context save returns and before arg setup, where xsp
* points beyond mcontext (xref emit_clean_call_save).
* It is 2 slots + temp stack size away.
* XXX: we could optimize the code by computing "taken" after clean call
* save if the eflags are not cleared.
*/
/* put our code before the popf or use of xbx */
opc = instr_get_opcode(instr);
if (opc == OP_jecxz || opc == OP_loop || opc == OP_loope || opc == OP_loopne) {
/* for 8-bit cbrs w/ multiple conditions and state, simpler to
* simply execute them -- they're rare so shouldn't be a perf hit.
* after all, ecx is saved, can clobber it.
* we do:
* loop/jecxz taken
* not_taken: mov 0, ebx
* jmp done
* taken: mov 1, ebx
* done:
*/
opnd_t opnd_taken = out_of_line_switch
?
/* 2 slots away from xsp, xref comment above for i#1155 */
OPND_CREATE_MEM32(REG_XSP, -2 * (int)XSP_SZ /* ret+taken */)
: opnd_create_reg(REG_EBX);
instr_t *branch = instr_clone(dcontext, instr);
instr_t *not_taken =
INSTR_CREATE_mov_imm(dcontext, opnd_taken, OPND_CREATE_INT32(0));
instr_t *taken = INSTR_CREATE_mov_imm(dcontext, opnd_taken, OPND_CREATE_INT32(1));
instr_t *done = INSTR_CREATE_label(dcontext);
instr_set_target(branch, opnd_create_instr(taken));
/* client-added meta instrs should not have translation set */
instr_set_translation(branch, NULL);
MINSERT(ilist, app_flags_ok, branch);
MINSERT(ilist, app_flags_ok, not_taken);
MINSERT(ilist, app_flags_ok,
INSTR_CREATE_jmp_short(dcontext, opnd_create_instr(done)));
MINSERT(ilist, app_flags_ok, taken);
MINSERT(ilist, app_flags_ok, done);
if (out_of_line_switch) {
if (opc == OP_loop || opc == OP_loope || opc == OP_loopne) {
/* We executed OP_loop* before we saved xcx, so we must restore
* it. We should be able to use OP_lea b/c OP_loop* uses
* addr prefix to shrink pointer-sized xcx, not data prefix.
*/
reg_id_t xcx = opnd_get_reg(instr_get_dst(instr, 0));
MINSERT(ilist, app_flags_ok,
INSTR_CREATE_lea(
dcontext, opnd_create_reg(xcx),
opnd_create_base_disp(xcx, DR_REG_NULL, 0, 1, OPSZ_lea)));
}
ASSERT(instr_get_opcode(app_flags_ok) == OP_call);
/* 2 slots + temp_stack_size away from xsp,
* xref comment above for i#1155
*/
opnd_taken = OPND_CREATE_MEM32(
REG_XSP, -2 * (int)XSP_SZ - get_clean_call_temp_stack_size());
MINSERT(ilist, instr_get_next(app_flags_ok),
XINST_CREATE_load(dcontext, opnd_create_reg(REG_EBX), opnd_taken));
}
} else {
/* build a setcc equivalent of instr's jcc operation
* WARNING: this relies on order of OP_ enum!
*/
opnd_t opnd_taken = out_of_line_switch
?
/* 2 slots away from xsp, xref comment above for i#1155 */
OPND_CREATE_MEM8(REG_XSP, -2 * (int)XSP_SZ /* ret+taken */)
: opnd_create_reg(REG_BL);
opc = instr_get_opcode(instr);
if (opc <= OP_jnle_short)
opc += (OP_jo - OP_jo_short);
CLIENT_ASSERT(opc >= OP_jo && opc <= OP_jnle,
"dr_insert_cbr_instrumentation: unknown opcode");
opc = opc - OP_jo + OP_seto;
MINSERT(ilist, app_flags_ok, INSTR_CREATE_setcc(dcontext, opc, opnd_taken));
if (out_of_line_switch) {
app_flags_ok = instr_get_next(app_flags_ok);
/* 2 slots + temp_stack_size away from xsp,
* xref comment above for i#1155
*/
opnd_taken = OPND_CREATE_MEM8(
REG_XSP, -2 * (int)XSP_SZ - get_clean_call_temp_stack_size());
}
/* movzx ebx <- bl */
MINSERT(ilist, app_flags_ok,
INSTR_CREATE_movzx(dcontext, opnd_create_reg(REG_EBX), opnd_taken));
}
/* now branch dir is in ebx and will be passed to clean call */
# elif defined(ARM)
/* i#1551: NYI on ARM */
ASSERT_NOT_IMPLEMENTED(false);
# endif /* X86/ARM */
}
DR_API void
dr_insert_cbr_instrumentation(void *drcontext, instrlist_t *ilist, instr_t *instr,
void *callee)
{
dr_insert_cbr_instrumentation_help(drcontext, ilist, instr, callee,
false /* no fallthrough */, opnd_create_null());
}
DR_API void
dr_insert_cbr_instrumentation_ex(void *drcontext, instrlist_t *ilist, instr_t *instr,
void *callee, opnd_t user_data)
{
dr_insert_cbr_instrumentation_help(drcontext, ilist, instr, callee,
true /* has fallthrough */, user_data);
}
DR_API void
dr_insert_ubr_instrumentation(void *drcontext, instrlist_t *ilist, instr_t *instr,
void *callee)
{
/* same as call */
dr_insert_call_instrumentation(drcontext, ilist, instr, callee);
}
/* This may seem like a pretty targeted API function, but there's no
* clean way for a client to do this on its own due to DR's
* restrictions on bb instrumentation (i#782).
*/
DR_API
bool
dr_clobber_retaddr_after_read(void *drcontext, instrlist_t *ilist, instr_t *instr,
ptr_uint_t value)
{
/* the client could be using note fields so we use a label and xfer to
* a note field during the mangling pass
*/
if (instr_is_return(instr)) {
instr_t *label = INSTR_CREATE_label(drcontext);
dr_instr_label_data_t *data = instr_get_label_data_area(label);
/* we could coordinate w/ drmgr and use some reserved note label value
* but only if we run out of instr flags. so we set to 0 to not
* overlap w/ any client uses (DRMGR_NOTE_NONE == 0).
*/
label->note = 0;
/* these values are read back in d_r_mangle() */
data->data[0] = (ptr_uint_t)instr;
data->data[1] = value;
label->flags |= INSTR_CLOBBER_RETADDR;
instr->flags |= INSTR_CLOBBER_RETADDR;
instrlist_meta_preinsert(ilist, instr, label);
return true;
}
return false;
}
DR_API bool
dr_mcontext_xmm_fields_valid(void)
{
return preserve_xmm_caller_saved();
}
DR_API bool
dr_mcontext_zmm_fields_valid(void)
{
# ifdef X86
return d_r_is_avx512_code_in_use();
# else
return false;
# endif
}
#endif /* CLIENT_INTERFACE */
/* dr_get_mcontext() needed for translating clean call arg errors */
/* Fills in whichever of dmc or mc is non-NULL */
bool
dr_get_mcontext_priv(dcontext_t *dcontext, dr_mcontext_t *dmc, priv_mcontext_t *mc)
{
priv_mcontext_t *state;
CLIENT_ASSERT(!TEST(SELFPROT_DCONTEXT, DYNAMO_OPTION(protect_mask)),
"DR context protection NYI");
if (mc == NULL) {
CLIENT_ASSERT(dmc != NULL, "invalid context");
CLIENT_ASSERT(dmc->flags != 0 && (dmc->flags & ~(DR_MC_ALL)) == 0,
"dr_mcontext_t.flags field not set properly");
} else
CLIENT_ASSERT(dmc == NULL, "invalid internal params");
#ifdef CLIENT_INTERFACE
/* i#117/PR 395156: support getting mcontext from events where mcontext is
* stable. It would be nice to support it from init and 1st thread init,
* but the mcontext is not available at those points.
*
* Since DR calls this routine when recreating state and wants the
* clean call version, can't distinguish by whereami=DR_WHERE_FCACHE,
* so we set a flag in the supported events. If client routine
* crashes and we recreate then we want clean call version anyway
* so should be ok. Note that we want in_pre_syscall for other
* reasons (dr_syscall_set_param() for Windows) so we keep it a
* separate flag.
*/
/* no support for init or initial thread init */
if (!dynamo_initialized)
return false;
if (dcontext->client_data->cur_mc != NULL) {
if (mc != NULL)
*mc = *dcontext->client_data->cur_mc;
else if (!priv_mcontext_to_dr_mcontext(dmc, dcontext->client_data->cur_mc))
return false;
return true;
}
if (!is_os_cxt_ptr_null(dcontext->client_data->os_cxt)) {
return os_context_to_mcontext(dmc, mc, dcontext->client_data->os_cxt);
}
if (dcontext->client_data->suspended) {
/* A thread suspended by dr_suspend_all_other_threads() has its
* context translated lazily here.
* We cache the result in cur_mc to avoid a translation cost next time.
*/
bool res;
priv_mcontext_t *mc_xl8;
if (mc != NULL)
mc_xl8 = mc;
else {
dcontext->client_data->cur_mc = (priv_mcontext_t *)heap_alloc(
dcontext, sizeof(*dcontext->client_data->cur_mc) HEAPACCT(ACCT_CLIENT));
/* We'll clear this cache in dr_resume_all_other_threads() */
mc_xl8 = dcontext->client_data->cur_mc;
}
res = thread_get_mcontext(dcontext->thread_record, mc_xl8);
CLIENT_ASSERT(res, "failed to get mcontext of suspended thread");
res = translate_mcontext(dcontext->thread_record, mc_xl8,
false /*do not restore memory*/, NULL);
CLIENT_ASSERT(res, "failed to xl8 mcontext of suspended thread");
if (mc == NULL && !priv_mcontext_to_dr_mcontext(dmc, mc_xl8))
return false;
return true;
}
/* PR 207947: support mcontext access from syscall events */
if (dcontext->client_data->mcontext_in_dcontext ||
dcontext->client_data->in_pre_syscall || dcontext->client_data->in_post_syscall) {
if (mc != NULL)
*mc = *get_mcontext(dcontext);
else if (!priv_mcontext_to_dr_mcontext(dmc, get_mcontext(dcontext)))
return false;
return true;
}
#endif
/* dr_prepare_for_call() puts the machine context on the dstack
* with pusha and pushf, but only fills in xmm values for
* preserve_xmm_caller_saved(): however, we tell the client that the xmm
* fields are not valid otherwise. so, we just have to copy the
* state from the dstack.
*/
state = get_priv_mcontext_from_dstack(dcontext);
if (mc != NULL)
*mc = *state;
else if (!priv_mcontext_to_dr_mcontext(dmc, state))
return false;
/* esp is a dstack value -- get the app stack's esp from the dcontext */
if (mc != NULL)
mc->xsp = get_mcontext(dcontext)->xsp;
else if (TEST(DR_MC_CONTROL, dmc->flags))
dmc->xsp = get_mcontext(dcontext)->xsp;
#ifdef ARM
if (TEST(DR_MC_INTEGER, dmc->flags)) {
/* get the stolen register's app value */
if (mc != NULL) {
set_stolen_reg_val(mc,
(reg_t)d_r_get_tls(os_tls_offset(TLS_REG_STOLEN_SLOT)));
} else {
set_stolen_reg_val(dr_mcontext_as_priv_mcontext(dmc),
(reg_t)d_r_get_tls(os_tls_offset(TLS_REG_STOLEN_SLOT)));
}
}
#endif
/* XXX: should we set the pc field?
* If we do we'll have to adopt a different solution for i#1685 in our Windows
* hooks where today we use the pc slot for temp storage.
*/
return true;
}
DR_API bool
dr_get_mcontext(void *drcontext, dr_mcontext_t *dmc)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
return dr_get_mcontext_priv(dcontext, dmc, NULL);
}
#ifdef CLIENT_INTERFACE
DR_API bool
dr_set_mcontext(void *drcontext, dr_mcontext_t *context)
{
priv_mcontext_t *state;
dcontext_t *dcontext = (dcontext_t *)drcontext;
IF_ARM(reg_t reg_val = 0 /* silence the compiler warning */;)
CLIENT_ASSERT(!TEST(SELFPROT_DCONTEXT, DYNAMO_OPTION(protect_mask)),
"DR context protection NYI");
CLIENT_ASSERT(context != NULL, "invalid context");
CLIENT_ASSERT(context->flags != 0 && (context->flags & ~(DR_MC_ALL)) == 0,
"dr_mcontext_t.flags field not set properly");
/* i#117/PR 395156: allow dr_[gs]et_mcontext where accurate */
/* PR 207947: support mcontext access from syscall events */
if (dcontext->client_data->mcontext_in_dcontext ||
dcontext->client_data->in_pre_syscall || dcontext->client_data->in_post_syscall) {
if (!dr_mcontext_to_priv_mcontext(get_mcontext(dcontext), context))
return false;
return true;
}
if (dcontext->client_data->cur_mc != NULL) {
return dr_mcontext_to_priv_mcontext(dcontext->client_data->cur_mc, context);
}
if (!is_os_cxt_ptr_null(dcontext->client_data->os_cxt)) {
/* It would be nice to fail for #DR_XFER_CALLBACK_RETURN but we'd need to
* store yet more state to do so. The pc will be ignored, and xsi
* changes will likely cause crashes.
*/
return mcontext_to_os_context(dcontext->client_data->os_cxt, context, NULL);
}
/* copy the machine context to the dstack area created with
* dr_prepare_for_call(). note that xmm0-5 copied there
* will override any save_fpstate xmm values, as desired.
*/
state = get_priv_mcontext_from_dstack(dcontext);
# ifdef ARM
if (TEST(DR_MC_INTEGER, context->flags)) {
/* Set the stolen register's app value in TLS, not on stack (we rely
* on our stolen reg retaining its value on the stack)
*/
priv_mcontext_t *mc = dr_mcontext_as_priv_mcontext(context);
d_r_set_tls(os_tls_offset(TLS_REG_STOLEN_SLOT), (void *)get_stolen_reg_val(mc));
/* save the reg val on the stack to be clobbered by the the copy below */
reg_val = get_stolen_reg_val(state);
}
# endif
if (!dr_mcontext_to_priv_mcontext(state, context))
return false;
# ifdef ARM
if (TEST(DR_MC_INTEGER, context->flags)) {
/* restore the reg val on the stack clobbered by the copy above */
set_stolen_reg_val(state, reg_val);
}
# endif
if (TEST(DR_MC_CONTROL, context->flags)) {
/* esp will be restored from a field in the dcontext */
get_mcontext(dcontext)->xsp = context->xsp;
}
/* XXX: should we support setting the pc field? */
return true;
}
DR_API
bool
dr_redirect_execution(dr_mcontext_t *mcontext)
{
dcontext_t *dcontext = get_thread_private_dcontext();
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
ASSERT(dcontext != NULL);
CLIENT_ASSERT(mcontext->size == sizeof(dr_mcontext_t),
"dr_mcontext_t.size field not set properly");
CLIENT_ASSERT(mcontext->flags == DR_MC_ALL, "dr_mcontext_t.flags must be DR_MC_ALL");
/* PR 352429: squash current trace.
* FIXME: will clients use this so much that this will be a perf issue?
* samples/cbr doesn't hit this even at -trace_threshold 1
*/
if (is_building_trace(dcontext)) {
LOG(THREAD, LOG_INTERP, 1, "squashing trace-in-progress\n");
trace_abort(dcontext);
}
dcontext->next_tag = canonicalize_pc_target(dcontext, mcontext->pc);
dcontext->whereami = DR_WHERE_FCACHE;
set_last_exit(dcontext, (linkstub_t *)get_client_linkstub());
# ifdef CLIENT_INTERFACE
if (kernel_xfer_callbacks.num > 0) {
/* This can only be called from a clean call or an exception event.
* For both of those we can get the current mcontext via dr_get_mcontext()
* (the latter b/c we explicitly store to cur_mc just for this use case).
*/
dr_mcontext_t src_dmc;
src_dmc.size = sizeof(src_dmc);
src_dmc.flags = DR_MC_CONTROL | DR_MC_INTEGER;
dr_get_mcontext(dcontext, &src_dmc);
if (instrument_kernel_xfer(dcontext, DR_XFER_CLIENT_REDIRECT, osc_empty, &src_dmc,
NULL, dcontext->next_tag, mcontext->xsp, osc_empty,
dr_mcontext_as_priv_mcontext(mcontext), 0))
dcontext->next_tag = canonicalize_pc_target(dcontext, mcontext->pc);
}
# endif
transfer_to_dispatch(dcontext, dr_mcontext_as_priv_mcontext(mcontext),
true /*full_DR_state*/);
/* on success we won't get here */
return false;
}
DR_API
byte *
dr_redirect_native_target(void *drcontext)
{
# ifdef PROGRAM_SHEPHERDING
/* This feature is unavail for prog shep b/c of the cross-ib-type pollution,
* as well as the lack of source tag info when exiting the ibl (i#1150).
*/
return NULL;
# else
dcontext_t *dcontext = (dcontext_t *)drcontext;
CLIENT_ASSERT(drcontext != NULL,
"dr_redirect_native_target(): drcontext cannot be NULL");
/* The client has no way to know the mode of our gencode so we set LSB here */
return PC_AS_JMP_TGT(DEFAULT_ISA_MODE, get_client_ibl_xfer_entry(dcontext));
# endif
}
/***************************************************************************
* ADAPTIVE OPTIMIZATION SUPPORT
* *Note for non owning thread support (i.e. sideline) all methods assume
* the dcontext valid, the client will have to insure this with a lock
* on thread_exit!!
*
* *need way for side thread to get a dcontext to use for logging and mem
* alloc, before do that should think more about mem alloc in/for adaptive
* routines
*
* *made local mem alloc by side thread safe (see heap.c)
*
* *loging not safe if not owning thread?
*/
DR_API
/* Schedules the fragment to be deleted. Once this call is completed,
* an existing executing fragment is allowed to complete, but control
* will not enter the fragment again before it is deleted.
*
* NOTE: this comment used to say, "after deletion, control may still
* reach the fragment by indirect branch.". We believe this is now only
* true for shared fragments, which are not currently supported.
*/
bool
dr_delete_fragment(void *drcontext, void *tag)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
fragment_t *f;
bool deletable = false, waslinking;
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
CLIENT_ASSERT(!SHARED_FRAGMENTS_ENABLED(),
"dr_delete_fragment() only valid with -thread_private");
CLIENT_ASSERT(drcontext != NULL, "dr_delete_fragment(): drcontext cannot be NULL");
/* i#1989: there's no easy way to get a translation without a proper dcontext */
CLIENT_ASSERT(!fragment_thread_exited(dcontext),
"dr_delete_fragment not supported from the thread exit event");
if (fragment_thread_exited(dcontext))
return false;
waslinking = is_couldbelinking(dcontext);
if (!waslinking)
enter_couldbelinking(dcontext, NULL, false);
# ifdef CLIENT_SIDELINE
d_r_mutex_lock(&(dcontext->client_data->sideline_mutex));
fragment_get_fragment_delete_mutex(dcontext);
# else
CLIENT_ASSERT(drcontext == get_thread_private_dcontext(),
"dr_delete_fragment(): drcontext does not belong to current thread");
# endif
f = fragment_lookup(dcontext, tag);
if (f != NULL && (f->flags & FRAG_CANNOT_DELETE) == 0) {
client_todo_list_t *todo =
HEAP_TYPE_ALLOC(dcontext, client_todo_list_t, ACCT_CLIENT, UNPROTECTED);
client_todo_list_t *iter = dcontext->client_data->to_do;
todo->next = NULL;
todo->ilist = NULL;
todo->tag = tag;
if (iter == NULL)
dcontext->client_data->to_do = todo;
else {
while (iter->next != NULL)
iter = iter->next;
iter->next = todo;
}
deletable = true;
/* unlink fragment so will return to dynamo and delete.
* Do not remove the fragment from the hashtable --
* we need to be able to look up the fragment when
* inspecting the to_do list in d_r_dispatch.
*/
if ((f->flags & FRAG_LINKED_INCOMING) != 0)
unlink_fragment_incoming(dcontext, f);
fragment_remove_from_ibt_tables(dcontext, f, false);
}
# ifdef CLIENT_SIDELINE
fragment_release_fragment_delete_mutex(dcontext);
d_r_mutex_unlock(&(dcontext->client_data->sideline_mutex));
# endif
if (!waslinking)
enter_nolinking(dcontext, NULL, false);
return deletable;
}
DR_API
/* Schedules the fragment at 'tag' for replacement. Once this call is
* completed, an existing executing fragment is allowed to complete,
* but control will not enter the fragment again before it is replaced.
*
* NOTE: this comment used to say, "after replacement, control may still
* reach the fragment by indirect branch.". We believe this is now only
* true for shared fragments, which are not currently supported.
*
* Takes control of the ilist and all responsibility for deleting it and the
* instrs inside of it. The client should not keep, use, reference, etc. the
* instrlist or any of the instrs it contains after they are passed in.
*/
bool
dr_replace_fragment(void *drcontext, void *tag, instrlist_t *ilist)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
bool frag_found, waslinking;
fragment_t *f;
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
CLIENT_ASSERT(!SHARED_FRAGMENTS_ENABLED(),
"dr_replace_fragment() only valid with -thread_private");
CLIENT_ASSERT(drcontext != NULL, "dr_replace_fragment(): drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_replace_fragment: drcontext is invalid");
/* i#1989: there's no easy way to get a translation without a proper dcontext */
CLIENT_ASSERT(!fragment_thread_exited(dcontext),
"dr_replace_fragment not supported from the thread exit event");
if (fragment_thread_exited(dcontext))
return false;
waslinking = is_couldbelinking(dcontext);
if (!waslinking)
enter_couldbelinking(dcontext, NULL, false);
# ifdef CLIENT_SIDELINE
d_r_mutex_lock(&(dcontext->client_data->sideline_mutex));
fragment_get_fragment_delete_mutex(dcontext);
# else
CLIENT_ASSERT(drcontext == get_thread_private_dcontext(),
"dr_replace_fragment(): drcontext does not belong to current thread");
# endif
f = fragment_lookup(dcontext, tag);
frag_found = (f != NULL);
if (frag_found) {
client_todo_list_t *iter = dcontext->client_data->to_do;
client_todo_list_t *todo =
HEAP_TYPE_ALLOC(dcontext, client_todo_list_t, ACCT_CLIENT, UNPROTECTED);
todo->next = NULL;
todo->ilist = ilist;
todo->tag = tag;
if (iter == NULL)
dcontext->client_data->to_do = todo;
else {
while (iter->next != NULL)
iter = iter->next;
iter->next = todo;
}
/* unlink fragment so will return to dynamo and replace for next time
* its executed
*/
if ((f->flags & FRAG_LINKED_INCOMING) != 0)
unlink_fragment_incoming(dcontext, f);
fragment_remove_from_ibt_tables(dcontext, f, false);
}
# ifdef CLIENT_SIDELINE
fragment_release_fragment_delete_mutex(dcontext);
d_r_mutex_unlock(&(dcontext->client_data->sideline_mutex));
# endif
if (!waslinking)
enter_nolinking(dcontext, NULL, false);
return frag_found;
}
# ifdef UNSUPPORTED_API
/* FIXME - doesn't work with shared fragments. Consider removing since dr_flush_region
* and dr_delay_flush_region give us most of this functionality. */
DR_API
/* Flushes all fragments containing 'flush_tag', or the entire code
* cache if flush_tag is NULL. 'curr_tag' must specify the tag of the
* currently-executing fragment. If curr_tag is NULL, flushing can be
* delayed indefinitely. Note that flushing is performed across all
* threads, but other threads may continue to execute fragments
* containing 'curr_tag' until those fragments finish.
*/
void
dr_flush_fragments(void *drcontext, void *curr_tag, void *flush_tag)
{
client_flush_req_t *iter, *flush;
dcontext_t *dcontext = (dcontext_t *)drcontext;
/* We want to unlink the currently executing fragment so we'll
* force a context switch to DR. That way, we'll perform the
* flush as soon as possible. Unfortunately, the client may not
* know the tag of the current trace. Therefore, we unlink all
* fragments in the region.
*
* Note that we aren't unlinking or ibl-invalidating (i.e., making
* unreachable) any fragments in other threads containing curr_tag
* until the delayed flush happens in enter_nolinking().
*/
if (curr_tag != NULL)
vm_area_unlink_incoming(dcontext, (app_pc)curr_tag);
flush = HEAP_TYPE_ALLOC(dcontext, client_flush_req_t, ACCT_CLIENT, UNPROTECTED);
flush->flush_callback = NULL;
if (flush_tag == NULL) {
flush->start = UNIVERSAL_REGION_BASE;
flush->size = UNIVERSAL_REGION_SIZE;
} else {
flush->start = (app_pc)flush_tag;
flush->size = 1;
}
flush->next = NULL;
iter = dcontext->client_data->flush_list;
if (iter == NULL) {
dcontext->client_data->flush_list = flush;
} else {
while (iter->next != NULL)
iter = iter->next;
iter->next = flush;
}
}
# endif /* UNSUPPORTED_API */
DR_API
/* Flush all fragments that contain code from the region [start, start+size).
* Uses a synchall flush to guarantee that no execution occurs out of the fragments
* flushed once this returns. Requires caller to be holding no locks (dr or client) and
* to be !couldbelinking (xref PR 199115, 227619). Caller must use
* dr_redirect_execution() to return to the cache. */
bool
dr_flush_region(app_pc start, size_t size)
{
dcontext_t *dcontext = get_thread_private_dcontext();
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
ASSERT(dcontext != NULL);
LOG(THREAD, LOG_FRAGMENT, 2, "%s: " PFX "-" PFX "\n", __FUNCTION__, start,
start + size);
/* Flush requires !couldbelinking. FIXME - not all event callbacks to the client are
* !couldbelinking (see PR 227619) restricting where this routine can be used. */
CLIENT_ASSERT(!is_couldbelinking(dcontext),
"dr_flush_region: called from an event "
"callback that doesn't support calling this routine; see header file "
"for restrictions.");
/* Flush requires caller to hold no locks that might block a couldbelinking thread
* (which includes almost all dr locks). FIXME - some event callbacks are holding
* dr locks (see PR 227619) so can't call this routine. Since we are going to use
* a synchall flush, holding client locks is disallowed too (could block a thread
* at an unsafe spot for synch). */
CLIENT_ASSERT(OWN_NO_LOCKS(dcontext),
"dr_flush_region: caller owns a client "
"lock or was called from an event callback that doesn't support "
"calling this routine; see header file for restrictions.");
CLIENT_ASSERT(size != 0, "dr_flush_region: 0 is invalid size for flush");
/* release build check of requirements, as many as possible at least */
if (size == 0 || is_couldbelinking(dcontext))
return false;
if (!executable_vm_area_executed_from(start, start + size))
return true;
flush_fragments_from_region(dcontext, start, size, true /*force synchall*/);
return true;
}
DR_API
/* Flush all fragments that contain code from the region [start, start+size).
* Uses an unlink flush which guarantees that no thread will enter a fragment that was
* flushed once this returns (threads already in a flushed fragment will continue).
* Requires caller to be holding no locks (dr or client) and to be !couldbelinking
* (xref PR 199115, 227619). */
bool
dr_unlink_flush_region(app_pc start, size_t size)
{
dcontext_t *dcontext = get_thread_private_dcontext();
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
ASSERT(dcontext != NULL);
LOG(THREAD, LOG_FRAGMENT, 2, "%s: " PFX "-" PFX "\n", __FUNCTION__, start,
start + size);
/* This routine won't work with coarse_units */
CLIENT_ASSERT(!DYNAMO_OPTION(coarse_units),
/* as of now, coarse_units are always disabled with -thread_private. */
"dr_unlink_flush_region is not supported with -opt_memory unless "
"-thread_private or -enable_full_api is also specified");
/* Flush requires !couldbelinking. FIXME - not all event callbacks to the client are
* !couldbelinking (see PR 227619) restricting where this routine can be used. */
CLIENT_ASSERT(!is_couldbelinking(dcontext),
"dr_flush_region: called from an event "
"callback that doesn't support calling this routine, see header file "
"for restrictions.");
/* Flush requires caller to hold no locks that might block a couldbelinking thread
* (which includes almost all dr locks). FIXME - some event callbacks are holding
* dr locks (see PR 227619) so can't call this routine. FIXME - some event callbacks
* are couldbelinking (see PR 227619) so can't allow the caller to hold any client
* locks that could block threads in one of those events (otherwise we don't need
* to care about client locks) */
CLIENT_ASSERT(OWN_NO_LOCKS(dcontext),
"dr_flush_region: caller owns a client "
"lock or was called from an event callback that doesn't support "
"calling this routine, see header file for restrictions.");
CLIENT_ASSERT(size != 0, "dr_unlink_flush_region: 0 is invalid size for flush");
/* release build check of requirements, as many as possible at least */
if (size == 0 || is_couldbelinking(dcontext))
return false;
if (!executable_vm_area_executed_from(start, start + size))
return true;
flush_fragments_from_region(dcontext, start, size, false /*don't force synchall*/);
return true;
}
DR_API
/* Flush all fragments that contain code from the region [start, start+size) at the next
* convenient time. Unlike dr_flush_region() this routine has no restrictions on lock
* or couldbelinking status; the downside is that the delay till the flush actually
* occurs is unbounded (FIXME - we could do something safely here to try to speed it
* up like unlinking shared_syscall etc.), but should occur before any new code is
* executed or any nudges are processed. */
bool
dr_delay_flush_region(app_pc start, size_t size, uint flush_id,
void (*flush_completion_callback)(int flush_id))
{
client_flush_req_t *flush;
LOG(THREAD_GET, LOG_FRAGMENT, 2, "%s: " PFX "-" PFX "\n", __FUNCTION__, start,
start + size);
if (size == 0) {
CLIENT_ASSERT(false, "dr_delay_flush_region: 0 is invalid size for flush");
return false;
}
/* With the new module load event at 1st execution (i#884), we get a lot of
* flush requests during creation of a bb from things like drwrap_replace().
* To avoid them flushing from a new module we check overlap up front here.
*/
if (!executable_vm_area_executed_from(start, start + size)) {
return true;
}
/* FIXME - would be nice if we could check the requirements and call
* dr_unlink_flush_region() here if it's safe. Is difficult to detect non-dr locks
* that could block a couldbelinking thread though. */
flush =
HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, client_flush_req_t, ACCT_CLIENT, UNPROTECTED);
memset(flush, 0x0, sizeof(client_flush_req_t));
flush->start = (app_pc)start;
flush->size = size;
flush->flush_id = flush_id;
flush->flush_callback = flush_completion_callback;
d_r_mutex_lock(&client_flush_request_lock);
flush->next = client_flush_requests;
client_flush_requests = flush;
d_r_mutex_unlock(&client_flush_request_lock);
return true;
}
DR_API
/* returns whether or not there is a fragment in the drcontext fcache at tag
*/
bool
dr_fragment_exists_at(void *drcontext, void *tag)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
fragment_t *f;
# ifdef CLIENT_SIDELINE
fragment_get_fragment_delete_mutex(dcontext);
# endif
f = fragment_lookup(dcontext, tag);
# ifdef CLIENT_SIDELINE
fragment_release_fragment_delete_mutex(dcontext);
# endif
return f != NULL;
}
DR_API
bool
dr_bb_exists_at(void *drcontext, void *tag)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
fragment_t *f = fragment_lookup(dcontext, tag);
if (f != NULL && !TEST(FRAG_IS_TRACE, f->flags)) {
return true;
}
return false;
}
DR_API
/* Looks up the fragment associated with the application pc tag.
* If not found, returns 0.
* If found, returns the total size occupied in the cache by the fragment.
*/
uint
dr_fragment_size(void *drcontext, void *tag)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
fragment_t *f;
int size = 0;
CLIENT_ASSERT(drcontext != NULL, "dr_fragment_size: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT, "dr_fragment_size: drcontext is invalid");
# ifdef CLIENT_SIDELINE
/* used to check to see if owning thread, if so don't need lock */
/* but the check for owning thread more expensive then just getting lock */
/* to check if owner d_r_get_thread_id() == dcontext->owning_thread */
fragment_get_fragment_delete_mutex(dcontext);
# endif
f = fragment_lookup(dcontext, tag);
if (f == NULL)
size = 0;
else
size = f->size;
# ifdef CLIENT_SIDELINE
fragment_release_fragment_delete_mutex(dcontext);
# endif
return size;
}
DR_API
/* Retrieves the application PC of a fragment */
app_pc
dr_fragment_app_pc(void *tag)
{
# ifdef WINDOWS
tag = get_app_pc_from_intercept_pc_if_necessary((app_pc)tag);
CLIENT_ASSERT(tag != NULL, "dr_fragment_app_pc shouldn't be NULL");
DODEBUG({
/* Without -hide our DllMain routine ends up in the cache (xref PR 223120).
* On Linux fini() ends up in the cache.
*/
if (DYNAMO_OPTION(hide) && is_dynamo_address(tag) &&
/* support client interpreting code out of its library */
!is_in_client_lib(tag)) {
/* downgraded from assert for client interpreting its own generated code */
SYSLOG_INTERNAL_WARNING_ONCE("dr_fragment_app_pc is a DR/client pc");
}
});
# elif defined(LINUX) && defined(X86_32)
/* Point back at our hook, undoing the bb shift for SA_RESTART (i#2659). */
if ((app_pc)tag == vsyscall_sysenter_displaced_pc)
tag = vsyscall_sysenter_return_pc;
# endif
return tag;
}
DR_API
/* i#268: opposite of dr_fragment_app_pc() */
app_pc
dr_app_pc_for_decoding(app_pc pc)
{
# ifdef WINDOWS
app_pc displaced;
if (is_intercepted_app_pc(pc, &displaced))
return displaced;
# endif
return pc;
}
DR_API
app_pc
dr_app_pc_from_cache_pc(byte *cache_pc)
{
app_pc res = NULL;
dcontext_t *dcontext = get_thread_private_dcontext();
bool waslinking;
CLIENT_ASSERT(!standalone_library, "API not supported in standalone mode");
ASSERT(dcontext != NULL);
/* i#1989: there's no easy way to get a translation without a proper dcontext */
CLIENT_ASSERT(!fragment_thread_exited(dcontext),
"dr_app_pc_from_cache_pc not supported from the thread exit event");
if (fragment_thread_exited(dcontext))
return NULL;
waslinking = is_couldbelinking(dcontext);
if (!waslinking)
enter_couldbelinking(dcontext, NULL, false);
/* suppress asserts about faults in meta instrs */
DODEBUG({ dcontext->client_data->is_translating = true; });
res = recreate_app_pc(dcontext, cache_pc, NULL);
DODEBUG({ dcontext->client_data->is_translating = false; });
if (!waslinking)
enter_nolinking(dcontext, NULL, false);
return res;
}
DR_API
bool
dr_using_app_state(void *drcontext)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
return os_using_app_state(dcontext);
}
DR_API
void
dr_switch_to_app_state(void *drcontext)
{
dr_switch_to_app_state_ex(drcontext, DR_STATE_ALL);
}
DR_API
void
dr_switch_to_app_state_ex(void *drcontext, dr_state_flags_t flags)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
os_swap_context(dcontext, true /*to app*/, flags);
}
DR_API
void
dr_switch_to_dr_state(void *drcontext)
{
dr_switch_to_dr_state_ex(drcontext, DR_STATE_ALL);
}
DR_API
void
dr_switch_to_dr_state_ex(void *drcontext, dr_state_flags_t flags)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
os_swap_context(dcontext, false /*to dr*/, flags);
}
/***************************************************************************
* CUSTOM TRACES SUPPORT
* *could use a method to unmark a trace head, would be nice if DR
* notified the client when it marked a trace head and gave the client a
* chance to override its decision
*/
DR_API
/* Marks the fragment associated with the application pc tag as
* a trace head. The fragment need not exist yet -- once it is
* created it will be marked as a trace head.
*
* DR associates a counter with a trace head and once it
* passes the -hot_threshold parameter, DR begins building
* a trace. Before each fragment is added to the trace, DR
* calls the client routine dr_end_trace to determine whether
* to end the trace. (dr_end_trace will be called both for
* standard DR traces and for client-defined traces.)
*
* Note, some fragments are unsuitable for trace heads. DR will
* ignore attempts to mark such fragments as trace heads and will return
* false. If the client marks a fragment that doesn't exist yet as a trace
* head and DR later determines that the fragment is unsuitable for
* a trace head it will unmark the fragment as a trace head without
* notifying the client.
*
* Returns true if the target fragment is marked as a trace head.
*
* If coarse, headness depends on path: currently this will only have
* links from tag's coarse unit unlinked.
*/
bool /* FIXME: dynamorio_app_init returns an int! */
dr_mark_trace_head(void *drcontext, void *tag)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
fragment_t *f;
fragment_t coarse_f;
bool success = true;
CLIENT_ASSERT(drcontext != NULL, "dr_mark_trace_head: drcontext cannot be NULL");
CLIENT_ASSERT(drcontext != GLOBAL_DCONTEXT,
"dr_mark_trace_head: drcontext is invalid");
/* Required to make the future-fragment lookup and add atomic and for
* mark_trace_head. We have to grab before fragment_delete_mutex so
* we pay the cost of acquiring up front even when f->flags doesn't
* require it.
*/
SHARED_FLAGS_RECURSIVE_LOCK(FRAG_SHARED, acquire, change_linking_lock);
# ifdef CLIENT_SIDELINE
/* used to check to see if owning thread, if so don't need lock */
/* but the check for owning thread more expensive then just getting lock */
/* to check if owner d_r_get_thread_id() == dcontext->owning_thread */
fragment_get_fragment_delete_mutex(dcontext);
# endif
f = fragment_lookup_fine_and_coarse(dcontext, tag, &coarse_f, NULL);
if (f == NULL) {
future_fragment_t *fut;
fut = fragment_lookup_future(dcontext, tag);
if (fut == NULL) {
/* need to create a future fragment */
fut = fragment_create_and_add_future(dcontext, tag, FRAG_IS_TRACE_HEAD);
} else {
/* don't call mark_trace_head, it will try to do some linking */
fut->flags |= FRAG_IS_TRACE_HEAD;
}
# ifndef CLIENT_SIDELINE
LOG(THREAD, LOG_MONITOR, 2,
"Client mark trace head : will mark fragment as trace head when built "
": address " PFX "\n",
tag);
# endif
} else {
/* check precluding conditions */
if (TEST(FRAG_IS_TRACE, f->flags)) {
# ifndef CLIENT_SIDELINE
LOG(THREAD, LOG_MONITOR, 2,
"Client mark trace head : not marking as trace head, is already "
"a trace : address " PFX "\n",
tag);
# endif
success = false;
} else if (TEST(FRAG_CANNOT_BE_TRACE, f->flags)) {
# ifndef CLIENT_SIDELINE
LOG(THREAD, LOG_MONITOR, 2,
"Client mark trace head : not marking as trace head, particular "
"fragment cannot be trace head : address " PFX "\n",
tag);
# endif
success = false;
} else if (TEST(FRAG_IS_TRACE_HEAD, f->flags)) {
# ifndef CLIENT_SIDELINE
LOG(THREAD, LOG_MONITOR, 2,
"Client mark trace head : fragment already marked as trace head : "
"address " PFX "\n",
tag);
# endif
success = true;
} else {
mark_trace_head(dcontext, f, NULL, NULL);
# ifndef CLIENT_SIDELINE
LOG(THREAD, LOG_MONITOR, 3,
"Client mark trace head : just marked as trace head : address " PFX "\n",
tag);
# endif
}
}
# ifdef CLIENT_SIDELINE
fragment_release_fragment_delete_mutex(dcontext);
# endif
SHARED_FLAGS_RECURSIVE_LOCK(FRAG_SHARED, release, change_linking_lock);
return success;
}
DR_API
/* Checks to see if the fragment (or future fragment) in the drcontext
* fcache at tag is marked as a trace head
*/
bool
dr_trace_head_at(void *drcontext, void *tag)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
fragment_t *f;
bool trace_head;
# ifdef CLIENT_SIDELINE
fragment_get_fragment_delete_mutex(dcontext);
# endif
f = fragment_lookup(dcontext, tag);
if (f != NULL)
trace_head = (f->flags & FRAG_IS_TRACE_HEAD) != 0;
else {
future_fragment_t *fut = fragment_lookup_future(dcontext, tag);
if (fut != NULL)
trace_head = (fut->flags & FRAG_IS_TRACE_HEAD) != 0;
else
trace_head = false;
}
# ifdef CLIENT_SIDELINE
fragment_release_fragment_delete_mutex(dcontext);
# endif
return trace_head;
}
DR_API
/* checks to see that if there is a trace in the drcontext fcache at tag
*/
bool
dr_trace_exists_at(void *drcontext, void *tag)
{
dcontext_t *dcontext = (dcontext_t *)drcontext;
fragment_t *f;
bool trace;
# ifdef CLIENT_SIDELINE
fragment_get_fragment_delete_mutex(dcontext);
# endif
f = fragment_lookup(dcontext, tag);
if (f != NULL)
trace = (f->flags & FRAG_IS_TRACE) != 0;
else
trace = false;
# ifdef CLIENT_SIDELINE
fragment_release_fragment_delete_mutex(dcontext);
# endif
return trace;
}
# ifdef UNSUPPORTED_API
DR_API
/* All basic blocks created after this routine is called will have a prefix
* that restores the ecx register. Exit ctis can be made to target this prefix
* instead of the normal entry point by using the instr_branch_set_prefix_target()
* routine.
* WARNING: this routine should almost always be called during client
* initialization, since having a mixture of prefixed and non-prefixed basic
* blocks can lead to trouble.
*/
void
dr_add_prefixes_to_basic_blocks(void)
{
if (DYNAMO_OPTION(coarse_units)) {
/* coarse_units doesn't support prefixes in general.
* the variation by addr prefix according to processor type
* is also not stored in pcaches.
*/
CLIENT_ASSERT(false,
"dr_add_prefixes_to_basic_blocks() not supported with -opt_memory");
}
options_make_writable();
dynamo_options.bb_prefixes = true;
options_restore_readonly();
}
# endif /* UNSUPPORTED_API */
DR_API
/* Insert code to get the segment base address pointed at by seg into
* register reg. In Linux, it is only supported with -mangle_app_seg option.
* In Windows, it only supports getting base address of the TLS segment.
*/
bool
dr_insert_get_seg_base(void *drcontext, instrlist_t *ilist, instr_t *instr, reg_id_t seg,
reg_id_t reg)
{
CLIENT_ASSERT(reg_is_pointer_sized(reg),
"dr_insert_get_seg_base: reg has wrong size\n");
# ifdef X86
CLIENT_ASSERT(reg_is_segment(seg),
"dr_insert_get_seg_base: seg is not a segment register");
# ifdef UNIX
CLIENT_ASSERT(INTERNAL_OPTION(mangle_app_seg),
"dr_insert_get_seg_base is supported"
"with -mangle_app_seg only");
/* FIXME: we should remove the constraint below by always mangling SEG_TLS,
* 1. Getting TLS base could be a common request by clients.
* 2. The TLS descriptor setup and selector setup can be separated,
* so we must intercept all descriptor setup. It will not be large
* runtime overhead for keeping track of the app's TLS segment base.
*/
CLIENT_ASSERT(INTERNAL_OPTION(private_loader) || seg != SEG_TLS,
"dr_insert_get_seg_base supports TLS seg"
"only with -private_loader");
if (!INTERNAL_OPTION(mangle_app_seg) ||
!(INTERNAL_OPTION(private_loader) || seg != SEG_TLS))
return false;
if (seg == SEG_FS || seg == SEG_GS) {
instrlist_meta_preinsert(ilist, instr,
instr_create_restore_from_tls(
drcontext, reg, os_get_app_tls_base_offset(seg)));
} else {
instrlist_meta_preinsert(
ilist, instr,
INSTR_CREATE_mov_imm(drcontext, opnd_create_reg(reg), OPND_CREATE_INTPTR(0)));
}
# else /* Windows */
if (seg == SEG_TLS) {
instrlist_meta_preinsert(
ilist, instr,
XINST_CREATE_load(drcontext, opnd_create_reg(reg),
opnd_create_far_base_disp(SEG_TLS, REG_NULL, REG_NULL, 0,
SELF_TIB_OFFSET, OPSZ_PTR)));
} else if (seg == SEG_CS || seg == SEG_DS || seg == SEG_ES || seg == SEG_SS) {
/* XXX: we assume flat address space */
instrlist_meta_preinsert(
ilist, instr,
INSTR_CREATE_mov_imm(drcontext, opnd_create_reg(reg), OPND_CREATE_INTPTR(0)));
} else
return false;
# endif /* UNIX/Windows */
# elif defined(ARM)
/* i#1551: NYI on ARM */
ASSERT_NOT_IMPLEMENTED(false);
# endif /* X86/ARM */
return true;
}
DR_API
reg_id_t
dr_get_stolen_reg()
{
return IF_X86_ELSE(REG_NULL, dr_reg_stolen);
}
DR_API
bool
dr_insert_get_stolen_reg_value(void *drcontext, instrlist_t *ilist, instr_t *instr,
reg_id_t reg)
{
IF_X86(CLIENT_ASSERT(false, "dr_insert_get_stolen_reg: should not be reached\n"));
CLIENT_ASSERT(reg_is_pointer_sized(reg),
"dr_insert_get_stolen_reg: reg has wrong size\n");
CLIENT_ASSERT(!reg_is_stolen(reg),
"dr_insert_get_stolen_reg: reg is used by DynamoRIO\n");
# ifdef AARCHXX
instrlist_meta_preinsert(
ilist, instr, instr_create_restore_from_tls(drcontext, reg, TLS_REG_STOLEN_SLOT));
# endif
return true;
}
DR_API
bool
dr_insert_set_stolen_reg_value(void *drcontext, instrlist_t *ilist, instr_t *instr,
reg_id_t reg)
{
IF_X86(CLIENT_ASSERT(false, "dr_insert_set_stolen_reg: should not be reached\n"));
CLIENT_ASSERT(reg_is_pointer_sized(reg),
"dr_insert_set_stolen_reg: reg has wrong size\n");
CLIENT_ASSERT(!reg_is_stolen(reg),
"dr_insert_set_stolen_reg: reg is used by DynamoRIO\n");
# ifdef AARCHXX
instrlist_meta_preinsert(
ilist, instr, instr_create_save_to_tls(drcontext, reg, TLS_REG_STOLEN_SLOT));
# endif
return true;
}
DR_API
int
dr_remove_it_instrs(void *drcontext, instrlist_t *ilist)
{
# if !defined(ARM)
return 0;
# else
int res = 0;
instr_t *inst, *next;
for (inst = instrlist_first(ilist); inst != NULL; inst = next) {
next = instr_get_next(inst);
if (instr_get_opcode(inst) == OP_it) {
res++;
instrlist_remove(ilist, inst);
instr_destroy(drcontext, inst);
}
}
return res;
# endif
}
DR_API
int
dr_insert_it_instrs(void *drcontext, instrlist_t *ilist)
{
# if !defined(ARM)
return 0;
# else
instr_t *first = instrlist_first(ilist);
if (first == NULL || instr_get_isa_mode(first) != DR_ISA_ARM_THUMB)
return 0;
return reinstate_it_blocks((dcontext_t *)drcontext, ilist, instrlist_first(ilist),
NULL);
# endif
}
DR_API
bool
dr_prepopulate_cache(app_pc *tags, size_t tags_count)
{
/* We expect get_thread_private_dcontext() to return NULL b/c we're between
* dr_app_setup() and dr_app_start() and are considered a "native" thread
* with disabled TLS. We do set up TLS as too many routines fail (e.g.,
* clean call analysis) with NULL from TLS, but we do not set up signal
* handling: the caller has to handle decode faults, as we do not
* want to enable our signal handlers, which might disrupt the app running
* natively in parallel with us.
*/
thread_record_t *tr = thread_lookup(d_r_get_thread_id());
dcontext_t *dcontext = tr->dcontext;
uint i;
if (dcontext == NULL)
return false;
SHARED_BB_LOCK();
SYSLOG_INTERNAL_INFO("pre-building code cache from %d tags", tags_count);
# ifdef UNIX
os_swap_context(dcontext, false /*to dr*/, DR_STATE_GO_NATIVE);
# endif
for (i = 0; i < tags_count; i++) {
/* There could be duplicates if sthg was deleted and re-added during profiling */
fragment_t coarse_f;
fragment_t *f;
# ifdef UNIX
/* We silently skip DR-segment-reading addresses to help out a caller
* who sampled and couldn't avoid self-sampling for decoding.
*/
if (is_DR_segment_reader_entry(tags[i]))
continue;
# endif
f = fragment_lookup_fine_and_coarse(dcontext, tags[i], &coarse_f, NULL);
if (f == NULL) {
/* For coarse-grain we won't link as that's done during execution,
* but for fine-grained this should produce a fully warmed cache.
*/
f = build_basic_block_fragment(dcontext, tags[i], 0, true /*link*/,
true /*visible*/
_IF_CLIENT(false /*!for_trace*/)
_IF_CLIENT(NULL));
}
ASSERT(f != NULL);
/* We're ok making a thread-private fragment: might be a waste if this
* thread never runs it, but simpler than trying to skip them or sthg.
*/
}
# ifdef UNIX
os_swap_context(dcontext, true /*to app*/, DR_STATE_GO_NATIVE);
# endif
SHARED_BB_UNLOCK();
return true;
}
DR_API
bool
dr_prepopulate_indirect_targets(dr_indirect_branch_type_t branch_type, app_pc *tags,
size_t tags_count)
{
/* We do the same setup as for dr_prepopulate_cache(). */
thread_record_t *tr = thread_lookup(d_r_get_thread_id());
dcontext_t *dcontext = tr->dcontext;
ibl_branch_type_t ibl_type;
uint i;
if (dcontext == NULL)
return false;
/* Initially I took in an opcode and used extract_branchtype(instr_branch_type())
* but every use case had to make a fake instr to get the opcode and had no
* good cross-platform method so I switched to an enum. We're unlikely to
* change our ibt split and we can add new enums in any case.
*/
switch (branch_type) {
case DR_INDIRECT_RETURN: ibl_type = IBL_RETURN; break;
case DR_INDIRECT_CALL: ibl_type = IBL_INDCALL; break;
case DR_INDIRECT_JUMP: ibl_type = IBL_INDJMP; break;
default: return false;
}
SYSLOG_INTERNAL_INFO("pre-populating ibt[%d] table for %d tags", ibl_type,
tags_count);
# ifdef UNIX
os_swap_context(dcontext, false /*to dr*/, DR_STATE_GO_NATIVE);
# endif
for (i = 0; i < tags_count; i++) {
fragment_add_ibl_target(dcontext, tags[i], ibl_type);
}
# ifdef UNIX
os_swap_context(dcontext, true /*to app*/, DR_STATE_GO_NATIVE);
# endif
return true;
}
DR_API
bool
dr_get_stats(dr_stats_t *drstats)
{
return stats_get_snapshot(drstats);
}
/***************************************************************************
* PERSISTENCE
*/
/* Up to caller to synchronize. */
uint
instrument_persist_ro_size(dcontext_t *dcontext, void *perscxt, size_t file_offs)
{
size_t sz = 0;
size_t i;
/* Store the set of clients in use as we require the same set in order
* to validate the pcache on use. Note that we can't just have -client_lib
* be OP_PCACHE_GLOBAL b/c it contains client options too.
* We have no unique guids for clients so we store the full path.
* We ignore ids. We do care about priority order: clients must
* be in the same order in addition to having the same path.
*
* XXX: we could go further and store client library checksum, etc. hashes,
* but that precludes clients from doing their own proper versioning.
*
* XXX: we could also put the set of clients into the pcache namespace to allow
* simultaneous use of pcaches with different sets of clients (empty set
* vs under tool, in particular): but doesn't really seem useful enough
* for the trouble
*/
for (i = 0; i < num_client_libs; i++) {
sz += strlen(client_libs[i].path) + 1 /*NULL*/;
}
sz++; /* double NULL ends it */
/* Now for clients' own data.
* For user_data, we assume each sequence of <size, patch, persist> is
* atomic: caller holds a mutex across the sequence. Thus, we can use
* global storage.
*/
if (persist_ro_size_callbacks.num > 0) {
call_all_ret(sz, +=, , persist_ro_size_callbacks,
size_t(*)(void *, void *, size_t, void **), (void *)dcontext,
perscxt, file_offs + sz, &persist_user_data[idx]);
}
/* using size_t for API w/ clients in case we want to widen in future */
CLIENT_ASSERT(CHECK_TRUNCATE_TYPE_uint(sz), "persisted cache size too large");
return (uint)sz;
}
/* Up to caller to synchronize.
* Returns true iff all writes succeeded.
*/
bool
instrument_persist_ro(dcontext_t *dcontext, void *perscxt, file_t fd)
{
bool res = true;
size_t i;
char nul = '\0';
ASSERT(fd != INVALID_FILE);
for (i = 0; i < num_client_libs; i++) {
size_t sz = strlen(client_libs[i].path) + 1 /*NULL*/;
if (os_write(fd, client_libs[i].path, sz) != (ssize_t)sz)
return false;
}
/* double NULL ends it */
if (os_write(fd, &nul, sizeof(nul)) != (ssize_t)sizeof(nul))
return false;
/* Now for clients' own data */
if (persist_ro_size_callbacks.num > 0) {
call_all_ret(res, = res &&, , persist_ro_callbacks,
bool (*)(void *, void *, file_t, void *), (void *)dcontext, perscxt,
fd, persist_user_data[idx]);
}
return res;
}
/* Returns true if successfully validated and de-serialized */
bool
instrument_resurrect_ro(dcontext_t *dcontext, void *perscxt, byte *map)
{
bool res = true;
size_t i;
const char *c;
ASSERT(map != NULL);
/* Ensure we have the same set of tools (see comments above) */
i = 0;
c = (const char *)map;
while (*c != '\0') {
if (i >= num_client_libs)
return false; /* too many clients */
if (strcmp(client_libs[i].path, c) != 0)
return false; /* client path mismatch */
c += strlen(c) + 1;
i++;
}
if (i < num_client_libs)
return false; /* too few clients */
c++;
/* Now for clients' own data */
if (resurrect_ro_callbacks.num > 0) {
call_all_ret(res, = res &&, , resurrect_ro_callbacks,
bool (*)(void *, void *, byte **), (void *)dcontext, perscxt,
(byte **)&c);
}
return res;
}
/* Up to caller to synchronize. */
uint
instrument_persist_rx_size(dcontext_t *dcontext, void *perscxt, size_t file_offs)
{
size_t sz = 0;
if (persist_rx_size_callbacks.num == 0)
return 0;
call_all_ret(sz, +=, , persist_rx_size_callbacks,
size_t(*)(void *, void *, size_t, void **), (void *)dcontext, perscxt,
file_offs + sz, &persist_user_data[idx]);
/* using size_t for API w/ clients in case we want to widen in future */
CLIENT_ASSERT(CHECK_TRUNCATE_TYPE_uint(sz), "persisted cache size too large");
return (uint)sz;
}
/* Up to caller to synchronize.
* Returns true iff all writes succeeded.
*/
bool
instrument_persist_rx(dcontext_t *dcontext, void *perscxt, file_t fd)
{
bool res = true;
ASSERT(fd != INVALID_FILE);
if (persist_rx_callbacks.num == 0)
return true;
call_all_ret(res, = res &&, , persist_rx_callbacks,
bool (*)(void *, void *, file_t, void *), (void *)dcontext, perscxt, fd,
persist_user_data[idx]);
return res;
}
/* Returns true if successfully validated and de-serialized */
bool
instrument_resurrect_rx(dcontext_t *dcontext, void *perscxt, byte *map)
{
bool res = true;
ASSERT(map != NULL);
if (resurrect_rx_callbacks.num == 0)
return true;
call_all_ret(res, = res &&, , resurrect_rx_callbacks,
bool (*)(void *, void *, byte **), (void *)dcontext, perscxt, &map);
return res;
}
/* Up to caller to synchronize. */
uint
instrument_persist_rw_size(dcontext_t *dcontext, void *perscxt, size_t file_offs)
{
size_t sz = 0;
if (persist_rw_size_callbacks.num == 0)
return 0;
call_all_ret(sz, +=, , persist_rw_size_callbacks,
size_t(*)(void *, void *, size_t, void **), (void *)dcontext, perscxt,
file_offs + sz, &persist_user_data[idx]);
/* using size_t for API w/ clients in case we want to widen in future */
CLIENT_ASSERT(CHECK_TRUNCATE_TYPE_uint(sz), "persisted cache size too large");
return (uint)sz;
}
/* Up to caller to synchronize.
* Returns true iff all writes succeeded.
*/
bool
instrument_persist_rw(dcontext_t *dcontext, void *perscxt, file_t fd)
{
bool res = true;
ASSERT(fd != INVALID_FILE);
if (persist_rw_callbacks.num == 0)
return true;
call_all_ret(res, = res &&, , persist_rw_callbacks,
bool (*)(void *, void *, file_t, void *), (void *)dcontext, perscxt, fd,
persist_user_data[idx]);
return res;
}
/* Returns true if successfully validated and de-serialized */
bool
instrument_resurrect_rw(dcontext_t *dcontext, void *perscxt, byte *map)
{
bool res = true;
ASSERT(map != NULL);
if (resurrect_rw_callbacks.num == 0)
return true;
call_all_ret(res, = res &&, , resurrect_rx_callbacks,
bool (*)(void *, void *, byte **), (void *)dcontext, perscxt, &map);
return res;
}
bool
instrument_persist_patch(dcontext_t *dcontext, void *perscxt, byte *bb_start,
size_t bb_size)
{
bool res = true;
if (persist_patch_callbacks.num == 0)
return true;
call_all_ret(res, = res &&, , persist_patch_callbacks,
bool (*)(void *, void *, byte *, size_t, void *), (void *)dcontext,
perscxt, bb_start, bb_size, persist_user_data[idx]);
return res;
}
DR_API
bool
dr_register_persist_ro(size_t (*func_size)(void *drcontext, void *perscxt,
size_t file_offs, void **user_data OUT),
bool (*func_persist)(void *drcontext, void *perscxt, file_t fd,
void *user_data),
bool (*func_resurrect)(void *drcontext, void *perscxt,
byte **map INOUT))
{
if (func_size == NULL || func_persist == NULL || func_resurrect == NULL)
return false;
add_callback(&persist_ro_size_callbacks, (void (*)(void))func_size, true);
add_callback(&persist_ro_callbacks, (void (*)(void))func_persist, true);
add_callback(&resurrect_ro_callbacks, (void (*)(void))func_resurrect, true);
return true;
}
DR_API
bool
dr_unregister_persist_ro(size_t (*func_size)(void *drcontext, void *perscxt,
size_t file_offs, void **user_data OUT),
bool (*func_persist)(void *drcontext, void *perscxt, file_t fd,
void *user_data),
bool (*func_resurrect)(void *drcontext, void *perscxt,
byte **map INOUT))
{
bool res = true;
if (func_size != NULL) {
res = remove_callback(&persist_ro_size_callbacks, (void (*)(void))func_size,
true) &&
res;
} else
res = false;
if (func_persist != NULL) {
res =
remove_callback(&persist_ro_callbacks, (void (*)(void))func_persist, true) &&
res;
} else
res = false;
if (func_resurrect != NULL) {
res = remove_callback(&resurrect_ro_callbacks, (void (*)(void))func_resurrect,
true) &&
res;
} else
res = false;
return res;
}
DR_API
bool
dr_register_persist_rx(size_t (*func_size)(void *drcontext, void *perscxt,
size_t file_offs, void **user_data OUT),
bool (*func_persist)(void *drcontext, void *perscxt, file_t fd,
void *user_data),
bool (*func_resurrect)(void *drcontext, void *perscxt,
byte **map INOUT))
{
if (func_size == NULL || func_persist == NULL || func_resurrect == NULL)
return false;
add_callback(&persist_rx_size_callbacks, (void (*)(void))func_size, true);
add_callback(&persist_rx_callbacks, (void (*)(void))func_persist, true);
add_callback(&resurrect_rx_callbacks, (void (*)(void))func_resurrect, true);
return true;
}
DR_API
bool
dr_unregister_persist_rx(size_t (*func_size)(void *drcontext, void *perscxt,
size_t file_offs, void **user_data OUT),
bool (*func_persist)(void *drcontext, void *perscxt, file_t fd,
void *user_data),
bool (*func_resurrect)(void *drcontext, void *perscxt,
byte **map INOUT))
{
bool res = true;
if (func_size != NULL) {
res = remove_callback(&persist_rx_size_callbacks, (void (*)(void))func_size,
true) &&
res;
} else
res = false;
if (func_persist != NULL) {
res =
remove_callback(&persist_rx_callbacks, (void (*)(void))func_persist, true) &&
res;
} else
res = false;
if (func_resurrect != NULL) {
res = remove_callback(&resurrect_rx_callbacks, (void (*)(void))func_resurrect,
true) &&
res;
} else
res = false;
return res;
}
DR_API
bool
dr_register_persist_rw(size_t (*func_size)(void *drcontext, void *perscxt,
size_t file_offs, void **user_data OUT),
bool (*func_persist)(void *drcontext, void *perscxt, file_t fd,
void *user_data),
bool (*func_resurrect)(void *drcontext, void *perscxt,
byte **map INOUT))
{
if (func_size == NULL || func_persist == NULL || func_resurrect == NULL)
return false;
add_callback(&persist_rw_size_callbacks, (void (*)(void))func_size, true);
add_callback(&persist_rw_callbacks, (void (*)(void))func_persist, true);
add_callback(&resurrect_rw_callbacks, (void (*)(void))func_resurrect, true);
return true;
}
DR_API
bool
dr_unregister_persist_rw(size_t (*func_size)(void *drcontext, void *perscxt,
size_t file_offs, void **user_data OUT),
bool (*func_persist)(void *drcontext, void *perscxt, file_t fd,
void *user_data),
bool (*func_resurrect)(void *drcontext, void *perscxt,
byte **map INOUT))
{
bool res = true;
if (func_size != NULL) {
res = remove_callback(&persist_rw_size_callbacks, (void (*)(void))func_size,
true) &&
res;
} else
res = false;
if (func_persist != NULL) {
res =
remove_callback(&persist_rw_callbacks, (void (*)(void))func_persist, true) &&
res;
} else
res = false;
if (func_resurrect != NULL) {
res = remove_callback(&resurrect_rw_callbacks, (void (*)(void))func_resurrect,
true) &&
res;
} else
res = false;
return res;
}
DR_API
bool
dr_register_persist_patch(bool (*func_patch)(void *drcontext, void *perscxt,
byte *bb_start, size_t bb_size,
void *user_data))
{
if (func_patch == NULL)
return false;
add_callback(&persist_patch_callbacks, (void (*)(void))func_patch, true);
return true;
}
DR_API
bool
dr_unregister_persist_patch(bool (*func_patch)(void *drcontext, void *perscxt,
byte *bb_start, size_t bb_size,
void *user_data))
{
return remove_callback(&persist_patch_callbacks, (void (*)(void))func_patch, true);
}
#endif /* CLIENT_INTERFACE */
| 1 | 18,087 | Maybe {}, even though no multi-line body? | DynamoRIO-dynamorio | c |
@@ -39,6 +39,16 @@ describe CommunicartMailer do
mail.from.should == ['[email protected]']
end
+ it 'renders the navigator template' do
+ cart.setProp('origin','navigator')
+ cart.stub(:approval_group).and_return(approval_group)
+ approval_group.stub(:approvers).and_return([approver])
+ approver.stub(:approver_comment).and_return([])
+# This is very fragile, it is based on a particular term coming from the navigator teplate.
+# If the template changes, this test will break --- I know of no other way of tesitng this.
+ expect(mail.body.encoded).to match('NAVIGATOR')
+ end
+
context 'attaching a csv of the cart activity' do
it 'generates csv attachments for an approved cart' do
cart.stub(:approval_group).and_return(approval_group) | 1 | require 'spec_helper'
require 'ostruct'
describe CommunicartMailer do
let(:approval_group) { FactoryGirl.create(:approval_group_with_approvers_and_requester, name: "anotherApprovalGroupName") }
let(:approver) { FactoryGirl.create(:user) }
let(:cart) { FactoryGirl.create(:cart_with_approvals, name: "TestCart") }
describe 'cart notification email' do
let(:mail) { CommunicartMailer.cart_notification_email('[email protected]', cart, cart.approvals.first) }
let(:api_token) { FactoryGirl.create(:api_token) }
before do
ENV.stub(:[])
ENV.stub(:[]).with('NOTIFICATION_FROM_EMAIL').and_return('[email protected]')
ApiToken.stub_chain(:where, :where, :last).and_return(api_token)
end
it 'renders the subject' do
cart.update_attributes(external_id: 13579)
cart.stub(:approval_group).and_return(approval_group)
approval_group.stub(:approvers).and_return([approver])
approver.stub(:approver_comment).and_return([])
mail.subject.should == 'Communicart Approval Request from Liono Requester: Please review Cart #13579'
end
it 'renders the receiver email' do
cart.stub(:approval_group).and_return(approval_group)
approval_group.stub(:approvers).and_return([approver])
approver.stub(:approver_comment).and_return([])
mail.to.should == ["[email protected]"]
end
it 'renders the sender email' do
cart.stub(:approval_group).and_return(approval_group)
approval_group.stub(:approvers).and_return([approver])
approver.stub(:approver_comment).and_return([])
mail.from.should == ['[email protected]']
end
context 'attaching a csv of the cart activity' do
it 'generates csv attachments for an approved cart' do
cart.stub(:approval_group).and_return(approval_group)
approval_group.stub(:approvers).and_return([approver])
approver.stub(:approver_comment).and_return([])
cart.stub(:all_approvals_received?).and_return(true)
cart.should_receive(:create_items_csv)
cart.should_receive(:create_comments_csv)
cart.should_receive(:create_approvals_csv)
mail
end
it 'does not generate csv attachments for an unapproved cart' do
cart.stub(:approval_group).and_return(approval_group)
approval_group.stub(:approvers).and_return([approver])
approver.stub(:approver_comment).and_return([])
cart.stub(:all_approvals_received?).and_return(false)
cart.should_not_receive(:create_items_csv)
cart.should_not_receive(:create_comments_csv)
cart.should_not_receive(:create_approvals_csv)
mail
end
end
end
describe 'approval reply received email' do
let(:requester) { FactoryGirl.create(:user, email_address: '[email protected]') }
before do
ENV.stub(:[])
ENV.stub(:[]).with('NOTIFICATION_FROM_EMAIL').and_return('[email protected]')
cart_with_approval_group.stub(:requester).and_return(requester)
end
let(:analysis) {
OpenStruct.new(
approve: 'APPROVE',
fromAddress: '[email protected]',
cartNumber: '13579'
)
}
let(:cart_with_approval_group) { FactoryGirl.create(:cart_with_approval_group) }
let(:mail) { CommunicartMailer.approval_reply_received_email(analysis, cart_with_approval_group) }
it 'renders the subject' do
mail.subject.should == 'User [email protected] has approved cart #13579'
end
it 'renders the receiver email' do
mail.to.should == ["[email protected]"]
end
it 'renders the sender email' do
mail.from.should == ['[email protected]']
end
context 'attaching a csv of the cart activity' do
it 'generates csv attachments for an approved cart' do
cart_with_approval_group.stub(:all_approvals_received?).and_return(true)
cart_with_approval_group.should_receive(:create_items_csv)
cart_with_approval_group.should_receive(:create_comments_csv)
cart_with_approval_group.should_receive(:create_approvals_csv)
mail
end
it 'does not generate csv attachments for an unapproved cart' do
cart_with_approval_group.stub(:all_approvals_received?).and_return(false)
cart_with_approval_group.should_not_receive(:create_items_csv)
cart_with_approval_group.should_not_receive(:create_comments_csv)
cart_with_approval_group.should_not_receive(:create_approvals_csv)
mail
end
end
end
describe 'comment_added_email' do
let(:cart_item) { FactoryGirl.create(:cart_item, description: "A cart item in need of a comment") }
let(:comment) { FactoryGirl.create(:comment, comment_text: 'Somebody give this cart item a comment') }
let(:email) { "[email protected]" }
let(:mail) { CommunicartMailer.comment_added_email(comment, email) }
before do
ENV.stub(:[])
ENV.stub(:[]).with('NOTIFICATION_FROM_EMAIL').and_return('[email protected]')
cart_item.comments << comment
end
it 'renders the subject' do
mail.subject.should == "A comment has been added to cart item 'A cart item in need of a comment'"
end
it 'renders the receiver email' do
mail.to.should == ["[email protected]"]
end
it 'renders the sender email' do
mail.from.should == ['[email protected]']
end
end
# TODO: describe 'rejection_update_email'
describe 'cart observer received email' do
let(:observer) { FactoryGirl.create(:user, email_address: '[email protected]') }
let(:requester) { FactoryGirl.create(:user, email_address: '[email protected]') }
before do
ENV.stub(:[])
ENV.stub(:[]).with('NOTIFICATION_FROM_EMAIL').and_return('[email protected]')
cart_with_observers.stub(:requester).and_return(requester)
end
let(:cart_with_observers) { FactoryGirl.create(:cart_with_observers, external_id: 1965) }
let(:mail) { CommunicartMailer.cart_observer_email(cart_with_observers.observers.first.user.email_address, cart_with_observers) }
it 'renders the subject' do
mail.subject.should == 'Communicart Approval Request from Liono Thunder: Please review Cart #1965'
end
it 'renders the receiver email' do
mail.to.should == ["[email protected]"]
end
it 'renders the sender email' do
mail.from.should == ['[email protected]']
end
context 'attaching a csv of the cart activity' do
it 'generates csv attachments for an approved cart' do
cart_with_observers.stub(:all_approvals_received?).and_return(true)
cart_with_observers.should_receive(:create_items_csv)
cart_with_observers.should_receive(:create_comments_csv)
cart_with_observers.should_receive(:create_approvals_csv)
mail
end
it 'does not generate csv attachments for an unapproved cart' do
cart_with_observers.stub(:all_approvals_received?).and_return(false)
cart_with_observers.should_not_receive(:create_items_csv)
cart_with_observers.should_not_receive(:create_comments_csv)
cart_with_observers.should_not_receive(:create_approvals_csv)
mail
end
end
end
end
| 1 | 11,918 | We can try something like this: response.should render_template(:partial => 'partial_name') | 18F-C2 | rb |
@@ -514,6 +514,10 @@ IDRETRY=4
IDCANCEL=3
def MessageBox(hwnd, text, caption, type):
+ if hasattr(text, 'decode'):
+ text = text.decode('mbcs')
+ if caption and hasattr(caption, 'decode'):
+ caption = caption.decode('mbcs')
res = user32.MessageBoxW(hwnd, text, caption, type)
if res == 0:
raise WinError() | 1 | #winUser.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2017 NV Access Limited, Babbage B.V.
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
"""Functions that wrap Windows API functions from user32.dll"""
from ctypes import *
from ctypes.wintypes import *
#dll handles
user32=windll.user32
LRESULT=c_long
HCURSOR=c_long
#Standard window class stuff
WNDPROC=WINFUNCTYPE(LRESULT,HWND,c_uint,WPARAM,LPARAM)
class WNDCLASSEXW(Structure):
_fields_=[
('cbSize',c_uint),
('style',c_uint),
('lpfnWndProc',WNDPROC),
('cbClsExtra',c_int),
('cbWndExtra',c_int),
('hInstance',HINSTANCE),
('hIcon',HICON),
('HCURSOR',HCURSOR),
('hbrBackground',HBRUSH),
('lpszMenuName',LPWSTR),
('lpszClassName',LPWSTR),
('hIconSm',HICON),
]
class NMHdrStruct(Structure):
_fields_=[
('hwndFrom',HWND),
('idFrom',c_uint),
('code',c_uint),
]
class GUITHREADINFO(Structure):
_fields_=[
('cbSize',DWORD),
('flags',DWORD),
('hwndActive',HWND),
('hwndFocus',HWND),
('hwndCapture',HWND),
('hwndMenuOwner',HWND),
('hwndMoveSize',HWND),
('hwndCaret',HWND),
('rcCaret',RECT),
]
#constants
ERROR_OLD_WIN_VERSION=1150
MOUSEEVENTF_LEFTDOWN=0x0002
MOUSEEVENTF_LEFTUP=0x0004
MOUSEEVENTF_RIGHTDOWN=0x0008
MOUSEEVENTF_RIGHTUP=0x0010
MOUSEEVENTF_MIDDLEDOWN=0x0020
MOUSEEVENTF_MIDDLEUP=0x0040
MOUSEEVENTF_XDOWN=0x0080
MOUSEEVENTF_XUP=0x0100
GUI_CARETBLINKING=0x00000001
GUI_INMOVESIZE=0x00000002
GUI_INMENUMODE=0x00000004
GUI_SYSTEMMENUMODE=0x00000008
GUI_POPUPMENUMODE=0x00000010
SPI_GETSTICKYKEYS=0x003A
SPI_GETSCREENREADER=70
SPI_SETSCREENREADER=71
SPIF_UPDATEINIFILE=1
SPIF_SENDCHANGE=2
WS_DISABLED=0x8000000
WS_VISIBLE=0x10000000
WS_POPUP=0x80000000
WS_GROUP=0x20000
WS_THICKFRAME=0x40000
WS_SIZEBOX=WS_THICKFRAME
WS_SYSMENU=0x80000
WS_HSCROLL=0x100000
WS_VSCROLL=0x200000
WS_CAPTION=0xC00000
WS_EX_TOPMOST=0x00000008
BS_GROUPBOX=7
ES_MULTILINE=4
LBS_OWNERDRAWFIXED=0x0010
LBS_OWNERDRAWVARIABLE=0x0020
LBS_HASSTRINGS=0x0040
CBS_OWNERDRAWFIXED=0x0010
CBS_OWNERDRAWVARIABLE=0x0020
CBS_HASSTRINGS=0x00200
WM_NULL=0
WM_COPYDATA=74
WM_NOTIFY=78
WM_USER=1024
#PeekMessage
PM_REMOVE=1
PM_NOYIELD=2
#sendMessageTimeout
SMTO_ABORTIFHUNG=0x0002
#getAncestor
GA_PARENT=1
GA_ROOT=2
GA_ROOTOWNER=3
#getWindowLong
GWL_ID=-12
GWL_STYLE=-16
GWL_EXSTYLE=-20
#getWindow
GW_HWNDNEXT=2
GW_HWNDPREV=3
GW_OWNER=4
#Window messages
WM_GETTEXT=13
WM_GETTEXTLENGTH=14
WM_PAINT=0x000F
WM_GETOBJECT=0x003D
#Edit control window messages
EM_GETSEL=176
EM_SETSEL=177
EM_SCROLLCARET=0xb7
EM_GETLINE=196
EM_GETLINECOUNT=186
EM_LINEFROMCHAR=201
EM_LINEINDEX=187
EM_LINELENGTH=193
EM_POSFROMCHAR=214
EM_CHARFROMPOS=215
EM_GETFIRSTVISIBLELINE=0x0ce
#Clipboard formats
CF_TEXT=1
#mapVirtualKey constants
MAPVK_VK_TO_CHAR=2
MAPVK_VSC_TO_VK_EX=3
#Virtual key codes
VK_LBUTTON=1
VK_RBUTTON=2
VK_CANCEL=3
VK_MBUTTON=4
VK_XBUTTON1=5
VK_XBUTTON2=6
VK_BACK=8
VK_TAB=9
VK_CLEAR=12
VK_RETURN=13
VK_SHIFT=16
VK_CONTROL=17
VK_MENU=18
VK_PAUSE=19
VK_CAPITAL=20
VK_FINAL=0x18
VK_ESCAPE=0x1B
VK_CONVERT=0x1C
VK_NONCONVERT=0x1D
VK_ACCEPT=0x1E
VK_MODECHANGE=0x1F
VK_SPACE=32
VK_PRIOR=33
VK_NEXT=34
VK_END=35
VK_HOME=36
VK_LEFT=37
VK_UP=38
VK_RIGHT=39
VK_DOWN=40
VK_SELECT=41
VK_PRINT=42
VK_EXECUTE=43
VK_SNAPSHOT=44
VK_INSERT=45
VK_DELETE=46
VK_HELP=47
VK_LWIN=0x5B
VK_RWIN=0x5C
VK_APPS=0x5D
VK_SLEEP=0x5F
VK_NUMPAD0=0x60
VK_NUMPAD1=0x61
VK_NUMPAD2=0x62
VK_NUMPAD3=0x63
VK_NUMPAD4=0x64
VK_NUMPAD5=0x65
VK_NUMPAD6=0x66
VK_NUMPAD7=0x67
VK_NUMPAD8=0x68
VK_NUMPAD9=0x69
VK_MULTIPLY=0x6A
VK_ADD=0x6B
VK_SEPARATOR=0x6C
VK_SUBTRACT=0x6D
VK_DECIMAL=0x6E
VK_DIVIDE=0x6F
VK_F1=0x70
VK_F2=0x71
VK_F3=0x72
VK_F4=0x73
VK_F5=0x74
VK_F6=0x75
VK_F7=0x76
VK_F8=0x77
VK_F9=0x78
VK_F10=0x79
VK_F11=0x7A
VK_F12=0x7B
VK_F13=0x7C
VK_F14=0x7D
VK_F15=0x7E
VK_F16=0x7F
VK_F17=0x80
VK_F18=0x81
VK_F19=0x82
VK_F20=0x83
VK_F21=0x84
VK_F22=0x85
VK_F23=0x86
VK_F24=0x87
VK_NUMLOCK=0x90
VK_SCROLL=0x91
VK_LSHIFT=0xA0
VK_RSHIFT=0xA1
VK_LCONTROL=0xA2
VK_RCONTROL=0xA3
VK_LMENU=0xA4
VK_RMENU=0xA5
VK_VOLUME_MUTE=0xAD
VK_VOLUME_DOWN=0xAE
VK_VOLUME_UP=0xAF
#Windows hooks
WH_KEYBOARD=2
WH_MOUSE=7
#win events
EVENT_SYSTEM_SOUND=0x1
EVENT_SYSTEM_ALERT=0x2
EVENT_SYSTEM_FOREGROUND=0x3
EVENT_SYSTEM_MENUSTART=0x4
EVENT_SYSTEM_MENUEND=0x5
EVENT_SYSTEM_MENUPOPUPSTART=0x6
EVENT_SYSTEM_MENUPOPUPEND=0x7
EVENT_SYSTEM_CAPTURESTART=0x8
EVENT_SYSTEM_CAPTUREEND=0x9
EVENT_SYSTEM_MOVESIZESTART=0xa
EVENT_SYSTEM_MOVESIZEEND=0xb
EVENT_SYSTEM_CONTEXTHELPSTART=0xc
EVENT_SYSTEM_CONTEXTHELPEND=0xd
EVENT_SYSTEM_DRAGDROPSTART=0xe
EVENT_SYSTEM_DRAGDROPEND=0xf
EVENT_SYSTEM_DIALOGSTART=0x10
EVENT_SYSTEM_DIALOGEND=0x11
EVENT_SYSTEM_SCROLLINGSTART=0x12
EVENT_SYSTEM_SCROLLINGEND=0x13
EVENT_SYSTEM_SWITCHSTART=0x14
EVENT_SYSTEM_SWITCHEND=0x15
EVENT_SYSTEM_MINIMIZESTART=0x16
EVENT_SYSTEM_MINIMIZEEND=0x17
EVENT_OBJECT_CREATE=0x8000
EVENT_OBJECT_DESTROY=0x8001
EVENT_OBJECT_SHOW=0x8002
EVENT_OBJECT_HIDE=0x8003
EVENT_OBJECT_REORDER=0x8004
EVENT_OBJECT_FOCUS=0x8005
EVENT_OBJECT_SELECTION=0x8006
EVENT_OBJECT_SELECTIONADD=0x8007
EVENT_OBJECT_SELECTIONREMOVE=0x8008
EVENT_OBJECT_SELECTIONWITHIN=0x8009
EVENT_OBJECT_STATECHANGE=0x800a
EVENT_OBJECT_LOCATIONCHANGE=0x800b
EVENT_OBJECT_NAMECHANGE=0x800c
EVENT_OBJECT_DESCRIPTIONCHANGE=0x800d
EVENT_OBJECT_VALUECHANGE=0x800e
EVENT_OBJECT_PARENTCHANGE=0x800f
EVENT_OBJECT_HELPCHANGE=0x8010
EVENT_OBJECT_DEFACTIONCHANGE=0x8011
EVENT_OBJECT_ACCELERATORCHANGE=0x8012
EVENT_OBJECT_LIVEREGIONCHANGED=0x8019
EVENT_SYSTEM_DESKTOPSWITCH=0x20
EVENT_OBJECT_INVOKED=0x8013
EVENT_OBJECT_TEXTSELECTIONCHANGED=0x8014
EVENT_OBJECT_CONTENTSCROLLED=0x8015
EVENT_CONSOLE_CARET=0x4001
EVENT_CONSOLE_UPDATE_REGION=0x4002
EVENT_CONSOLE_UPDATE_SIMPLE=0x4003
EVENT_CONSOLE_UPDATE_SCROLL=0x4004
EVENT_CONSOLE_LAYOUT=0x4005
EVENT_CONSOLE_START_APPLICATION=0x4006
EVENT_CONSOLE_END_APPLICATION=0x4007
#IAccessible Child IDs
CHILDID_SELF=0
#IAccessible Object IDs
OBJID_WINDOW=0
OBJID_SYSMENU=-1
OBJID_TITLEBAR=-2
OBJID_MENU=-3
OBJID_CLIENT=-4
OBJID_VSCROLL=-5
OBJID_HSCROLL=-6
OBJID_SIZEGRIP=-7
OBJID_CARET=-8
OBJID_CURSOR=-9
OBJID_ALERT=-10
OBJID_SOUND=-11
OBJID_NATIVEOM=-16
# ShowWindow() commands
SW_HIDE = 0
SW_SHOWNORMAL = 1
# RedrawWindow() flags
RDW_INVALIDATE = 0x0001
RDW_UPDATENOW = 0x0100
# MsgWaitForMultipleObjectsEx
QS_ALLINPUT = 0x04ff
MWMO_ALERTABLE = 0x0002
def setSystemScreenReaderFlag(val):
user32.SystemParametersInfoW(SPI_SETSCREENREADER,val,0,SPIF_UPDATEINIFILE|SPIF_SENDCHANGE)
def getSystemScreenReaderFlag():
val = BOOL()
user32.SystemParametersInfoW(SPI_GETSCREENREADER, 0, byref(val), 0)
return bool(val.value)
def LOBYTE(word):
return word&0xFF
def HIBYTE(word):
return word>>8
def MAKEWORD(lo,hi):
return (hi<<8)+lo
def LOWORD(long):
return long&0xFFFF
def HIWORD(long):
return long>>16
def GET_X_LPARAM(lp):
return c_short(LOWORD(lp)).value
def GET_Y_LPARAM(lp):
return c_short(HIWORD(lp)).value
def MAKELONG(lo,hi):
return (hi<<16)+lo
def waitMessage():
return user32.WaitMessage()
def getMessage(*args):
return user32.GetMessageW(*args)
def translateMessage(*args):
return user32.TranslateMessage(*args)
def dispatchMessage(*args):
return user32.DispatchMessageW(*args)
def peekMessage(*args):
try:
res=user32.PeekMessageW(*args)
except:
res=0
return res
def registerWindowMessage(name):
return user32.RegisterWindowMessageW(name)
def getAsyncKeyState(v):
return user32.GetAsyncKeyState(v)
def getKeyState(v):
return user32.GetKeyState(v)
def isWindow(hwnd):
return user32.IsWindow(hwnd)
def isDescendantWindow(parentHwnd,childHwnd):
if (parentHwnd==childHwnd) or user32.IsChild(parentHwnd,childHwnd):
return True
else:
return False
def getForegroundWindow():
return user32.GetForegroundWindow()
def setForegroundWindow(hwnd):
user32.SetForegroundWindow(hwnd)
def setFocus(hwnd):
user32.SetFocus(hwnd)
def getDesktopWindow():
return user32.GetDesktopWindow()
def getControlID(hwnd):
return user32.GetWindowLongW(hwnd,GWL_ID)
def getClientRect(hwnd):
return user32.GetClientRect(hwnd)
HWINEVENTHOOK=HANDLE
WINEVENTPROC=WINFUNCTYPE(None,HWINEVENTHOOK,DWORD,HWND,c_long,c_long,DWORD,DWORD)
def setWinEventHook(*args):
return user32.SetWinEventHook(*args)
def unhookWinEvent(*args):
return user32.UnhookWinEvent(*args)
def sendMessage(hwnd,msg,param1,param2):
return user32.SendMessageW(hwnd,msg,param1,param2)
def getWindowThreadProcessID(hwnd):
processID=c_int()
threadID=user32.GetWindowThreadProcessId(hwnd,byref(processID))
return (processID.value,threadID)
def getClassName(window):
buf=create_unicode_buffer(256)
user32.GetClassNameW(window,buf,255)
return buf.value
def keybd_event(*args):
return user32.keybd_event(*args)
def mouse_event(*args):
return user32.mouse_event(*args)
def getAncestor(hwnd,flags):
return user32.GetAncestor(hwnd,flags)
try:
# Windows >= Vista
_getCursorPos = user32.GetPhysicalCursorPos
_setCursorPos = user32.SetPhysicalCursorPos
except AttributeError:
_getCursorPos = user32.GetCursorPos
_setCursorPos = user32.SetCursorPos
def setCursorPos(x,y):
_setCursorPos(x,y)
def getCursorPos():
point=POINT()
_getCursorPos(byref(point))
return [point.x,point.y]
def getCaretPos():
point=POINT()
user32.GetCaretPos(byref(point))
return [point.x,point.y]
def getTopWindow(hwnd):
return user32.GetTopWindow(hwnd)
def getWindowText(hwnd):
buf=create_unicode_buffer(1024)
user32.InternalGetWindowText(hwnd,buf,1023)
return buf.value
def getWindow(window,relation):
return user32.GetWindow(window,relation)
def isWindowVisible(window):
return bool(user32.IsWindowVisible(window))
def isWindowEnabled(window):
return bool(user32.IsWindowEnabled(window))
def getGUIThreadInfo(threadID):
info=GUITHREADINFO(cbSize=sizeof(GUITHREADINFO))
user32.GetGUIThreadInfo(threadID,byref(info))
return info
def getWindowStyle(hwnd):
return user32.GetWindowLongW(hwnd,GWL_STYLE)
def getPreviousWindow(hwnd):
try:
return user32.GetWindow(hwnd,GW_HWNDPREV)
except WindowsError:
return 0
def getKeyboardLayout(idThread=0):
return user32.GetKeyboardLayout(idThread)
def RedrawWindow(hwnd, rcUpdate, rgnUpdate, flags):
return user32.RedrawWindow(hwnd, byref(rcUpdate), rgnUpdate, flags)
def getKeyNameText(scanCode,extended):
buf=create_unicode_buffer(32)
user32.GetKeyNameTextW((scanCode<<16)|(extended<<24),buf,31)
return buf.value
def FindWindow(className, windowName):
res = user32.FindWindowW(className, windowName)
if res == 0:
raise WinError()
return res
MB_RETRYCANCEL=5
MB_ICONERROR=0x10
MB_SYSTEMMODAL=0x1000
IDRETRY=4
IDCANCEL=3
def MessageBox(hwnd, text, caption, type):
res = user32.MessageBoxW(hwnd, text, caption, type)
if res == 0:
raise WinError()
return res
def PostMessage(hwnd, msg, wParam, lParam):
if not user32.PostMessageW(hwnd, msg, wParam, lParam):
raise WinError()
user32.VkKeyScanExW.restype = SHORT
def VkKeyScanEx(ch, hkl):
res = user32.VkKeyScanExW(WCHAR(ch), hkl)
if res == -1:
raise LookupError
return res >> 8, res & 0xFF
def ScreenToClient(hwnd, x, y):
point = POINT(x, y)
user32.ScreenToClient(hwnd, byref(point))
return point.x, point.y
def ClientToScreen(hwnd, x, y):
point = POINT(x, y)
user32.ClientToScreen(hwnd, byref(point))
return point.x, point.y
def NotifyWinEvent(event, hwnd, idObject, idChild):
user32.NotifyWinEvent(event, hwnd, idObject, idChild)
class STICKYKEYS(Structure):
_fields_ = (
("cbSize", DWORD),
("dwFlags", DWORD),
)
def __init__(self, **kwargs):
super(STICKYKEYS, self).__init__(cbSize=sizeof(self), **kwargs)
SKF_STICKYKEYSON = 0x00000001
SKF_AUDIBLEFEEDBACK = 0x00000040
SKF_TRISTATE = 0x00000080
SKF_TWOKEYSOFF = 0x00000100
def getSystemStickyKeys():
sk = STICKYKEYS()
user32.SystemParametersInfoW(SPI_GETSTICKYKEYS, 0, byref(sk), 0)
return sk
# START SENDINPUT TYPE DECLARATIONS
PUL = POINTER(c_ulong)
class KeyBdInput(Structure):
_fields_ = [("wVk", c_ushort),
("wScan", c_ushort),
("dwFlags", c_ulong),
("time", c_ulong),
("dwExtraInfo", PUL)]
class HardwareInput(Structure):
_fields_ = [("uMsg", c_ulong),
("wParamL", c_short),
("wParamH", c_ushort)]
class MouseInput(Structure):
_fields_ = [("dx", c_long),
("dy", c_long),
("mouseData", c_ulong),
("dwFlags", c_ulong),
("time",c_ulong),
("dwExtraInfo", PUL)]
class Input_I(Union):
_fields_ = [("ki", KeyBdInput),
("mi", MouseInput),
("hi", HardwareInput)]
class Input(Structure):
_fields_ = [("type", c_ulong),
("ii", Input_I)]
INPUT_KEYBOARD = 1
KEYEVENTF_KEYUP = 0x0002
KEYEVENTF_UNICODE = 0x04
# END SENDINPUT TYPE DECLARATIONS
def SendInput(inputs):
n = len(inputs)
arr = (Input * n)(*inputs)
user32.SendInput(n, arr, sizeof(Input))
| 1 | 23,351 | Please use `isinstance(text, bytes)` instead. Otherwise, this will lead to unnecessary decoding on python 2 unicode strings. | nvaccess-nvda | py |
@@ -3068,7 +3068,7 @@ void SwiftLanguageRuntime::FindFunctionPointersInCall(
ExecutionContext exe_ctx;
frame.CalculateExecutionContext(exe_ctx);
error = argument_values.GetValueAtIndex(0)->GetValueAsData(
- &exe_ctx, data, 0, NULL);
+ &exe_ctx, data, NULL);
lldb::offset_t offset = 0;
lldb::addr_t fn_ptr_addr = data.GetPointer(&offset);
Address fn_ptr_address; | 1 | //===-- SwiftLanguageRuntime.cpp --------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "lldb/Target/SwiftLanguageRuntime.h"
#include <string.h>
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "swift/ABI/System.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Module.h"
#include "swift/AST/Types.h"
#include "swift/AST/ASTWalker.h"
#include "swift/Basic/SourceLoc.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Demangling/Demangler.h"
#include "swift/Reflection/ReflectionContext.h"
#include "swift/Reflection/TypeRefBuilder.h"
#include "swift/Remote/MemoryReader.h"
#include "swift/Remote/RemoteAddress.h"
#include "swift/RemoteAST/RemoteAST.h"
#include "swift/Runtime/Metadata.h"
#include "lldb/Breakpoint/StoppointCallbackContext.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Mangled.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Section.h"
#include "lldb/Core/UniqueCStringMap.h"
#include "lldb/Core/Value.h"
#include "lldb/Core/ValueObjectConstResult.h"
#include "lldb/DataFormatters/StringPrinter.h"
#include "lldb/DataFormatters/TypeSynthetic.h"
#include "lldb/DataFormatters/ValueObjectPrinter.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/OptionParser.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#include "lldb/Interpreter/CommandObject.h"
#include "lldb/Interpreter/CommandObjectMultiword.h"
#include "lldb/Interpreter/CommandReturnObject.h"
#include "lldb/Interpreter/OptionValueBoolean.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "lldb/Symbol/CompileUnit.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/SwiftASTContext.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Symbol/TypeList.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/ProcessStructReader.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/ThreadPlanRunToAddress.h"
#include "lldb/Target/ThreadPlanStepInRange.h"
#include "lldb/Target/ThreadPlanStepOverRange.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/CleanUp.h"
#include "lldb/Utility/DataBuffer.h"
#include "lldb/Utility/LLDBAssert.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/StringLexer.h"
// FIXME: we should not need this
#include "Plugins/Language/Swift/SwiftFormatters.h"
using namespace lldb;
using namespace lldb_private;
char SwiftLanguageRuntime::ID = 0;
static constexpr std::chrono::seconds g_po_function_timeout(15);
static const char *g_dollar_tau_underscore = u8"$\u03C4_";
static ConstString g_self = ConstString("self");
extern "C" unsigned long long _swift_classIsSwiftMask = 0;
namespace lldb_private {
swift::Type GetSwiftType(void *opaque_ptr) {
return reinterpret_cast<swift::TypeBase *>(opaque_ptr);
}
swift::CanType GetCanonicalSwiftType(void *opaque_ptr) {
return reinterpret_cast<swift::TypeBase *>(opaque_ptr)->getCanonicalType();
}
swift::CanType GetCanonicalSwiftType(const CompilerType &type) {
return GetCanonicalSwiftType(
reinterpret_cast<void *>(type.GetOpaqueQualType()));
}
swift::Type GetSwiftType(const CompilerType &type) {
return GetSwiftType(reinterpret_cast<void *>(type.GetOpaqueQualType()));
}
} // namespace lldb_private
SwiftLanguageRuntime::~SwiftLanguageRuntime() = default;
static bool HasReflectionInfo(ObjectFile *obj_file) {
auto findSectionInObject = [&](std::string name) {
ConstString section_name(name);
SectionSP section_sp =
obj_file->GetSectionList()->FindSectionByName(section_name);
if (section_sp)
return true;
return false;
};
bool hasReflectionSection = false;
hasReflectionSection |= findSectionInObject("__swift5_fieldmd");
hasReflectionSection |= findSectionInObject("__swift5_assocty");
hasReflectionSection |= findSectionInObject("__swift5_builtin");
hasReflectionSection |= findSectionInObject("__swift5_capture");
hasReflectionSection |= findSectionInObject("__swift5_typeref");
hasReflectionSection |= findSectionInObject("__swift5_reflstr");
return hasReflectionSection;
}
void SwiftLanguageRuntime::SetupReflection() {
reflection_ctx.reset(new NativeReflectionContext(this->GetMemoryReader()));
auto &target = m_process->GetTarget();
auto exe_module = target.GetExecutableModule();
if (!exe_module)
return;
auto *obj_file = exe_module->GetObjectFile();
if (!obj_file)
return;
if (obj_file->GetPluginName().GetStringRef().equals("elf"))
return;
Address start_address = obj_file->GetBaseAddress();
auto load_ptr = static_cast<uintptr_t>(start_address.GetLoadAddress(&target));
// Bail out if we can't read the executable instead of crashing.
if (load_ptr == 0 || load_ptr == LLDB_INVALID_ADDRESS)
return;
reflection_ctx.reset(new NativeReflectionContext(this->GetMemoryReader()));
reflection_ctx->addImage(swift::remote::RemoteAddress(load_ptr));
auto module_list = GetTargetRef().GetImages();
module_list.ForEach([&](const ModuleSP &module_sp) -> bool {
auto *obj_file = module_sp->GetObjectFile();
if (!obj_file)
return false;
if (obj_file->GetPluginName().GetStringRef().equals("elf"))
return true;
Address start_address = obj_file->GetBaseAddress();
auto load_ptr = static_cast<uintptr_t>(
start_address.GetLoadAddress(&(m_process->GetTarget())));
if (load_ptr == 0 || load_ptr == LLDB_INVALID_ADDRESS)
return false;
if (HasReflectionInfo(obj_file))
reflection_ctx->addImage(swift::remote::RemoteAddress(load_ptr));
return true;
});
}
SwiftLanguageRuntime::SwiftLanguageRuntime(Process *process)
: LanguageRuntime(process) {
SetupSwiftError();
SetupExclusivity();
SetupReflection();
SetupABIBit();
}
bool SwiftLanguageRuntime::IsABIStable() {
return _swift_classIsSwiftMask == 2;
}
static llvm::Optional<lldb::addr_t>
FindSymbolForSwiftObject(Target &target, ConstString object,
const SymbolType sym_type) {
llvm::Optional<lldb::addr_t> retval;
SymbolContextList sc_list;
if (target.GetImages().FindSymbolsWithNameAndType(object, sym_type,
sc_list)) {
SymbolContext SwiftObject_Class;
if (sc_list.GetSize() == 1 &&
sc_list.GetContextAtIndex(0, SwiftObject_Class)) {
if (SwiftObject_Class.symbol) {
lldb::addr_t SwiftObject_class_addr =
SwiftObject_Class.symbol->GetAddress().GetLoadAddress(&target);
if (SwiftObject_class_addr &&
SwiftObject_class_addr != LLDB_INVALID_ADDRESS)
retval = SwiftObject_class_addr;
}
}
}
return retval;
}
AppleObjCRuntimeV2 *SwiftLanguageRuntime::GetObjCRuntime() {
if (auto objc_runtime = ObjCLanguageRuntime::Get(*GetProcess())) {
if (objc_runtime->GetPluginName() ==
AppleObjCRuntimeV2::GetPluginNameStatic())
return (AppleObjCRuntimeV2 *)objc_runtime;
}
return nullptr;
}
void SwiftLanguageRuntime::SetupSwiftError() {
Target &target(m_process->GetTarget());
if (m_SwiftNativeNSErrorISA.hasValue())
return;
ConstString g_SwiftNativeNSError("__SwiftNativeNSError");
m_SwiftNativeNSErrorISA = FindSymbolForSwiftObject(
target, g_SwiftNativeNSError, eSymbolTypeObjCClass);
}
void SwiftLanguageRuntime::SetupExclusivity() {
Target &target(m_process->GetTarget());
ConstString g_disableExclusivityChecking("_swift_disableExclusivityChecking");
m_dynamic_exclusivity_flag_addr = FindSymbolForSwiftObject(
target, g_disableExclusivityChecking, eSymbolTypeData);
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (log)
log->Printf("SwiftLanguageRuntime: _swift_disableExclusivityChecking = %lu",
m_dynamic_exclusivity_flag_addr ?
*m_dynamic_exclusivity_flag_addr : 0);
}
void SwiftLanguageRuntime::SetupABIBit() {
Target &target(m_process->GetTarget());
ConstString g_objc_debug_swift_stable_abi_bit("objc_debug_swift_stable_abi_bit");
if (FindSymbolForSwiftObject(target, g_objc_debug_swift_stable_abi_bit, eSymbolTypeAny))
_swift_classIsSwiftMask = 2;
else
_swift_classIsSwiftMask = 1;
}
void SwiftLanguageRuntime::ModulesDidLoad(const ModuleList &module_list) {
module_list.ForEach([&](const ModuleSP &module_sp) -> bool {
auto *obj_file = module_sp->GetObjectFile();
if (!obj_file)
return true;
Address start_address = obj_file->GetBaseAddress();
auto load_ptr = static_cast<uintptr_t>(
start_address.GetLoadAddress(&(m_process->GetTarget())));
if (load_ptr == 0 || load_ptr == LLDB_INVALID_ADDRESS)
return false;
if (!reflection_ctx)
return false;
if (HasReflectionInfo(obj_file))
reflection_ctx->addImage(swift::remote::RemoteAddress(load_ptr));
return true;
});
}
static bool GetObjectDescription_ResultVariable(Process *process, Stream &str,
ValueObject &object) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
StreamString expr_string;
expr_string.Printf("Swift._DebuggerSupport.stringForPrintObject(%s)",
object.GetName().GetCString());
if (log)
log->Printf("[GetObjectDescription_ResultVariable] expression: %s",
expr_string.GetData());
ValueObjectSP result_sp;
EvaluateExpressionOptions eval_options;
eval_options.SetLanguage(lldb::eLanguageTypeSwift);
eval_options.SetResultIsInternal(true);
eval_options.SetGenerateDebugInfo(true);
eval_options.SetTimeout(g_po_function_timeout);
auto eval_result = process->GetTarget().EvaluateExpression(
expr_string.GetData(),
process->GetThreadList().GetSelectedThread()->GetSelectedFrame().get(),
result_sp, eval_options);
if (log) {
switch (eval_result) {
case eExpressionCompleted:
log->Printf("[GetObjectDescription_ResultVariable] eExpressionCompleted");
break;
case eExpressionSetupError:
log->Printf(
"[GetObjectDescription_ResultVariable] eExpressionSetupError");
break;
case eExpressionParseError:
log->Printf(
"[GetObjectDescription_ResultVariable] eExpressionParseError");
break;
case eExpressionDiscarded:
log->Printf("[GetObjectDescription_ResultVariable] eExpressionDiscarded");
break;
case eExpressionInterrupted:
log->Printf(
"[GetObjectDescription_ResultVariable] eExpressionInterrupted");
break;
case eExpressionHitBreakpoint:
log->Printf(
"[GetObjectDescription_ResultVariable] eExpressionHitBreakpoint");
break;
case eExpressionTimedOut:
log->Printf("[GetObjectDescription_ResultVariable] eExpressionTimedOut");
break;
case eExpressionResultUnavailable:
log->Printf(
"[GetObjectDescription_ResultVariable] eExpressionResultUnavailable");
break;
case eExpressionStoppedForDebug:
log->Printf(
"[GetObjectDescription_ResultVariable] eExpressionStoppedForDebug");
break;
}
}
// sanitize the result of the expression before moving forward
if (!result_sp) {
if (log)
log->Printf("[GetObjectDescription_ResultVariable] expression generated "
"no result");
return false;
}
if (result_sp->GetError().Fail()) {
if (log)
log->Printf("[GetObjectDescription_ResultVariable] expression generated "
"error: %s",
result_sp->GetError().AsCString());
return false;
}
if (false == result_sp->GetCompilerType().IsValid()) {
if (log)
log->Printf("[GetObjectDescription_ResultVariable] expression generated "
"invalid type");
return false;
}
lldb_private::formatters::StringPrinter::ReadStringAndDumpToStreamOptions
dump_options;
dump_options.SetEscapeNonPrintables(false).SetQuote('\0').SetPrefixToken(
nullptr);
if (lldb_private::formatters::swift::String_SummaryProvider(
*result_sp.get(), str, TypeSummaryOptions()
.SetLanguage(lldb::eLanguageTypeSwift)
.SetCapping(eTypeSummaryUncapped),
dump_options)) {
if (log)
log->Printf("[GetObjectDescription_ResultVariable] expression completed "
"successfully");
return true;
} else {
if (log)
log->Printf("[GetObjectDescription_ResultVariable] expression generated "
"invalid string data");
return false;
}
}
static bool GetObjectDescription_ObjectReference(Process *process, Stream &str,
ValueObject &object) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
StreamString expr_string;
expr_string.Printf("Swift._DebuggerSupport.stringForPrintObject(Swift."
"unsafeBitCast(0x%" PRIx64 ", to: AnyObject.self))",
object.GetValueAsUnsigned(0));
if (log)
log->Printf("[GetObjectDescription_ObjectReference] expression: %s",
expr_string.GetData());
ValueObjectSP result_sp;
EvaluateExpressionOptions eval_options;
eval_options.SetLanguage(lldb::eLanguageTypeSwift);
eval_options.SetResultIsInternal(true);
eval_options.SetGenerateDebugInfo(true);
eval_options.SetTimeout(g_po_function_timeout);
auto eval_result = process->GetTarget().EvaluateExpression(
expr_string.GetData(),
process->GetThreadList().GetSelectedThread()->GetSelectedFrame().get(),
result_sp, eval_options);
if (log) {
switch (eval_result) {
case eExpressionCompleted:
log->Printf(
"[GetObjectDescription_ObjectReference] eExpressionCompleted");
break;
case eExpressionSetupError:
log->Printf(
"[GetObjectDescription_ObjectReference] eExpressionSetupError");
break;
case eExpressionParseError:
log->Printf(
"[GetObjectDescription_ObjectReference] eExpressionParseError");
break;
case eExpressionDiscarded:
log->Printf(
"[GetObjectDescription_ObjectReference] eExpressionDiscarded");
break;
case eExpressionInterrupted:
log->Printf(
"[GetObjectDescription_ObjectReference] eExpressionInterrupted");
break;
case eExpressionHitBreakpoint:
log->Printf(
"[GetObjectDescription_ObjectReference] eExpressionHitBreakpoint");
break;
case eExpressionTimedOut:
log->Printf("[GetObjectDescription_ObjectReference] eExpressionTimedOut");
break;
case eExpressionResultUnavailable:
log->Printf("[GetObjectDescription_ObjectReference] "
"eExpressionResultUnavailable");
break;
case eExpressionStoppedForDebug:
log->Printf(
"[GetObjectDescription_ObjectReference] eExpressionStoppedForDebug");
break;
}
}
// sanitize the result of the expression before moving forward
if (!result_sp) {
if (log)
log->Printf("[GetObjectDescription_ObjectReference] expression generated "
"no result");
return false;
}
if (result_sp->GetError().Fail()) {
if (log)
log->Printf("[GetObjectDescription_ObjectReference] expression generated "
"error: %s",
result_sp->GetError().AsCString());
return false;
}
if (false == result_sp->GetCompilerType().IsValid()) {
if (log)
log->Printf("[GetObjectDescription_ObjectReference] expression generated "
"invalid type");
return false;
}
lldb_private::formatters::StringPrinter::ReadStringAndDumpToStreamOptions
dump_options;
dump_options.SetEscapeNonPrintables(false).SetQuote('\0').SetPrefixToken(
nullptr);
if (lldb_private::formatters::swift::String_SummaryProvider(
*result_sp.get(), str, TypeSummaryOptions()
.SetLanguage(lldb::eLanguageTypeSwift)
.SetCapping(eTypeSummaryUncapped),
dump_options)) {
if (log)
log->Printf("[GetObjectDescription_ObjectReference] expression completed "
"successfully");
return true;
} else {
if (log)
log->Printf("[GetObjectDescription_ObjectReference] expression generated "
"invalid string data");
return false;
}
}
static const ExecutionContextRef *GetSwiftExeCtx(ValueObject &valobj) {
return (valobj.GetPreferredDisplayLanguage() == eLanguageTypeSwift)
? &valobj.GetExecutionContextRef()
: nullptr;
}
static bool GetObjectDescription_ObjectCopy(SwiftLanguageRuntime *runtime,
Process *process, Stream &str,
ValueObject &object) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
ValueObjectSP static_sp(object.GetStaticValue());
CompilerType static_type(static_sp->GetCompilerType());
if (auto non_reference_type = static_type.GetNonReferenceType())
static_type = non_reference_type;
Status error;
// If we are in a generic context, here the static type of the object
// might end up being generic (i.e. <T>). We want to make sure that
// we correctly map the type into context before asking questions or
// printing, as IRGen requires a fully realized type to work on.
auto frame_sp =
process->GetThreadList().GetSelectedThread()->GetSelectedFrame();
auto *swift_ast_ctx =
llvm::dyn_cast_or_null<SwiftASTContext>(static_type.GetTypeSystem());
if (swift_ast_ctx) {
SwiftASTContextLock lock(GetSwiftExeCtx(object));
static_type = runtime->DoArchetypeBindingForType(*frame_sp, static_type);
}
auto stride = 0;
auto opt_stride = static_type.GetByteStride(frame_sp.get());
if (opt_stride)
stride = *opt_stride;
lldb::addr_t copy_location = process->AllocateMemory(
stride, ePermissionsReadable | ePermissionsWritable, error);
if (copy_location == LLDB_INVALID_ADDRESS) {
if (log)
log->Printf("[GetObjectDescription_ObjectCopy] copy_location invalid");
return false;
}
CleanUp cleanup(
[process, copy_location] { process->DeallocateMemory(copy_location); });
DataExtractor data_extractor;
if (0 == static_sp->GetData(data_extractor, error)) {
if (log)
log->Printf("[GetObjectDescription_ObjectCopy] data extraction failed");
return false;
}
if (0 ==
process->WriteMemory(copy_location, data_extractor.GetDataStart(),
data_extractor.GetByteSize(), error)) {
if (log)
log->Printf("[GetObjectDescription_ObjectCopy] memory copy failed");
return false;
}
StreamString expr_string;
expr_string.Printf("Swift._DebuggerSupport.stringForPrintObject(Swift."
"UnsafePointer<%s>(bitPattern: 0x%" PRIx64 ")!.pointee)",
static_type.GetTypeName().GetCString(), copy_location);
if (log)
log->Printf("[GetObjectDescription_ObjectCopy] expression: %s",
expr_string.GetData());
ValueObjectSP result_sp;
EvaluateExpressionOptions eval_options;
eval_options.SetLanguage(lldb::eLanguageTypeSwift);
eval_options.SetResultIsInternal(true);
eval_options.SetGenerateDebugInfo(true);
eval_options.SetTimeout(g_po_function_timeout);
auto eval_result = process->GetTarget().EvaluateExpression(
expr_string.GetData(),
process->GetThreadList().GetSelectedThread()->GetSelectedFrame().get(),
result_sp, eval_options);
if (log) {
switch (eval_result) {
case eExpressionCompleted:
log->Printf("[GetObjectDescription_ObjectCopy] eExpressionCompleted");
break;
case eExpressionSetupError:
log->Printf("[GetObjectDescription_ObjectCopy] eExpressionSetupError");
break;
case eExpressionParseError:
log->Printf("[GetObjectDescription_ObjectCopy] eExpressionParseError");
break;
case eExpressionDiscarded:
log->Printf("[GetObjectDescription_ObjectCopy] eExpressionDiscarded");
break;
case eExpressionInterrupted:
log->Printf("[GetObjectDescription_ObjectCopy] eExpressionInterrupted");
break;
case eExpressionHitBreakpoint:
log->Printf("[GetObjectDescription_ObjectCopy] eExpressionHitBreakpoint");
break;
case eExpressionTimedOut:
log->Printf("[GetObjectDescription_ObjectCopy] eExpressionTimedOut");
break;
case eExpressionResultUnavailable:
log->Printf(
"[GetObjectDescription_ObjectCopy] eExpressionResultUnavailable");
break;
case eExpressionStoppedForDebug:
log->Printf(
"[GetObjectDescription_ObjectCopy] eExpressionStoppedForDebug");
break;
}
}
// sanitize the result of the expression before moving forward
if (!result_sp) {
if (log)
log->Printf(
"[GetObjectDescription_ObjectCopy] expression generated no result");
str.Printf("expression produced no result");
return true;
}
if (result_sp->GetError().Fail()) {
if (log)
log->Printf(
"[GetObjectDescription_ObjectCopy] expression generated error: %s",
result_sp->GetError().AsCString());
str.Printf("expression produced error: %s",
result_sp->GetError().AsCString());
return true;
}
if (false == result_sp->GetCompilerType().IsValid()) {
if (log)
log->Printf("[GetObjectDescription_ObjectCopy] expression generated "
"invalid type");
str.Printf("expression produced invalid result type");
return true;
}
lldb_private::formatters::StringPrinter::ReadStringAndDumpToStreamOptions
dump_options;
dump_options.SetEscapeNonPrintables(false).SetQuote('\0').SetPrefixToken(
nullptr);
if (lldb_private::formatters::swift::String_SummaryProvider(
*result_sp.get(), str, TypeSummaryOptions()
.SetLanguage(lldb::eLanguageTypeSwift)
.SetCapping(eTypeSummaryUncapped),
dump_options)) {
if (log)
log->Printf("[GetObjectDescription_ObjectCopy] expression completed "
"successfully");
} else {
if (log)
log->Printf("[GetObjectDescription_ObjectCopy] expression generated "
"invalid string data");
str.Printf("expression produced unprintable string");
}
return true;
}
static bool IsSwiftResultVariable(ConstString name) {
if (name) {
llvm::StringRef name_sr(name.GetStringRef());
if (name_sr.size() > 2 &&
(name_sr.startswith("$R") || name_sr.startswith("$E")) &&
::isdigit(name_sr[2]))
return true;
}
return false;
}
static bool IsSwiftReferenceType(ValueObject &object) {
CompilerType object_type(object.GetCompilerType());
if (llvm::dyn_cast_or_null<SwiftASTContext>(object_type.GetTypeSystem())) {
Flags type_flags(object_type.GetTypeInfo());
if (type_flags.AllSet(eTypeIsClass | eTypeHasValue |
eTypeInstanceIsPointer))
return true;
}
return false;
}
bool SwiftLanguageRuntime::GetObjectDescription(Stream &str,
ValueObject &object) {
if (object.IsUninitializedReference()) {
str.Printf("<uninitialized>");
return true;
}
if (::IsSwiftResultVariable(object.GetName())) {
// if this thing is a Swift expression result variable, it has two
// properties:
// a) its name is something we can refer to in expressions for free
// b) its type may be something we can't actually talk about in expressions
// so, just use the result variable's name in the expression and be done
// with it
StreamString probe_stream;
if (GetObjectDescription_ResultVariable(m_process, probe_stream, object)) {
str.Printf("%s", probe_stream.GetData());
return true;
}
} else if (::IsSwiftReferenceType(object)) {
// if this is a Swift class, it has two properties:
// a) we do not need its type name, AnyObject is just as good
// b) its value is something we can directly use to refer to it
// so, just use the ValueObject's pointer-value and be done with it
StreamString probe_stream;
if (GetObjectDescription_ObjectReference(m_process, probe_stream, object)) {
str.Printf("%s", probe_stream.GetData());
return true;
}
}
// in general, don't try to use the name of the ValueObject as it might end up
// referring to the wrong thing
return GetObjectDescription_ObjectCopy(this, m_process, str, object);
}
bool SwiftLanguageRuntime::GetObjectDescription(
Stream &str, Value &value, ExecutionContextScope *exe_scope) {
// This is only interesting to do with a ValueObject for Swift
return false;
}
bool SwiftLanguageRuntime::IsSwiftMangledName(const char *name) {
return swift::Demangle::isSwiftSymbol(name);
}
void SwiftLanguageRuntime::GetGenericParameterNamesForFunction(
const SymbolContext &const_sc,
llvm::DenseMap<SwiftLanguageRuntime::ArchetypePath, StringRef> &dict) {
// This terrifying cast avoids having too many differences with llvm.org.
SymbolContext &sc = const_cast<SymbolContext &>(const_sc);
// While building the Symtab itself the symbol context is incomplete.
// Note that calling sc.module_sp->FindFunctions() here is too early and
// would mess up the loading process.
if (!sc.function && sc.module_sp && sc.symbol)
return;
Block *block = sc.GetFunctionBlock();
if (!block)
return;
bool can_create = true;
VariableListSP var_list = block->GetBlockVariableList(can_create);
if (!var_list)
return;
for (unsigned i = 0; i < var_list->GetSize(); ++i) {
VariableSP var_sp = var_list->GetVariableAtIndex(i);
StringRef name = var_sp->GetName().GetStringRef();
if (!name.consume_front(g_dollar_tau_underscore))
continue;
uint64_t depth;
if (name.consumeInteger(10, depth))
continue;
if (!name.consume_front("_"))
continue;
uint64_t index;
if (name.consumeInteger(10, index))
continue;
if (!name.empty())
continue;
Type *archetype = var_sp->GetType();
if (!archetype)
continue;
dict.insert({{depth, index}, archetype->GetName().GetStringRef()});
}
}
std::string
SwiftLanguageRuntime::DemangleSymbolAsString(StringRef symbol, bool simplified,
const SymbolContext *sc) {
bool did_init = false;
llvm::DenseMap<ArchetypePath, StringRef> dict;
swift::Demangle::DemangleOptions options;
if (simplified)
options = swift::Demangle::DemangleOptions::SimplifiedUIDemangleOptions();
if (sc) {
options.GenericParameterName = [&](uint64_t depth, uint64_t index) {
if (!did_init) {
GetGenericParameterNamesForFunction(*sc, dict);
did_init = true;
}
auto it = dict.find({depth, index});
if (it != dict.end())
return it->second.str();
return swift::Demangle::genericParameterName(depth, index);
};
}
return swift::Demangle::demangleSymbolAsString(symbol, options);
}
bool SwiftLanguageRuntime::IsSwiftClassName(const char *name)
{
return swift::Demangle::isClass(name);
}
const std::string SwiftLanguageRuntime::GetCurrentMangledName(const char *mangled_name)
{
#ifndef USE_NEW_MANGLING
return std::string(mangled_name);
#else
//FIXME: Check if we need to cache these lookups...
swift::Demangle::Context demangle_ctx;
swift::Demangle::NodePointer node_ptr = demangle_ctx.demangleSymbolAsNode(mangled_name);
if (!node_ptr)
{
// Sometimes this gets passed the prefix of a name, in which case we
// won't be able to demangle it. In that case return what was passed in.
printf ("Couldn't get mangled name for %s.\n", mangled_name);
return mangled_name;
}
else
return swift::Demangle::mangleNode(node_ptr);
#endif
}
void SwiftLanguageRuntime::MethodName::Clear() {
m_full.Clear();
m_basename = llvm::StringRef();
m_context = llvm::StringRef();
m_arguments = llvm::StringRef();
m_qualifiers = llvm::StringRef();
m_template_args = llvm::StringRef();
m_metatype_ref = llvm::StringRef();
m_return_type = llvm::StringRef();
m_type = eTypeInvalid;
m_parsed = false;
m_parse_error = false;
}
static bool StringHasAllOf(const llvm::StringRef &s, const char *which) {
for (const char *c = which; *c != 0; c++) {
if (s.find(*c) == llvm::StringRef::npos)
return false;
}
return true;
}
static bool StringHasAnyOf(const llvm::StringRef &s,
std::initializer_list<const char *> which,
size_t &where) {
for (const char *item : which) {
size_t where_item = s.find(item);
if (where_item != llvm::StringRef::npos) {
where = where_item;
return true;
}
}
where = llvm::StringRef::npos;
return false;
}
static bool UnpackTerminatedSubstring(const llvm::StringRef &s,
const char start, const char stop,
llvm::StringRef &dest) {
size_t pos_of_start = s.find(start);
if (pos_of_start == llvm::StringRef::npos)
return false;
size_t pos_of_stop = s.rfind(stop);
if (pos_of_stop == llvm::StringRef::npos)
return false;
size_t token_count = 1;
size_t idx = pos_of_start + 1;
while (idx < s.size()) {
if (s[idx] == start)
++token_count;
if (s[idx] == stop) {
if (token_count == 1) {
dest = s.slice(pos_of_start, idx + 1);
return true;
}
}
idx++;
}
return false;
}
static bool UnpackQualifiedName(const llvm::StringRef &s, llvm::StringRef &decl,
llvm::StringRef &basename, bool &was_operator) {
size_t pos_of_dot = s.rfind('.');
if (pos_of_dot == llvm::StringRef::npos)
return false;
decl = s.substr(0, pos_of_dot);
basename = s.substr(pos_of_dot + 1);
size_t idx_of_operator;
was_operator = StringHasAnyOf(basename, {"@infix", "@prefix", "@postfix"},
idx_of_operator);
if (was_operator)
basename = basename.substr(0, idx_of_operator - 1);
return !decl.empty() && !basename.empty();
}
static bool ParseLocalDeclName(const swift::Demangle::NodePointer &node,
StreamString &identifier,
swift::Demangle::Node::Kind &parent_kind,
swift::Demangle::Node::Kind &kind) {
swift::Demangle::Node::iterator end = node->end();
for (swift::Demangle::Node::iterator pos = node->begin(); pos != end; ++pos) {
swift::Demangle::NodePointer child = *pos;
swift::Demangle::Node::Kind child_kind = child->getKind();
switch (child_kind) {
case swift::Demangle::Node::Kind::Number:
break;
default:
if (child->hasText()) {
identifier.PutCString(child->getText());
return true;
}
break;
}
}
return false;
}
static bool ParseFunction(const swift::Demangle::NodePointer &node,
StreamString &identifier,
swift::Demangle::Node::Kind &parent_kind,
swift::Demangle::Node::Kind &kind) {
swift::Demangle::Node::iterator end = node->end();
swift::Demangle::Node::iterator pos = node->begin();
// First child is the function's scope
parent_kind = (*pos)->getKind();
++pos;
// Second child is either the type (no identifier)
if (pos != end) {
switch ((*pos)->getKind()) {
case swift::Demangle::Node::Kind::Type:
break;
case swift::Demangle::Node::Kind::LocalDeclName:
if (ParseLocalDeclName(*pos, identifier, parent_kind, kind))
return true;
else
return false;
break;
default:
case swift::Demangle::Node::Kind::InfixOperator:
case swift::Demangle::Node::Kind::PostfixOperator:
case swift::Demangle::Node::Kind::PrefixOperator:
case swift::Demangle::Node::Kind::Identifier:
if ((*pos)->hasText())
identifier.PutCString((*pos)->getText());
return true;
}
}
return false;
}
static bool ParseGlobal(const swift::Demangle::NodePointer &node,
StreamString &identifier,
swift::Demangle::Node::Kind &parent_kind,
swift::Demangle::Node::Kind &kind) {
swift::Demangle::Node::iterator end = node->end();
for (swift::Demangle::Node::iterator pos = node->begin(); pos != end; ++pos) {
swift::Demangle::NodePointer child = *pos;
if (child) {
kind = child->getKind();
switch (child->getKind()) {
case swift::Demangle::Node::Kind::Allocator:
identifier.PutCString("__allocating_init");
ParseFunction(child, identifier, parent_kind, kind);
return true;
case swift::Demangle::Node::Kind::Constructor:
identifier.PutCString("init");
ParseFunction(child, identifier, parent_kind, kind);
return true;
case swift::Demangle::Node::Kind::Deallocator:
identifier.PutCString("__deallocating_deinit");
ParseFunction(child, identifier, parent_kind, kind);
return true;
case swift::Demangle::Node::Kind::Destructor:
identifier.PutCString("deinit");
ParseFunction(child, identifier, parent_kind, kind);
return true;
case swift::Demangle::Node::Kind::Getter:
case swift::Demangle::Node::Kind::Setter:
case swift::Demangle::Node::Kind::Function:
return ParseFunction(child, identifier, parent_kind, kind);
// Ignore these, they decorate a function at the same level, but don't
// contain any text
case swift::Demangle::Node::Kind::ObjCAttribute:
break;
default:
return false;
}
}
}
return false;
}
bool SwiftLanguageRuntime::MethodName::ExtractFunctionBasenameFromMangled(
ConstString mangled, ConstString &basename, bool &is_method) {
bool success = false;
swift::Demangle::Node::Kind kind = swift::Demangle::Node::Kind::Global;
swift::Demangle::Node::Kind parent_kind = swift::Demangle::Node::Kind::Global;
if (mangled) {
const char *mangled_cstr = mangled.GetCString();
const size_t mangled_cstr_len = mangled.GetLength();
if (mangled_cstr_len > 3) {
llvm::StringRef mangled_ref(mangled_cstr, mangled_cstr_len);
// Only demangle swift functions
// This is a no-op right now for the new mangling, because you
// have to demangle the whole name to figure this out anyway.
// I'm leaving the test here in case we actually need to do this
// only to functions.
swift::Demangle::Context demangle_ctx;
swift::Demangle::NodePointer node =
demangle_ctx.demangleSymbolAsNode(mangled_ref);
StreamString identifier;
if (node) {
switch (node->getKind()) {
case swift::Demangle::Node::Kind::Global:
success = ParseGlobal(node, identifier, parent_kind, kind);
break;
default:
break;
}
if (!identifier.GetString().empty()) {
basename = ConstString(identifier.GetString());
}
}
}
}
if (success) {
switch (kind) {
case swift::Demangle::Node::Kind::Allocator:
case swift::Demangle::Node::Kind::Constructor:
case swift::Demangle::Node::Kind::Deallocator:
case swift::Demangle::Node::Kind::Destructor:
is_method = true;
break;
case swift::Demangle::Node::Kind::Getter:
case swift::Demangle::Node::Kind::Setter:
// don't handle getters and setters right now...
return false;
case swift::Demangle::Node::Kind::Function:
switch (parent_kind) {
case swift::Demangle::Node::Kind::BoundGenericClass:
case swift::Demangle::Node::Kind::BoundGenericEnum:
case swift::Demangle::Node::Kind::BoundGenericStructure:
case swift::Demangle::Node::Kind::Class:
case swift::Demangle::Node::Kind::Enum:
case swift::Demangle::Node::Kind::Structure:
is_method = true;
break;
default:
break;
}
break;
default:
break;
}
}
return success;
}
void SwiftLanguageRuntime::MethodName::Parse() {
if (!m_parsed && m_full) {
m_parse_error = false;
m_parsed = true;
llvm::StringRef full(m_full.GetCString());
bool was_operator = false;
if (full.find("::") != llvm::StringRef::npos) {
// :: is not an allowed operator in Swift (func ::(...) { fails to
// compile)
// but it's a very legitimate token in C++ - as a defense, reject anything
// with a :: in it as invalid Swift
m_parse_error = true;
return;
}
if (StringHasAllOf(full, ".:()")) {
const size_t open_paren = full.find(" (");
llvm::StringRef funcname = full.substr(0, open_paren);
UnpackQualifiedName(funcname, m_context, m_basename, was_operator);
if (was_operator)
m_type = eTypeOperator;
// check for obvious constructor/destructor cases
else if (m_basename.equals("__deallocating_destructor"))
m_type = eTypeDeallocator;
else if (m_basename.equals("__allocating_constructor"))
m_type = eTypeAllocator;
else if (m_basename.equals("init"))
m_type = eTypeConstructor;
else if (m_basename.equals("destructor"))
m_type = eTypeDestructor;
else
m_type = eTypeUnknownMethod;
const size_t idx_of_colon =
full.find(':', open_paren == llvm::StringRef::npos ? 0 : open_paren);
full = full.substr(idx_of_colon + 2);
if (full.empty())
return;
if (full[0] == '<') {
if (UnpackTerminatedSubstring(full, '<', '>', m_template_args)) {
full = full.substr(m_template_args.size());
} else {
m_parse_error = true;
return;
}
}
if (full.empty())
return;
if (full[0] == '(') {
if (UnpackTerminatedSubstring(full, '(', ')', m_metatype_ref)) {
full = full.substr(m_template_args.size());
if (full[0] == '<') {
if (UnpackTerminatedSubstring(full, '<', '>', m_template_args)) {
full = full.substr(m_template_args.size());
} else {
m_parse_error = true;
return;
}
}
} else {
m_parse_error = true;
return;
}
}
if (full.empty())
return;
if (full[0] == '(') {
if (UnpackTerminatedSubstring(full, '(', ')', m_arguments)) {
full = full.substr(m_template_args.size());
} else {
m_parse_error = true;
return;
}
}
if (full.empty())
return;
size_t idx_of_ret = full.find("->");
if (idx_of_ret == llvm::StringRef::npos) {
full = full.substr(idx_of_ret);
if (full.empty()) {
m_parse_error = true;
return;
}
if (full[0] == ' ')
full = full.substr(1);
m_return_type = full;
}
} else if (full.find('.') != llvm::StringRef::npos) {
// this is probably just a full name (module.type.func)
UnpackQualifiedName(full, m_context, m_basename, was_operator);
if (was_operator)
m_type = eTypeOperator;
else
m_type = eTypeUnknownMethod;
} else {
// this is most probably just a basename
m_basename = full;
m_type = eTypeUnknownMethod;
}
}
}
llvm::StringRef SwiftLanguageRuntime::MethodName::GetBasename() {
if (!m_parsed)
Parse();
return m_basename;
}
const CompilerType &SwiftLanguageRuntime::GetBoxMetadataType() {
if (m_box_metadata_type.IsValid())
return m_box_metadata_type;
static ConstString g_type_name("__lldb_autogen_boxmetadata");
const bool is_packed = false;
if (ClangASTContext *ast_ctx =
GetProcess()->GetTarget().GetScratchClangASTContext()) {
CompilerType voidstar =
ast_ctx->GetBasicType(lldb::eBasicTypeVoid).GetPointerType();
CompilerType uint32 = ClangASTContext::GetIntTypeFromBitSize(
ast_ctx->getASTContext(), 32, false);
m_box_metadata_type = ast_ctx->GetOrCreateStructForIdentifier(
g_type_name, {{"kind", voidstar}, {"offset", uint32}}, is_packed);
}
return m_box_metadata_type;
}
class LLDBMemoryReader : public swift::remote::MemoryReader {
public:
LLDBMemoryReader(Process *p, size_t max_read_amount = INT32_MAX)
: m_process(p) {
lldbassert(m_process && "MemoryReader requires a valid Process");
m_max_read_amount = max_read_amount;
}
virtual ~LLDBMemoryReader() = default;
bool queryDataLayout(DataLayoutQueryType type, void *inBuffer,
void *outBuffer) override {
switch (type) {
case DLQ_GetPointerSize: {
auto result = static_cast<uint8_t *>(outBuffer);
*result = m_process->GetAddressByteSize();
return true;
}
case DLQ_GetSizeSize: {
auto result = static_cast<uint8_t *>(outBuffer);
*result = m_process->GetAddressByteSize(); // FIXME: sizeof(size_t)
return true;
}
}
return false;
}
swift::remote::RemoteAddress
getSymbolAddress(const std::string &name) override {
lldbassert(!name.empty());
if (name.empty())
return swift::remote::RemoteAddress(nullptr);
LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES),
"[MemoryReader] asked to retrieve the address of symbol {0}",
name);
ConstString name_cs(name.c_str(), name.size());
SymbolContextList sc_list;
if (!m_process->GetTarget().GetImages().FindSymbolsWithNameAndType(
name_cs, lldb::eSymbolTypeAny, sc_list)) {
LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES),
"[MemoryReader] symbol resoution failed {0}", name);
return swift::remote::RemoteAddress(nullptr);
}
SymbolContext sym_ctx;
// Remove undefined symbols from the list.
size_t num_sc_matches = sc_list.GetSize();
if (num_sc_matches > 1) {
SymbolContextList tmp_sc_list(sc_list);
sc_list.Clear();
for (size_t idx = 0; idx < num_sc_matches; idx++) {
tmp_sc_list.GetContextAtIndex(idx, sym_ctx);
if (sym_ctx.symbol &&
sym_ctx.symbol->GetType() != lldb::eSymbolTypeUndefined) {
sc_list.Append(sym_ctx);
}
}
}
if (sc_list.GetSize() == 1 && sc_list.GetContextAtIndex(0, sym_ctx)) {
if (sym_ctx.symbol) {
auto load_addr =
sym_ctx.symbol->GetLoadAddress(&m_process->GetTarget());
LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES),
"[MemoryReader] symbol resolved to 0x%" PRIx64, load_addr);
return swift::remote::RemoteAddress(load_addr);
}
}
// Empty list, resolution failed.
if (sc_list.GetSize() == 0) {
LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES),
"[MemoryReader] symbol resoution failed {0}", name);
return swift::remote::RemoteAddress(nullptr);
}
// If there's a single symbol, then we're golden. If there's more than
// a symbol, then just make sure all of them agree on the value.
Status error;
auto sym = sc_list.GetContextAtIndex(0, sym_ctx);
auto load_addr = sym_ctx.symbol->GetLoadAddress(&m_process->GetTarget());
uint64_t sym_value = m_process->GetTarget().ReadUnsignedIntegerFromMemory(
load_addr, false, m_process->GetAddressByteSize(), 0, error);
for (unsigned i = 1; i < sc_list.GetSize(); ++i) {
auto other_sym = sc_list.GetContextAtIndex(i, sym_ctx);
auto other_load_addr =
sym_ctx.symbol->GetLoadAddress(&m_process->GetTarget());
uint64_t other_sym_value =
m_process->GetTarget().ReadUnsignedIntegerFromMemory(
load_addr, false, m_process->GetAddressByteSize(), 0, error);
if (sym_value != other_sym_value) {
LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES),
"[MemoryReader] symbol resoution failed {0}", name);
return swift::remote::RemoteAddress(nullptr);
}
}
LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES),
"[MemoryReader] symbol resolved to {0}", load_addr);
return swift::remote::RemoteAddress(load_addr);
}
bool readBytes(swift::remote::RemoteAddress address, uint8_t *dest,
uint64_t size) override {
if (m_local_buffer) {
auto addr = address.getAddressData();
if (addr >= m_local_buffer &&
addr + size <= m_local_buffer + m_local_buffer_size) {
// If this crashes, the assumptions stated in
// GetDynamicTypeAndAddress_Protocol() most likely no longer
// hold.
memcpy(dest, (void *) addr, size);
return true;
}
}
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("[MemoryReader] asked to read %" PRIu64
" bytes at address 0x%" PRIx64,
size, address.getAddressData());
if (size > m_max_read_amount) {
if (log)
log->Printf(
"[MemoryReader] memory read exceeds maximum allowed size");
return false;
}
Target &target(m_process->GetTarget());
Address addr(address.getAddressData());
Status error;
if (size > target.ReadMemory(addr, false, dest, size, error)) {
if (log)
log->Printf(
"[MemoryReader] memory read returned fewer bytes than asked for");
return false;
}
if (error.Fail()) {
if (log)
log->Printf("[MemoryReader] memory read returned error: %s",
error.AsCString());
return false;
}
if (log && log->GetVerbose()) {
StreamString stream;
for (uint64_t i = 0; i < size; i++) {
stream.PutHex8(dest[i]);
stream.PutChar(' ');
}
log->Printf("[MemoryReader] memory read returned data: %s",
stream.GetData());
}
return true;
}
bool readString(swift::remote::RemoteAddress address,
std::string &dest) override {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf(
"[MemoryReader] asked to read string data at address 0x%" PRIx64,
address.getAddressData());
uint32_t read_size = 50 * 1024;
std::vector<char> storage(read_size, 0);
Target &target(m_process->GetTarget());
Address addr(address.getAddressData());
Status error;
target.ReadCStringFromMemory(addr, &storage[0], storage.size(), error);
if (error.Success()) {
dest.assign(&storage[0]);
if (log)
log->Printf("[MemoryReader] memory read returned data: %s",
dest.c_str());
return true;
} else {
if (log)
log->Printf("[MemoryReader] memory read returned error: %s",
error.AsCString());
return false;
}
}
void pushLocalBuffer(uint64_t local_buffer, uint64_t local_buffer_size) {
lldbassert(!m_local_buffer);
m_local_buffer = local_buffer;
m_local_buffer_size = local_buffer_size;
}
void popLocalBuffer() {
lldbassert(m_local_buffer);
m_local_buffer = 0;
m_local_buffer_size = 0;
}
private:
Process *m_process;
size_t m_max_read_amount;
uint64_t m_local_buffer = 0;
uint64_t m_local_buffer_size = 0;
};
std::shared_ptr<swift::remote::MemoryReader>
SwiftLanguageRuntime::GetMemoryReader() {
if (!m_memory_reader_sp)
m_memory_reader_sp.reset(new LLDBMemoryReader(GetProcess()));
return m_memory_reader_sp;
}
void SwiftLanguageRuntime::PushLocalBuffer(uint64_t local_buffer,
uint64_t local_buffer_size) {
((LLDBMemoryReader *)GetMemoryReader().get())->pushLocalBuffer(
local_buffer, local_buffer_size);
}
void SwiftLanguageRuntime::PopLocalBuffer() {
((LLDBMemoryReader *)GetMemoryReader().get())->popLocalBuffer();
}
SwiftLanguageRuntime::MetadataPromise::MetadataPromise(
ValueObject &for_object, SwiftLanguageRuntime &runtime,
lldb::addr_t location)
: m_for_object_sp(for_object.GetSP()), m_swift_runtime(runtime),
m_metadata_location(location) {}
CompilerType
SwiftLanguageRuntime::MetadataPromise::FulfillTypePromise(Status *error) {
if (error)
error->Clear();
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("[MetadataPromise] asked to fulfill type promise at location "
"0x%" PRIx64,
m_metadata_location);
if (m_compiler_type.hasValue())
return m_compiler_type.getValue();
auto swift_ast_ctx = m_for_object_sp->GetScratchSwiftASTContext();
if (!swift_ast_ctx) {
error->SetErrorString("couldn't get Swift scratch context");
return CompilerType();
}
auto &remote_ast = m_swift_runtime.GetRemoteASTContext(*swift_ast_ctx);
swift::remoteAST::Result<swift::Type> result =
remote_ast.getTypeForRemoteTypeMetadata(
swift::remote::RemoteAddress(m_metadata_location));
if (result) {
m_compiler_type = {swift_ast_ctx.get(), result.getValue().getPointer()};
if (log)
log->Printf("[MetadataPromise] result is type %s",
m_compiler_type->GetTypeName().AsCString());
return m_compiler_type.getValue();
} else {
const auto &failure = result.getFailure();
if (error)
error->SetErrorStringWithFormat("error in resolving type: %s",
failure.render().c_str());
if (log)
log->Printf("[MetadataPromise] failure: %s", failure.render().c_str());
return (m_compiler_type = CompilerType()).getValue();
}
}
llvm::Optional<swift::MetadataKind>
SwiftLanguageRuntime::MetadataPromise::FulfillKindPromise(Status *error) {
if (error)
error->Clear();
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("[MetadataPromise] asked to fulfill kind promise at location "
"0x%" PRIx64,
m_metadata_location);
if (m_metadata_kind.hasValue())
return m_metadata_kind;
auto swift_ast_ctx = m_for_object_sp->GetScratchSwiftASTContext();
if (!swift_ast_ctx) {
error->SetErrorString("couldn't get Swift scratch context");
return llvm::None;
}
auto &remote_ast = m_swift_runtime.GetRemoteASTContext(*swift_ast_ctx);
swift::remoteAST::Result<swift::MetadataKind> result =
remote_ast.getKindForRemoteTypeMetadata(
swift::remote::RemoteAddress(m_metadata_location));
if (result) {
m_metadata_kind = result.getValue();
if (log)
log->Printf("[MetadataPromise] result is kind %u", result.getValue());
return m_metadata_kind;
} else {
const auto &failure = result.getFailure();
if (error)
error->SetErrorStringWithFormat("error in resolving type: %s",
failure.render().c_str());
if (log)
log->Printf("[MetadataPromise] failure: %s", failure.render().c_str());
return m_metadata_kind;
}
}
bool SwiftLanguageRuntime::MetadataPromise::IsStaticallyDetermined() {
if (llvm::Optional<swift::MetadataKind> kind_promise = FulfillKindPromise()) {
switch (kind_promise.getValue()) {
case swift::MetadataKind::Class:
case swift::MetadataKind::Existential:
case swift::MetadataKind::ObjCClassWrapper:
return false;
default:
return true;
}
}
llvm_unreachable("Unknown metadata kind");
}
SwiftLanguageRuntime::MetadataPromiseSP
SwiftLanguageRuntime::GetMetadataPromise(lldb::addr_t addr,
ValueObject &for_object) {
auto swift_ast_ctx = for_object.GetScratchSwiftASTContext();
if (!swift_ast_ctx || swift_ast_ctx->HasFatalErrors())
return nullptr;
if (addr == 0 || addr == LLDB_INVALID_ADDRESS)
return nullptr;
typename decltype(m_promises_map)::key_type key{
swift_ast_ctx->GetASTContext(), addr};
auto iter = m_promises_map.find(key), end = m_promises_map.end();
if (iter != end)
return iter->second;
MetadataPromiseSP promise_sp(
new MetadataPromise(for_object, *this, std::get<1>(key)));
m_promises_map.emplace(key, promise_sp);
return promise_sp;
}
swift::remoteAST::RemoteASTContext &
SwiftLanguageRuntime::GetRemoteASTContext(SwiftASTContext &swift_ast_ctx) {
// If we already have a remote AST context for this AST context,
// return it.
auto known = m_remote_ast_contexts.find(swift_ast_ctx.GetASTContext());
if (known != m_remote_ast_contexts.end())
return *known->second;
// Initialize a new remote AST context.
return *m_remote_ast_contexts
.emplace(swift_ast_ctx.GetASTContext(),
llvm::make_unique<swift::remoteAST::RemoteASTContext>(
*swift_ast_ctx.GetASTContext(), GetMemoryReader()))
.first->second;
}
void SwiftLanguageRuntime::ReleaseAssociatedRemoteASTContext(
swift::ASTContext *ctx) {
m_remote_ast_contexts.erase(ctx);
}
namespace {
class ASTVerifier : public swift::ASTWalker {
bool hasMissingPatterns = false;
bool walkToDeclPre(swift::Decl *D) override {
if (auto *PBD = llvm::dyn_cast<swift::PatternBindingDecl>(D)) {
if (PBD->getPatternList().empty()) {
hasMissingPatterns = true;
return false;
}
}
return true;
}
public:
/// Detect (one form of) incomplete types. These may appear if
/// member variables have Clang-imported types that couldn't be
/// resolved.
static bool Verify(swift::Decl *D) {
if (!D)
return false;
ASTVerifier verifier;
D->walk(verifier);
return !verifier.hasMissingPatterns;
}
};
}
llvm::Optional<uint64_t>
SwiftLanguageRuntime::GetMemberVariableOffset(CompilerType instance_type,
ValueObject *instance,
ConstString member_name,
Status *error) {
if (!instance_type.IsValid())
return llvm::None;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
// Using the module context for RemoteAST is cheaper bit only safe
// when there is no dynamic type resolution involved.
auto *module_ctx =
llvm::dyn_cast_or_null<SwiftASTContext>(instance_type.GetTypeSystem());
if (!module_ctx || module_ctx->HasFatalErrors())
return llvm::None;
llvm::Optional<SwiftASTContextReader> scratch_ctx;
if (instance) {
scratch_ctx = instance->GetScratchSwiftASTContext();
if (!scratch_ctx)
return llvm::None;
}
auto *remote_ast = &GetRemoteASTContext(*module_ctx);
if (log)
log->Printf(
"[GetMemberVariableOffset] asked to resolve offset for member %s",
member_name.AsCString());
// Check whether we've already cached this offset.
auto *swift_type = GetCanonicalSwiftType(instance_type).getPointer();
// Perform the cache lookup.
auto key = std::make_tuple(swift_type, member_name.GetCString());
auto it = m_member_offsets.find(key);
if (it != m_member_offsets.end())
return it->second;
// Dig out metadata describing the type, if it's easy to find.
// FIXME: the Remote AST library should make this easier.
swift::remote::RemoteAddress optmeta(nullptr);
const swift::TypeKind type_kind = swift_type->getKind();
switch (type_kind) {
case swift::TypeKind::Class:
case swift::TypeKind::BoundGenericClass: {
if (log)
log->Printf("[MemberVariableOffsetResolver] type is a class - trying to "
"get metadata for valueobject %s",
(instance ? instance->GetName().AsCString() : "<null>"));
if (instance) {
lldb::addr_t pointer = instance->GetPointerValue();
if (!pointer || pointer == LLDB_INVALID_ADDRESS)
break;
swift::remote::RemoteAddress address(pointer);
if (auto metadata = remote_ast->getHeapMetadataForObject(address))
optmeta = metadata.getValue();
}
if (log)
log->Printf("[MemberVariableOffsetResolver] optmeta = 0x%" PRIx64,
optmeta.getAddressData());
break;
}
default:
// Bind generic parameters if necessary.
if (instance && swift_type->hasTypeParameter())
if (auto *frame = instance->GetExecutionContextRef().GetFrameSP().get())
if (auto bound = DoArchetypeBindingForType(*frame, instance_type)) {
if (log)
log->Printf(
"[MemberVariableOffsetResolver] resolved non-class type = %s",
bound.GetTypeName().AsCString());
swift_type = GetCanonicalSwiftType(bound).getPointer();
auto key = std::make_tuple(swift_type, member_name.GetCString());
auto it = m_member_offsets.find(key);
if (it != m_member_offsets.end())
return it->second;
assert(bound.GetTypeSystem() == scratch_ctx->get());
remote_ast = &GetRemoteASTContext(*scratch_ctx->get());
}
}
// Try to determine whether it is safe to use RemoteAST. RemoteAST
// is faster than RemoteMirrors, but can't do dynamic types (checked
// inside RemoteAST) or incomplete types (checked here).
bool safe_to_use_remote_ast = true;
if (swift::Decl *type_decl = swift_type->getNominalOrBoundGenericNominal())
safe_to_use_remote_ast &= ASTVerifier::Verify(type_decl);
// Use RemoteAST to determine the member offset.
if (safe_to_use_remote_ast) {
swift::remoteAST::Result<uint64_t> result = remote_ast->getOffsetOfMember(
swift_type, optmeta, member_name.GetStringRef());
if (result) {
if (log)
log->Printf(
"[MemberVariableOffsetResolver] offset discovered = %" PRIu64,
(uint64_t)result.getValue());
// Cache this result.
auto key = std::make_tuple(swift_type, member_name.GetCString());
m_member_offsets.insert(std::make_pair(key, result.getValue()));
return result.getValue();
}
const auto &failure = result.getFailure();
if (error)
error->SetErrorStringWithFormat("error in resolving type offset: %s",
failure.render().c_str());
if (log)
log->Printf("[MemberVariableOffsetResolver] failure: %s",
failure.render().c_str());
}
// Try remote mirrors.
const swift::reflection::TypeInfo *type_info = GetTypeInfo(instance_type);
if (!type_info)
return llvm::None;
auto record_type_info =
llvm::dyn_cast<swift::reflection::RecordTypeInfo>(type_info);
if (record_type_info) {
// Handle tuples.
if (record_type_info->getRecordKind() ==
swift::reflection::RecordKind::Tuple) {
unsigned tuple_idx;
if (member_name.GetStringRef().getAsInteger(10, tuple_idx) ||
tuple_idx >= record_type_info->getNumFields()) {
if (error)
error->SetErrorString("tuple index out of bounds");
return llvm::None;
}
return record_type_info->getFields()[tuple_idx].Offset;
}
// Handle other record types.
for (auto &field : record_type_info->getFields()) {
if (ConstString(field.Name) == member_name)
return field.Offset;
}
}
lldb::addr_t pointer = instance->GetPointerValue();
auto class_instance_type_info = reflection_ctx->getInstanceTypeInfo(pointer);
if (class_instance_type_info) {
auto class_type_info = llvm::dyn_cast<swift::reflection::RecordTypeInfo>(
class_instance_type_info);
if (class_type_info) {
for (auto &field : class_type_info->getFields()) {
if (ConstString(field.Name) == member_name)
return field.Offset;
}
}
}
return llvm::None;
}
bool SwiftLanguageRuntime::IsSelf(Variable &variable) {
// A variable is self if its name if "self", and it's either a
// function argument or a local variable and it's scope is a
// constructor. These checks are sorted from cheap to expensive.
if (variable.GetUnqualifiedName() != g_self)
return false;
if (variable.GetScope() == lldb::eValueTypeVariableArgument)
return true;
if (variable.GetScope() != lldb::eValueTypeVariableLocal)
return false;
SymbolContextScope *sym_ctx_scope = variable.GetSymbolContextScope();
if (!sym_ctx_scope)
return false;
Function *function = sym_ctx_scope->CalculateSymbolContextFunction();
if (!function)
return false;
StringRef func_name = function->GetMangled().GetMangledName().GetStringRef();
swift::Demangle::Context demangle_ctx;
swift::Demangle::NodePointer node_ptr =
demangle_ctx.demangleSymbolAsNode(func_name);
if (!node_ptr)
return false;
if (node_ptr->getKind() != swift::Demangle::Node::Kind::Global)
return false;
if (node_ptr->getNumChildren() != 1)
return false;
node_ptr = node_ptr->getFirstChild();
return node_ptr->getKind() == swift::Demangle::Node::Kind::Constructor;
}
/// Determine whether the scratch SwiftASTContext has been locked.
static bool IsScratchContextLocked(Target &target) {
if (target.GetSwiftScratchContextLock().try_lock()) {
target.GetSwiftScratchContextLock().unlock();
return false;
}
return true;
}
/// Determine whether the scratch SwiftASTContext has been locked.
static bool IsScratchContextLocked(TargetSP target) {
return target ? IsScratchContextLocked(*target) : true;
}
bool SwiftLanguageRuntime::GetDynamicTypeAndAddress_Class(
ValueObject &in_value, SwiftASTContext &scratch_ctx,
lldb::DynamicValueType use_dynamic, TypeAndOrName &class_type_or_name,
Address &address) {
AddressType address_type;
lldb::addr_t class_metadata_ptr = in_value.GetPointerValue(&address_type);
if (class_metadata_ptr == LLDB_INVALID_ADDRESS || class_metadata_ptr == 0)
return false;
address.SetRawAddress(class_metadata_ptr);
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
auto &remote_ast = GetRemoteASTContext(scratch_ctx);
swift::remote::RemoteAddress instance_address(class_metadata_ptr);
auto metadata_address = remote_ast.getHeapMetadataForObject(instance_address);
if (!metadata_address) {
if (log) {
log->Printf("could not read heap metadata for object at %lu: %s\n",
class_metadata_ptr,
metadata_address.getFailure().render().c_str());
}
return false;
}
auto instance_type =
remote_ast.getTypeForRemoteTypeMetadata(metadata_address.getValue(),
/*skipArtificial=*/true);
if (!instance_type) {
if (log) {
log->Printf("could not get type metadata from address %" PRIu64 " : %s\n",
metadata_address.getValue().getAddressData(),
instance_type.getFailure().render().c_str());
}
return false;
}
// The read lock must have been acquired by the caller.
class_type_or_name.SetCompilerType(
{&scratch_ctx, instance_type.getValue().getPointer()});
return true;
}
bool SwiftLanguageRuntime::IsValidErrorValue(ValueObject &in_value) {
CompilerType var_type = in_value.GetStaticValue()->GetCompilerType();
SwiftASTContext::ProtocolInfo protocol_info;
if (!SwiftASTContext::GetProtocolTypeInfo(var_type, protocol_info))
return false;
if (!protocol_info.m_is_errortype)
return false;
unsigned index = SwiftASTContext::ProtocolInfo::error_instance_index;
ValueObjectSP instance_type_sp(
in_value.GetStaticValue()->GetChildAtIndex(index, true));
if (!instance_type_sp)
return false;
lldb::addr_t metadata_location = instance_type_sp->GetValueAsUnsigned(0);
if (metadata_location == 0 || metadata_location == LLDB_INVALID_ADDRESS)
return false;
SetupSwiftError();
if (m_SwiftNativeNSErrorISA.hasValue()) {
if (auto objc_runtime = GetObjCRuntime()) {
if (auto descriptor =
objc_runtime->GetClassDescriptor(*instance_type_sp)) {
if (descriptor->GetISA() != m_SwiftNativeNSErrorISA.getValue()) {
// not a __SwiftNativeNSError - but statically typed as ErrorType
// return true here
return true;
}
}
}
}
if (GetObjCRuntime()) {
// this is a swift native error but it can be bridged to ObjC
// so it needs to be layout compatible
size_t ptr_size = m_process->GetAddressByteSize();
size_t metadata_offset =
ptr_size + 4 + (ptr_size == 8 ? 4 : 0); // CFRuntimeBase
metadata_offset += ptr_size + ptr_size + ptr_size; // CFIndex + 2*CFRef
metadata_location += metadata_offset;
Status error;
lldb::addr_t metadata_ptr_value =
m_process->ReadPointerFromMemory(metadata_location, error);
if (metadata_ptr_value == 0 || metadata_ptr_value == LLDB_INVALID_ADDRESS ||
error.Fail())
return false;
} else {
// this is a swift native error and it has no way to be bridged to ObjC
// so it adopts a more compact layout
Status error;
size_t ptr_size = m_process->GetAddressByteSize();
size_t metadata_offset = 2 * ptr_size;
metadata_location += metadata_offset;
lldb::addr_t metadata_ptr_value =
m_process->ReadPointerFromMemory(metadata_location, error);
if (metadata_ptr_value == 0 || metadata_ptr_value == LLDB_INVALID_ADDRESS ||
error.Fail())
return false;
}
return true;
}
bool SwiftLanguageRuntime::GetDynamicTypeAndAddress_Protocol(
ValueObject &in_value, CompilerType protocol_type,
SwiftASTContext &scratch_ctx,
lldb::DynamicValueType use_dynamic,
TypeAndOrName &class_type_or_name,
Address &address) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
auto &target = m_process->GetTarget();
assert(IsScratchContextLocked(target) &&
"Swift scratch context not locked ahead");
auto &remote_ast = GetRemoteASTContext(scratch_ctx);
lldb::addr_t existential_address;
bool use_local_buffer = false;
if (in_value.GetValueType() == eValueTypeConstResult &&
in_value.GetValue().GetValueType() ==
lldb_private::Value::eValueTypeHostAddress) {
if (log)
log->Printf("existential value is a const result");
// We have a locally materialized value that is a host address;
// register it with MemoryReader so it does not treat it as a load
// address. Note that this assumes that any address at that host
// address is also a load address. If this assumption breaks there
// will be a crash in readBytes().
existential_address = in_value.GetValue().GetScalar().ULongLong();
use_local_buffer = true;
} else {
existential_address = in_value.GetAddressOf();
}
if (log)
log->Printf("existential address is %llu", existential_address);
if (!existential_address || existential_address == LLDB_INVALID_ADDRESS)
return false;
if (use_local_buffer)
PushLocalBuffer(existential_address, in_value.GetByteSize());
swift::remote::RemoteAddress remote_existential(existential_address);
auto result = remote_ast.getDynamicTypeAndAddressForExistential(
remote_existential, GetSwiftType(protocol_type));
if (use_local_buffer)
PopLocalBuffer();
if (!result.isSuccess()) {
if (log)
log->Printf("RemoteAST failed to get dynamic type of existential");
return false;
}
auto type_and_address = result.getValue();
class_type_or_name.SetCompilerType(type_and_address.InstanceType);
address.SetRawAddress(type_and_address.PayloadAddress.getAddressData());
return true;
}
SwiftLanguageRuntime::MetadataPromiseSP
SwiftLanguageRuntime::GetPromiseForTypeNameAndFrame(const char *type_name,
StackFrame *frame) {
if (!frame || !type_name || !type_name[0])
return nullptr;
StreamString type_metadata_ptr_var_name;
type_metadata_ptr_var_name.Printf("$%s", type_name);
VariableList *var_list = frame->GetVariableList(false);
if (!var_list)
return nullptr;
VariableSP var_sp(var_list->FindVariable(
ConstString(type_metadata_ptr_var_name.GetData())));
if (!var_sp)
return nullptr;
ValueObjectSP metadata_ptr_var_sp(
frame->GetValueObjectForFrameVariable(var_sp, lldb::eNoDynamicValues));
if (!metadata_ptr_var_sp ||
metadata_ptr_var_sp->UpdateValueIfNeeded() == false)
return nullptr;
lldb::addr_t metadata_location(metadata_ptr_var_sp->GetValueAsUnsigned(0));
if (metadata_location == 0 || metadata_location == LLDB_INVALID_ADDRESS)
return nullptr;
return GetMetadataPromise(metadata_location, *metadata_ptr_var_sp);
}
CompilerType
SwiftLanguageRuntime::DoArchetypeBindingForType(StackFrame &stack_frame,
CompilerType base_type) {
auto sc = stack_frame.GetSymbolContext(lldb::eSymbolContextEverything);
Status error;
// A failing Clang import in a module context permanently damages
// that module context. Binding archetypes can trigger an import of
// another module, so switch to a scratch context where such an
// operation is safe.
auto &target = m_process->GetTarget();
assert(IsScratchContextLocked(target) &&
"Swift scratch context not locked ahead of archetype binding");
auto scratch_ctx = target.GetScratchSwiftASTContext(error, stack_frame);
if (!scratch_ctx)
return base_type;
base_type = scratch_ctx->ImportType(base_type, error);
if (base_type.GetTypeInfo() & lldb::eTypeIsSwift) {
swift::Type target_swift_type(GetSwiftType(base_type));
if (target_swift_type->hasArchetype())
target_swift_type = target_swift_type->mapTypeOutOfContext().getPointer();
// FIXME: This is wrong, but it doesn't actually matter right now since
// all conformances are always visible
auto *module_decl = scratch_ctx->GetASTContext()->getStdlibModule();
// Replace opaque types with their underlying types when possible.
swift::Mangle::ASTMangler mangler(true);
while (target_swift_type->hasOpaqueArchetype()) {
auto old_type = target_swift_type;
target_swift_type = target_swift_type.subst(
[&](swift::SubstitutableType *type) -> swift::Type {
auto opaque_type =
llvm::dyn_cast<swift::OpaqueTypeArchetypeType>(type);
if (!opaque_type)
return type;
// Try to find the symbol for the opaque type descriptor in the
// process.
auto mangled_name = ConstString(
mangler.mangleOpaqueTypeDescriptor(opaque_type->getDecl()));
SymbolContextList found;
target.GetImages().FindSymbolsWithNameAndType(mangled_name,
eSymbolTypeData, found);
if (found.GetSize() == 0)
return type;
swift::Type result_type;
for (unsigned i = 0, e = found.GetSize(); i < e; ++i) {
SymbolContext found_sc;
if (!found.GetContextAtIndex(i, found_sc))
continue;
// See if the symbol has an address.
if (!found_sc.symbol)
continue;
auto addr = found_sc.symbol->GetAddress()
.GetLoadAddress(&target);
if (!addr || addr == LLDB_INVALID_ADDRESS)
continue;
// Ask RemoteAST to get the underlying type out of the descriptor.
auto &remote_ast = GetRemoteASTContext(*scratch_ctx);
auto underlying_type_result =
remote_ast.getUnderlyingTypeForOpaqueType(
swift::remote::RemoteAddress(addr),
opaque_type->getSubstitutions(),
opaque_type->getOrdinal());
if (!underlying_type_result)
continue;
// If we haven't yet gotten an underlying type, use this as our
// possible result.
if (!result_type) {
result_type = underlying_type_result.getValue();
}
// If we have two possibilities, they should match.
else if (!result_type->isEqual(underlying_type_result.getValue())) {
return type;
}
}
if (!result_type)
return type;
return result_type;
},
swift::LookUpConformanceInModule(module_decl),
swift::SubstFlags::DesugarMemberTypes
| swift::SubstFlags::SubstituteOpaqueArchetypes);
// Stop if we've reached a fixpoint where we can't further resolve opaque
// types.
if (old_type->isEqual(target_swift_type))
break;
}
target_swift_type = target_swift_type.subst(
[this, &stack_frame,
&scratch_ctx](swift::SubstitutableType *type) -> swift::Type {
StreamString type_name;
if (!GetAbstractTypeName(type_name, type))
return type;
CompilerType concrete_type = this->GetConcreteType(
&stack_frame, ConstString(type_name.GetString()));
Status import_error;
CompilerType target_concrete_type =
scratch_ctx->ImportType(concrete_type, import_error);
if (target_concrete_type.IsValid())
return swift::Type(GetSwiftType(target_concrete_type));
return type;
},
swift::LookUpConformanceInModule(module_decl),
swift::SubstFlags::DesugarMemberTypes);
assert(target_swift_type);
return {target_swift_type.getPointer()};
}
return base_type;
}
bool SwiftLanguageRuntime::GetAbstractTypeName(StreamString &name,
swift::Type swift_type) {
auto *generic_type_param = swift_type->getAs<swift::GenericTypeParamType>();
if (!generic_type_param)
return false;
name.Printf(u8"\u03C4_%d_%d", generic_type_param->getDepth(),
generic_type_param->getIndex());
return true;
}
bool SwiftLanguageRuntime::GetDynamicTypeAndAddress_Value(
ValueObject &in_value, CompilerType &bound_type,
lldb::DynamicValueType use_dynamic, TypeAndOrName &class_type_or_name,
Address &address) {
class_type_or_name.SetCompilerType(bound_type);
llvm::Optional<uint64_t> size = bound_type.GetByteSize(
in_value.GetExecutionContextRef().GetFrameSP().get());
if (!size)
return false;
lldb::addr_t val_address = in_value.GetAddressOf(true, nullptr);
if (*size && (!val_address || val_address == LLDB_INVALID_ADDRESS))
return false;
address.SetLoadAddress(val_address, in_value.GetTargetSP().get());
return true;
}
bool SwiftLanguageRuntime::GetDynamicTypeAndAddress_IndirectEnumCase(
ValueObject &in_value, lldb::DynamicValueType use_dynamic,
TypeAndOrName &class_type_or_name, Address &address) {
static ConstString g_offset("offset");
DataExtractor data;
Status error;
if (!(in_value.GetParent() && in_value.GetParent()->GetData(data, error) &&
error.Success()))
return false;
bool has_payload;
bool is_indirect;
CompilerType payload_type;
if (!SwiftASTContext::GetSelectedEnumCase(
in_value.GetParent()->GetCompilerType(), data, nullptr, &has_payload,
&payload_type, &is_indirect))
return false;
if (has_payload && is_indirect && payload_type)
class_type_or_name.SetCompilerType(payload_type);
lldb::addr_t box_addr = in_value.GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
if (box_addr == LLDB_INVALID_ADDRESS)
return false;
box_addr = MaskMaybeBridgedPointer(box_addr);
lldb::addr_t box_location = m_process->ReadPointerFromMemory(box_addr, error);
if (box_location == LLDB_INVALID_ADDRESS)
return false;
box_location = MaskMaybeBridgedPointer(box_location);
ProcessStructReader reader(m_process, box_location, GetBoxMetadataType());
uint32_t offset = reader.GetField<uint32_t>(g_offset);
lldb::addr_t box_value = box_addr + offset;
// try to read one byte at the box value
m_process->ReadUnsignedIntegerFromMemory(box_value, 1, 0, error);
if (error.Fail()) // and if that fails, then we're off in no man's land
return false;
Flags type_info(payload_type.GetTypeInfo());
if (type_info.AllSet(eTypeIsSwift | eTypeIsClass)) {
lldb::addr_t old_box_value = box_value;
box_value = m_process->ReadPointerFromMemory(box_value, error);
if (box_value == LLDB_INVALID_ADDRESS)
return false;
DataExtractor data(&box_value, m_process->GetAddressByteSize(),
m_process->GetByteOrder(),
m_process->GetAddressByteSize());
ValueObjectSP valobj_sp(ValueObject::CreateValueObjectFromData(
"_", data, *m_process, payload_type));
if (!valobj_sp)
return false;
Value::ValueType value_type;
if (!GetDynamicTypeAndAddress(*valobj_sp, use_dynamic, class_type_or_name,
address, value_type))
return false;
address.SetRawAddress(old_box_value);
return true;
} else if (type_info.AllSet(eTypeIsSwift | eTypeIsProtocol)) {
SwiftASTContext::ProtocolInfo protocol_info;
if (!SwiftASTContext::GetProtocolTypeInfo(payload_type, protocol_info))
return false;
auto ptr_size = m_process->GetAddressByteSize();
std::vector<uint8_t> buffer(ptr_size * protocol_info.m_num_storage_words,
0);
for (uint32_t idx = 0; idx < protocol_info.m_num_storage_words; idx++) {
lldb::addr_t word = m_process->ReadUnsignedIntegerFromMemory(
box_value + idx * ptr_size, ptr_size, 0, error);
if (error.Fail())
return false;
memcpy(&buffer[idx * ptr_size], &word, ptr_size);
}
DataExtractor data(&buffer[0], buffer.size(), m_process->GetByteOrder(),
m_process->GetAddressByteSize());
ValueObjectSP valobj_sp(ValueObject::CreateValueObjectFromData(
"_", data, *m_process, payload_type));
if (!valobj_sp)
return false;
Value::ValueType value_type;
if (!GetDynamicTypeAndAddress(*valobj_sp, use_dynamic, class_type_or_name,
address, value_type))
return false;
address.SetRawAddress(box_value);
return true;
} else {
// This is most likely a statically known type.
address.SetLoadAddress(box_value, &m_process->GetTarget());
return true;
}
}
// Dynamic type resolution tends to want to generate scalar data - but there are
// caveats
// Per original comment here
// "Our address is the location of the dynamic type stored in memory. It isn't
// a load address,
// because we aren't pointing to the LOCATION that stores the pointer to us,
// we're pointing to us..."
// See inlined comments for exceptions to this general rule.
Value::ValueType SwiftLanguageRuntime::GetValueType(
Value::ValueType static_value_type, const CompilerType &static_type,
const CompilerType &dynamic_type, bool is_indirect_enum_case) {
Flags static_type_flags(static_type.GetTypeInfo());
Flags dynamic_type_flags(dynamic_type.GetTypeInfo());
if (dynamic_type_flags.AllSet(eTypeIsSwift)) {
// for a protocol object where does the dynamic data live if the target
// object is a struct? (for a class, it's easy)
if (static_type_flags.AllSet(eTypeIsSwift | eTypeIsProtocol) &&
dynamic_type_flags.AnySet(eTypeIsStructUnion | eTypeIsEnumeration)) {
SwiftASTContext *swift_ast_ctx =
llvm::dyn_cast_or_null<SwiftASTContext>(static_type.GetTypeSystem());
if (swift_ast_ctx && swift_ast_ctx->IsErrorType(static_type)) {
// ErrorType values are always a pointer
return Value::eValueTypeLoadAddress;
}
switch (SwiftASTContext::GetAllocationStrategy(dynamic_type)) {
case SwiftASTContext::TypeAllocationStrategy::eDynamic:
case SwiftASTContext::TypeAllocationStrategy::eUnknown:
break;
case SwiftASTContext::TypeAllocationStrategy::eInline: // inline data;
// same as the
// static data
return static_value_type;
case SwiftASTContext::TypeAllocationStrategy::ePointer: // pointed-to; in
// the target
return Value::eValueTypeLoadAddress;
}
}
if (static_type_flags.AllSet(eTypeIsSwift | eTypeIsGenericTypeParam)) {
// if I am handling a non-pointer Swift type obtained from an archetype,
// then the runtime vends the location
// of the object, not the object per se (since the object is not a pointer
// itself, this is way easier to achieve)
// hence, it's a load address, not a scalar containing a pointer as for
// ObjC classes
if (dynamic_type_flags.AllClear(eTypeIsPointer | eTypeIsReference |
eTypeInstanceIsPointer))
return Value::eValueTypeLoadAddress;
}
if (static_type_flags.AllSet(eTypeIsSwift | eTypeIsPointer) &&
static_type_flags.AllClear(eTypeIsGenericTypeParam)) {
// FIXME: This branch is not covered by any testcases in the test suite.
if (is_indirect_enum_case || static_type_flags.AllClear(eTypeIsBuiltIn))
return Value::eValueTypeLoadAddress;
}
}
// Enabling this makes the inout_variables test hang.
// return Value::eValueTypeScalar;
if (static_type_flags.AllSet(eTypeIsSwift) &&
dynamic_type_flags.AllSet(eTypeIsSwift) &&
dynamic_type_flags.AllClear(eTypeIsPointer | eTypeInstanceIsPointer))
return static_value_type;
else
return Value::eValueTypeScalar;
}
static bool IsIndirectEnumCase(ValueObject &valobj) {
return (valobj.GetLanguageFlags() &
SwiftASTContext::LanguageFlags::eIsIndirectEnumCase) ==
SwiftASTContext::LanguageFlags::eIsIndirectEnumCase;
}
bool SwiftLanguageRuntime::GetDynamicTypeAndAddress(
ValueObject &in_value, lldb::DynamicValueType use_dynamic,
TypeAndOrName &class_type_or_name, Address &address,
Value::ValueType &value_type) {
class_type_or_name.Clear();
if (use_dynamic == lldb::eNoDynamicValues || !CouldHaveDynamicValue(in_value))
return false;
// Dynamic type resolution in RemoteAST might pull in other Swift modules, so
// use the scratch context where such operations are legal and safe.
assert(IsScratchContextLocked(in_value.GetTargetSP()) &&
"Swift scratch context not locked ahead of dynamic type resolution");
auto scratch_ctx = in_value.GetScratchSwiftASTContext();
if (!scratch_ctx)
return false;
auto retry_once = [&]() {
// Retry exactly once using the per-module fallback scratch context.
auto &target = m_process->GetTarget();
if (!target.UseScratchTypesystemPerModule()) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("Dynamic type resolution detected fatal errors in "
"shared Swift state. Falling back to per-module "
"scratch context.\n");
target.SetUseScratchTypesystemPerModule(true);
return GetDynamicTypeAndAddress(in_value, use_dynamic, class_type_or_name,
address, value_type);
}
return false;
};
if (scratch_ctx->HasFatalErrors())
return retry_once();
// Import the type into the scratch context. Any form of dynamic
// type resolution may trigger a cross-module import.
CompilerType val_type(in_value.GetCompilerType());
Flags type_info(val_type.GetTypeInfo());
if (!type_info.AnySet(eTypeIsSwift))
return false;
bool success = false;
bool is_indirect_enum_case = IsIndirectEnumCase(in_value);
// Type kinds with metadata don't need archetype binding.
if (is_indirect_enum_case)
// ..._IndirectEnumCase() recurses, no need to bind archetypes.
success = GetDynamicTypeAndAddress_IndirectEnumCase(
in_value, use_dynamic, class_type_or_name, address);
else if (type_info.AnySet(eTypeIsClass) ||
type_info.AllSet(eTypeIsBuiltIn | eTypeIsPointer | eTypeHasValue))
success = GetDynamicTypeAndAddress_Class(
in_value, *scratch_ctx, use_dynamic, class_type_or_name, address);
else if (type_info.AnySet(eTypeIsProtocol))
success = GetDynamicTypeAndAddress_Protocol(
in_value, val_type, *scratch_ctx, use_dynamic,
class_type_or_name, address);
else {
// Perform archetype binding in the scratch context.
auto *frame = in_value.GetExecutionContextRef().GetFrameSP().get();
if (!frame)
return false;
CompilerType bound_type = DoArchetypeBindingForType(*frame, val_type);
if (!bound_type)
return false;
Flags subst_type_info(bound_type.GetTypeInfo());
if (subst_type_info.AnySet(eTypeIsClass)) {
success = GetDynamicTypeAndAddress_Class(in_value, *scratch_ctx, use_dynamic,
class_type_or_name, address);
} else if (subst_type_info.AnySet(eTypeIsProtocol)) {
success = GetDynamicTypeAndAddress_Protocol(in_value, bound_type,
*scratch_ctx, use_dynamic,
class_type_or_name, address);
} else {
success = GetDynamicTypeAndAddress_Value(in_value, bound_type,
use_dynamic, class_type_or_name,
address);
}
}
if (success)
value_type = GetValueType(
in_value.GetValue().GetValueType(), in_value.GetCompilerType(),
class_type_or_name.GetCompilerType(), is_indirect_enum_case);
else if (scratch_ctx->HasFatalErrors())
return retry_once();
return success;
}
TypeAndOrName
SwiftLanguageRuntime::FixUpDynamicType(const TypeAndOrName &type_and_or_name,
ValueObject &static_value) {
TypeAndOrName ret(type_and_or_name);
bool should_be_made_into_ref = false;
bool should_be_made_into_ptr = false;
Flags type_flags(static_value.GetCompilerType().GetTypeInfo());
Flags type_andor_name_flags(type_and_or_name.GetCompilerType().GetTypeInfo());
// if the static type is a pointer or reference, so should the dynamic type
// caveat: if the static type is a Swift class instance, the dynamic type
// could either be a Swift type (no need to change anything), or an ObjC type
// in which case it needs to be made into a pointer
if (type_flags.AnySet(eTypeIsPointer))
should_be_made_into_ptr =
(type_flags.AllClear(eTypeIsGenericTypeParam | eTypeIsBuiltIn) &&
!IsIndirectEnumCase(static_value));
else if (type_flags.AnySet(eTypeInstanceIsPointer))
should_be_made_into_ptr = !type_andor_name_flags.AllSet(eTypeIsSwift);
else if (type_flags.AnySet(eTypeIsReference))
should_be_made_into_ref = true;
else if (type_flags.AllSet(eTypeIsSwift | eTypeIsProtocol))
should_be_made_into_ptr =
type_and_or_name.GetCompilerType().IsRuntimeGeneratedType() &&
!type_and_or_name.GetCompilerType().IsPointerType();
if (type_and_or_name.HasType()) {
// The type will always be the type of the dynamic object. If our parent's
// type was a pointer,
// then our type should be a pointer to the type of the dynamic object. If
// a reference, then the original type
// should be okay...
CompilerType orig_type = type_and_or_name.GetCompilerType();
CompilerType corrected_type = orig_type;
if (should_be_made_into_ptr)
corrected_type = orig_type.GetPointerType();
else if (should_be_made_into_ref)
corrected_type = orig_type.GetLValueReferenceType();
ret.SetCompilerType(corrected_type);
}
return ret;
}
bool SwiftLanguageRuntime::IsTaggedPointer(lldb::addr_t addr,
CompilerType type) {
swift::CanType swift_can_type = GetCanonicalSwiftType(type);
switch (swift_can_type->getKind()) {
case swift::TypeKind::UnownedStorage: {
Target &target = m_process->GetTarget();
llvm::Triple triple = target.GetArchitecture().GetTriple();
// On Darwin the Swift runtime stores unowned references to
// Objective-C objects as a pointer to a struct that has the
// actual object pointer at offset zero. The least significant bit
// of the reference pointer indicates whether the reference refers
// to an Objective-C or Swift object.
//
// This is a property of the Swift runtime(!). In the future it
// may be necessary to check for the version of the Swift runtime
// (or indirectly by looking at the version of the remote
// operating system) to determine how to interpret references.
if (triple.isOSDarwin())
// Check whether this is a reference to an Objective-C object.
if ((addr & 1) == 1)
return true;
}
default:
break;
}
return false;
}
std::pair<lldb::addr_t, bool>
SwiftLanguageRuntime::FixupPointerValue(lldb::addr_t addr, CompilerType type) {
// Check for an unowned Darwin Objective-C reference.
if (IsTaggedPointer(addr, type)) {
// Clear the discriminator bit to get at the pointer to Objective-C object.
bool needs_deref = true;
return {addr & ~1ULL, needs_deref};
}
// Adjust the pointer to strip away the spare bits.
Target &target = m_process->GetTarget();
llvm::Triple triple = target.GetArchitecture().GetTriple();
switch (triple.getArch()) {
case llvm::Triple::ArchType::aarch64:
return {addr & ~SWIFT_ABI_ARM64_SWIFT_SPARE_BITS_MASK, false};
case llvm::Triple::ArchType::arm:
return {addr & ~SWIFT_ABI_ARM_SWIFT_SPARE_BITS_MASK, false};
case llvm::Triple::ArchType::x86:
return {addr & ~SWIFT_ABI_I386_SWIFT_SPARE_BITS_MASK, false};
case llvm::Triple::ArchType::x86_64:
return {addr & ~SWIFT_ABI_X86_64_SWIFT_SPARE_BITS_MASK, false};
case llvm::Triple::ArchType::systemz:
return {addr & ~SWIFT_ABI_S390X_SWIFT_SPARE_BITS_MASK, false};
case llvm::Triple::ArchType::ppc64le:
return { addr & ~SWIFT_ABI_POWERPC64_SWIFT_SPARE_BITS_MASK, false};
default:
break;
}
return {addr, false};
}
/// This allows a language runtime to adjust references depending on the type.
lldb::addr_t SwiftLanguageRuntime::FixupAddress(lldb::addr_t addr,
CompilerType type,
Status &error) {
swift::CanType swift_can_type = GetCanonicalSwiftType(type);
switch (swift_can_type->getKind()) {
case swift::TypeKind::UnownedStorage: {
// Peek into the reference to see whether it needs an extra deref.
// If yes, return the fixed-up address we just read.
Target &target = m_process->GetTarget();
size_t ptr_size = m_process->GetAddressByteSize();
lldb::addr_t refd_addr = LLDB_INVALID_ADDRESS;
target.ReadMemory(addr, false, &refd_addr, ptr_size, error);
if (error.Success()) {
bool extra_deref;
std::tie(refd_addr, extra_deref) = FixupPointerValue(refd_addr, type);
if (extra_deref)
return refd_addr;
}
}
default:
break;
}
return addr;
}
const swift::reflection::TypeInfo *
SwiftLanguageRuntime::GetTypeInfo(CompilerType type) {
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
CompilerType can_type(swift_can_type);
ConstString mangled_name(can_type.GetMangledTypeName());
StringRef mangled_no_prefix =
swift::Demangle::dropSwiftManglingPrefix(mangled_name.GetStringRef());
swift::Demangle::Demangler Dem;
auto demangled = Dem.demangleType(mangled_no_prefix);
auto *type_ref = swift::Demangle::decodeMangledType(
reflection_ctx->getBuilder(), demangled);
if (!type_ref)
return nullptr;
return reflection_ctx->getBuilder().getTypeConverter().getTypeInfo(type_ref);
}
bool SwiftLanguageRuntime::IsStoredInlineInBuffer(CompilerType type) {
if (auto *type_info = GetTypeInfo(type))
return type_info->isBitwiseTakable() && type_info->getSize() <= 24;
return true;
}
llvm::Optional<uint64_t> SwiftLanguageRuntime::GetBitSize(CompilerType type) {
if (auto *type_info = GetTypeInfo(type))
return type_info->getSize() * 8;
return {};
}
llvm::Optional<uint64_t> SwiftLanguageRuntime::GetByteStride(CompilerType type) {
if (auto *type_info = GetTypeInfo(type))
return type_info->getStride();
return {};
}
bool SwiftLanguageRuntime::IsWhitelistedRuntimeValue(ConstString name) {
return name == g_self;
}
bool SwiftLanguageRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
// if (in_value.IsDynamic())
// return false;
if (IsIndirectEnumCase(in_value))
return true;
CompilerType var_type(in_value.GetCompilerType());
Flags var_type_flags(var_type.GetTypeInfo());
if (var_type_flags.AllSet(eTypeIsSwift | eTypeInstanceIsPointer)) {
// Swift class instances are actually pointers, but base class instances
// are inlined at offset 0 in the class data. If we just let base classes
// be dynamic, it would cause an infinite recursion. So we would usually
// disable it
// But if the base class is a generic type we still need to bind it, and
// that is
// a good job for dynamic types to perform
if (in_value.IsBaseClass()) {
CompilerType base_type(in_value.GetCompilerType());
if (SwiftASTContext::IsFullyRealized(base_type))
return false;
}
return true;
}
return var_type.IsPossibleDynamicType(nullptr, false, false, true);
}
CompilerType
SwiftLanguageRuntime::GetConcreteType(ExecutionContextScope *exe_scope,
ConstString abstract_type_name) {
if (!exe_scope)
return CompilerType();
StackFrame *frame(exe_scope->CalculateStackFrame().get());
if (!frame)
return CompilerType();
MetadataPromiseSP promise_sp(
GetPromiseForTypeNameAndFrame(abstract_type_name.GetCString(), frame));
if (!promise_sp)
return CompilerType();
return promise_sp->FulfillTypePromise();
}
namespace {
enum class ThunkKind
{
Unknown = 0,
AllocatingInit,
PartialApply,
ObjCAttribute,
Reabstraction,
ProtocolConformance,
};
enum class ThunkAction
{
Unknown = 0,
GetThunkTarget,
StepIntoConformance,
StepThrough
};
}
static ThunkKind
GetThunkKind(llvm::StringRef symbol_name)
{
swift::Demangle::Node::Kind kind;
swift::Demangle::Context demangle_ctx;
if (!demangle_ctx.isThunkSymbol(symbol_name))
return ThunkKind::Unknown;
swift::Demangle::NodePointer nodes = demangle_ctx.demangleSymbolAsNode(symbol_name);
size_t num_global_children = nodes->getNumChildren();
if (num_global_children == 0)
return ThunkKind::Unknown;
if (nodes->getKind() != swift::Demangle::Node::Kind::Global)
return ThunkKind::Unknown;
if (nodes->getNumChildren() == 0)
return ThunkKind::Unknown;
swift::Demangle::NodePointer node_ptr = nodes->getFirstChild();
kind = node_ptr->getKind();
switch (kind)
{
case swift::Demangle::Node::Kind::ObjCAttribute:
return ThunkKind::ObjCAttribute;
break;
case swift::Demangle::Node::Kind::ProtocolWitness:
if (node_ptr->getNumChildren() == 0)
return ThunkKind::Unknown;
if (node_ptr->getFirstChild()->getKind()
== swift::Demangle::Node::Kind::ProtocolConformance)
return ThunkKind::ProtocolConformance;
break;
case swift::Demangle::Node::Kind::ReabstractionThunkHelper:
return ThunkKind::Reabstraction;
case swift::Demangle::Node::Kind::PartialApplyForwarder:
return ThunkKind::PartialApply;
case swift::Demangle::Node::Kind::Allocator:
if (node_ptr->getNumChildren() == 0)
return ThunkKind::Unknown;
if (node_ptr->getFirstChild()->getKind()
== swift::Demangle::Node::Kind::Class)
return ThunkKind::AllocatingInit;
break;
default:
break;
}
return ThunkKind::Unknown;
}
static const char *GetThunkKindName (ThunkKind kind)
{
switch (kind)
{
case ThunkKind::Unknown:
return "Unknown";
case ThunkKind::AllocatingInit:
return "StepThrough";
case ThunkKind::PartialApply:
return "GetThunkTarget";
case ThunkKind::ObjCAttribute:
return "GetThunkTarget";
case ThunkKind::Reabstraction:
return "GetThunkTarget";
case ThunkKind::ProtocolConformance:
return "StepIntoConformance";
}
}
static ThunkAction
GetThunkAction (ThunkKind kind)
{
switch (kind)
{
case ThunkKind::Unknown:
return ThunkAction::Unknown;
case ThunkKind::AllocatingInit:
return ThunkAction::StepThrough;
case ThunkKind::PartialApply:
return ThunkAction::GetThunkTarget;
case ThunkKind::ObjCAttribute:
return ThunkAction::GetThunkTarget;
case ThunkKind::Reabstraction:
return ThunkAction::StepThrough;
case ThunkKind::ProtocolConformance:
return ThunkAction::StepIntoConformance;
}
}
bool SwiftLanguageRuntime::GetTargetOfPartialApply(SymbolContext &curr_sc,
ConstString &apply_name,
SymbolContext &sc) {
if (!curr_sc.module_sp)
return false;
SymbolContextList sc_list;
swift::Demangle::Context demangle_ctx;
// Make sure this is a partial apply:
std::string apply_target = demangle_ctx.getThunkTarget(apply_name.GetStringRef());
if (!apply_target.empty()) {
size_t num_symbols = curr_sc.module_sp->FindFunctions(
ConstString(apply_target), NULL, eFunctionNameTypeFull, true, false, false, sc_list);
if (num_symbols == 0)
return false;
CompileUnit *curr_cu = curr_sc.comp_unit;
size_t num_found = 0;
for (size_t i = 0; i < num_symbols; i++) {
SymbolContext tmp_sc;
if (sc_list.GetContextAtIndex(i, tmp_sc)) {
if (tmp_sc.comp_unit && curr_cu && tmp_sc.comp_unit == curr_cu) {
sc = tmp_sc;
num_found++;
} else if (curr_sc.module_sp == tmp_sc.module_sp) {
sc = tmp_sc;
num_found++;
}
}
}
if (num_found == 1)
return true;
else {
sc.Clear(false);
return false;
}
} else {
return false;
}
}
bool SwiftLanguageRuntime::IsSymbolARuntimeThunk(const Symbol &symbol) {
llvm::StringRef symbol_name = symbol.GetMangled().GetMangledName().GetStringRef();
if (symbol_name.empty())
return false;
swift::Demangle::Context demangle_ctx;
return demangle_ctx.isThunkSymbol(symbol_name);
}
lldb::ThreadPlanSP
SwiftLanguageRuntime::GetStepThroughTrampolinePlan(Thread &thread,
bool stop_others) {
// Here are the trampolines we have at present.
// 1) The thunks from protocol invocations to the call in the actual object
// implementing the protocol.
// 2) Thunks for going from Swift ObjC classes to their actual method
// invocations
// 3) Thunks that retain captured objects in closure invocations.
ThreadPlanSP new_thread_plan_sp;
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
StackFrameSP stack_sp = thread.GetStackFrameAtIndex(0);
if (!stack_sp)
return new_thread_plan_sp;
SymbolContext sc = stack_sp->GetSymbolContext(eSymbolContextEverything);
Symbol *symbol = sc.symbol;
// Note, I don't really need to consult IsSymbolARuntimeThunk here, but it
// is fast to do and
// keeps this list and the one in IsSymbolARuntimeThunk in sync.
if (!symbol || !IsSymbolARuntimeThunk(*symbol))
return new_thread_plan_sp;
// Only do this if you are at the beginning of the thunk function:
lldb::addr_t cur_addr = thread.GetRegisterContext()->GetPC();
lldb::addr_t symbol_addr = symbol->GetAddress().GetLoadAddress(
&thread.GetProcess()->GetTarget());
if (symbol_addr != cur_addr)
return new_thread_plan_sp;
Address target_address;
ConstString symbol_mangled_name = symbol->GetMangled().GetMangledName();
const char *symbol_name = symbol_mangled_name.AsCString();
ThunkKind thunk_kind = GetThunkKind(symbol_mangled_name.GetStringRef());
ThunkAction thunk_action = GetThunkAction(thunk_kind);
switch (thunk_action)
{
case ThunkAction::Unknown:
return new_thread_plan_sp;
case ThunkAction::GetThunkTarget:
{
swift::Demangle::Context demangle_ctx;
std::string thunk_target = demangle_ctx.getThunkTarget(symbol_name);
if (thunk_target.empty())
{
if (log)
log->Printf("Stepped to thunk \"%s\" (kind: %s) but could not "
"find the thunk target. ",
symbol_name,
GetThunkKindName(thunk_kind));
return new_thread_plan_sp;
}
if (log)
log->Printf("Stepped to thunk \"%s\" (kind: %s) stepping to target: \"%s\".",
symbol_name, GetThunkKindName(thunk_kind), thunk_target.c_str());
ModuleList modules = thread.GetProcess()->GetTarget().GetImages();
SymbolContextList sc_list;
modules.FindFunctionSymbols(ConstString(thunk_target),
eFunctionNameTypeFull, sc_list);
if (sc_list.GetSize() == 1) {
SymbolContext sc;
sc_list.GetContextAtIndex(0, sc);
if (sc.symbol)
target_address = sc.symbol->GetAddress();
}
}
break;
case ThunkAction::StepIntoConformance:
{
// The TTW symbols encode the protocol conformance requirements and it
// is possible to go to
// the AST and get it to replay the logic that it used to determine
// what to dispatch to.
// But that ties us too closely to the logic of the compiler, and
// these thunks are quite
// simple, they just do a little retaining, and then call the correct
// function.
// So for simplicity's sake, I'm just going to get the base name of
// the function
// this protocol thunk is preparing to call, then step into through
// the thunk, stopping if I end up
// in a frame with that function name.
swift::Demangle::Context demangle_ctx;
swift::Demangle::NodePointer demangled_nodes =
demangle_ctx.demangleSymbolAsNode(symbol_mangled_name.GetStringRef());
// Now find the ProtocolWitness node in the demangled result.
swift::Demangle::NodePointer witness_node = demangled_nodes;
bool found_witness_node = false;
while (witness_node) {
if (witness_node->getKind() ==
swift::Demangle::Node::Kind::ProtocolWitness) {
found_witness_node = true;
break;
}
witness_node = witness_node->getFirstChild();
}
if (!found_witness_node) {
if (log)
log->Printf("Stepped into witness thunk \"%s\" but could not "
"find the ProtocolWitness node in the demangled "
"nodes.",
symbol_name);
return new_thread_plan_sp;
}
size_t num_children = witness_node->getNumChildren();
if (num_children < 2) {
if (log)
log->Printf("Stepped into witness thunk \"%s\" but the "
"ProtocolWitness node doesn't have enough nodes.",
symbol_name);
return new_thread_plan_sp;
}
swift::Demangle::NodePointer function_node =
witness_node->getChild(1);
if (function_node == nullptr ||
function_node->getKind() !=
swift::Demangle::Node::Kind::Function) {
if (log)
log->Printf("Stepped into witness thunk \"%s\" but could not "
"find the function in the ProtocolWitness node.",
symbol_name);
return new_thread_plan_sp;
}
// Okay, now find the name of this function.
num_children = function_node->getNumChildren();
swift::Demangle::NodePointer name_node(nullptr);
for (size_t i = 0; i < num_children; i++) {
if (function_node->getChild(i)->getKind() ==
swift::Demangle::Node::Kind::Identifier) {
name_node = function_node->getChild(i);
break;
}
}
if (!name_node) {
if (log)
log->Printf("Stepped into witness thunk \"%s\" but could not "
"find the Function name in the function node.",
symbol_name);
return new_thread_plan_sp;
}
std::string function_name(name_node->getText());
if (function_name.empty()) {
if (log)
log->Printf("Stepped into witness thunk \"%s\" but the Function "
"name was empty.",
symbol_name);
return new_thread_plan_sp;
}
// We have to get the address range of the thunk symbol, and make a
// "step through range stepping in"
AddressRange sym_addr_range(sc.symbol->GetAddress(),
sc.symbol->GetByteSize());
new_thread_plan_sp.reset(new ThreadPlanStepInRange(
thread, sym_addr_range, sc, function_name.c_str(),
eOnlyDuringStepping, eLazyBoolNo, eLazyBoolNo));
return new_thread_plan_sp;
}
break;
case ThunkAction::StepThrough:
{
if (log)
log->Printf("Stepping through thunk: %s kind: %s",
symbol_name, GetThunkKindName(thunk_kind));
AddressRange sym_addr_range(sc.symbol->GetAddress(),
sc.symbol->GetByteSize());
new_thread_plan_sp.reset(new ThreadPlanStepInRange(
thread, sym_addr_range, sc, nullptr, eOnlyDuringStepping,
eLazyBoolNo, eLazyBoolNo));
return new_thread_plan_sp;
}
break;
}
if (target_address.IsValid()) {
new_thread_plan_sp.reset(
new ThreadPlanRunToAddress(thread, target_address, stop_others));
}
return new_thread_plan_sp;
}
void SwiftLanguageRuntime::FindFunctionPointersInCall(
StackFrame &frame, std::vector<Address> &addresses, bool debug_only,
bool resolve_thunks) {
// Extract the mangled name from the stack frame, and realize the function
// type in the Target's SwiftASTContext.
// Then walk the arguments looking for function pointers. If we find one in
// the FIRST argument, we can fetch
// the pointer value and return that.
// FIXME: when we can ask swift/llvm for the location of function arguments,
// then we can do this for all the
// function pointer arguments we find.
SymbolContext sc = frame.GetSymbolContext(eSymbolContextSymbol);
if (sc.symbol) {
Mangled mangled_name = sc.symbol->GetMangled();
if (mangled_name.GuessLanguage() == lldb::eLanguageTypeSwift) {
Status error;
Target &target = frame.GetThread()->GetProcess()->GetTarget();
ExecutionContext exe_ctx(frame);
auto swift_ast = target.GetScratchSwiftASTContext(error, frame);
if (swift_ast) {
CompilerType function_type = swift_ast->GetTypeFromMangledTypename(
mangled_name.GetMangledName(), error);
if (error.Success()) {
if (function_type.IsFunctionType()) {
// FIXME: For now we only check the first argument since we don't
// know how to find the values
// of arguments further in the argument list.
// int num_arguments = function_type.GetFunctionArgumentCount();
// for (int i = 0; i < num_arguments; i++)
for (int i = 0; i < 1; i++) {
CompilerType argument_type =
function_type.GetFunctionArgumentTypeAtIndex(i);
if (argument_type.IsFunctionPointerType()) {
// We found a function pointer argument. Try to track down its
// value. This is a hack
// for now, we really should ask swift/llvm how to find the
// argument(s) given the
// Swift decl for this function, and then look those up in the
// frame.
ABISP abi_sp(frame.GetThread()->GetProcess()->GetABI());
ValueList argument_values;
Value input_value;
CompilerType clang_void_ptr_type =
target.GetScratchClangASTContext()
->GetBasicType(eBasicTypeVoid)
.GetPointerType();
input_value.SetValueType(Value::eValueTypeScalar);
input_value.SetCompilerType(clang_void_ptr_type);
argument_values.PushValue(input_value);
bool success = abi_sp->GetArgumentValues(
*(frame.GetThread().get()), argument_values);
if (success) {
// Now get a pointer value from the zeroth argument.
Status error;
DataExtractor data;
ExecutionContext exe_ctx;
frame.CalculateExecutionContext(exe_ctx);
error = argument_values.GetValueAtIndex(0)->GetValueAsData(
&exe_ctx, data, 0, NULL);
lldb::offset_t offset = 0;
lldb::addr_t fn_ptr_addr = data.GetPointer(&offset);
Address fn_ptr_address;
fn_ptr_address.SetLoadAddress(fn_ptr_addr, &target);
// Now check to see if this has debug info:
bool add_it = true;
if (resolve_thunks) {
SymbolContext sc;
fn_ptr_address.CalculateSymbolContext(
&sc, eSymbolContextEverything);
if (sc.comp_unit && sc.symbol) {
ConstString symbol_name =
sc.symbol->GetMangled().GetMangledName();
if (symbol_name) {
SymbolContext target_context;
if (GetTargetOfPartialApply(sc, symbol_name,
target_context)) {
if (target_context.symbol)
fn_ptr_address =
target_context.symbol->GetAddress();
else if (target_context.function)
fn_ptr_address =
target_context.function->GetAddressRange()
.GetBaseAddress();
}
}
}
}
if (debug_only) {
LineEntry line_entry;
fn_ptr_address.CalculateSymbolContextLineEntry(line_entry);
if (!line_entry.IsValid())
add_it = false;
}
if (add_it)
addresses.push_back(fn_ptr_address);
}
}
}
}
}
}
}
}
}
//------------------------------------------------------------------
// Exception breakpoint Precondition class for Swift:
//------------------------------------------------------------------
void SwiftLanguageRuntime::SwiftExceptionPrecondition::AddTypeName(
const char *class_name) {
m_type_names.insert(class_name);
}
void SwiftLanguageRuntime::SwiftExceptionPrecondition::AddEnumSpec(
const char *enum_name, const char *element_name) {
std::unordered_map<std::string, std::vector<std::string>>::value_type
new_value(enum_name, std::vector<std::string>());
auto result = m_enum_spec.emplace(new_value);
result.first->second.push_back(element_name);
}
SwiftLanguageRuntime::SwiftExceptionPrecondition::SwiftExceptionPrecondition() {
}
ValueObjectSP
SwiftLanguageRuntime::CalculateErrorValueObjectFromValue(
Value &value, ConstString name, bool persistent)
{
ValueObjectSP error_valobj_sp;
auto type_system_or_err = m_process->GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeSwift);
if (!type_system_or_err)
return error_valobj_sp;
auto *ast_context = llvm::dyn_cast_or_null<SwiftASTContext>(&*type_system_or_err);
if (!ast_context)
return error_valobj_sp;
CompilerType swift_error_proto_type = ast_context->GetErrorType();
value.SetCompilerType(swift_error_proto_type);
error_valobj_sp = ValueObjectConstResult::Create(
m_process, value, name);
if (error_valobj_sp && error_valobj_sp->GetError().Success()) {
error_valobj_sp = error_valobj_sp->GetQualifiedRepresentationIfAvailable(
lldb::eDynamicCanRunTarget, true);
if (!IsValidErrorValue(*(error_valobj_sp.get()))) {
error_valobj_sp.reset();
}
}
if (persistent && error_valobj_sp) {
ExecutionContext ctx =
error_valobj_sp->GetExecutionContextRef().Lock(false);
auto *exe_scope = ctx.GetBestExecutionContextScope();
if (!exe_scope)
return error_valobj_sp;
Target &target = m_process->GetTarget();
auto *persistent_state =
target.GetSwiftPersistentExpressionState(*exe_scope);
const bool is_error = true;
auto prefix = persistent_state->GetPersistentVariablePrefix(is_error);
ConstString persistent_variable_name(
persistent_state->GetNextPersistentVariableName(target, prefix));
lldb::ValueObjectSP const_valobj_sp;
// Check in case our value is already a constant value
if (error_valobj_sp->GetIsConstant()) {
const_valobj_sp = error_valobj_sp;
const_valobj_sp->SetName(persistent_variable_name);
} else
const_valobj_sp =
error_valobj_sp->CreateConstantValue(persistent_variable_name);
lldb::ValueObjectSP live_valobj_sp = error_valobj_sp;
error_valobj_sp = const_valobj_sp;
ExpressionVariableSP clang_expr_variable_sp(
persistent_state->CreatePersistentVariable(error_valobj_sp));
clang_expr_variable_sp->m_live_sp = live_valobj_sp;
clang_expr_variable_sp->m_flags |=
ClangExpressionVariable::EVIsProgramReference;
error_valobj_sp = clang_expr_variable_sp->GetValueObject();
}
return error_valobj_sp;
}
ValueObjectSP
SwiftLanguageRuntime::CalculateErrorValue(StackFrameSP frame_sp,
ConstString variable_name) {
ProcessSP process_sp(frame_sp->GetThread()->GetProcess());
Status error;
Target *target = frame_sp->CalculateTarget().get();
ValueObjectSP error_valobj_sp;
auto *runtime = Get(*process_sp);
if (!runtime)
return error_valobj_sp;
llvm::Optional<Value> arg0 =
runtime->GetErrorReturnLocationAfterReturn(frame_sp);
if (!arg0)
return error_valobj_sp;
ExecutionContext exe_ctx;
frame_sp->CalculateExecutionContext(exe_ctx);
auto *exe_scope = exe_ctx.GetBestExecutionContextScope();
if (!exe_scope)
return error_valobj_sp;
auto ast_context = target->GetScratchSwiftASTContext(error, *frame_sp);
if (!ast_context || error.Fail())
return error_valobj_sp;
lldb::DataBufferSP buffer(new lldb_private::DataBufferHeap(
arg0->GetScalar().GetBytes(), arg0->GetScalar().GetByteSize()));
CompilerType swift_error_proto_type = ast_context->GetErrorType();
if (!swift_error_proto_type.IsValid())
return error_valobj_sp;
error_valobj_sp = ValueObjectConstResult::Create(
exe_scope, swift_error_proto_type,
variable_name, buffer, endian::InlHostByteOrder(),
exe_ctx.GetAddressByteSize());
if (error_valobj_sp->GetError().Fail())
return error_valobj_sp;
error_valobj_sp = error_valobj_sp->GetQualifiedRepresentationIfAvailable(
lldb::eDynamicCanRunTarget, true);
return error_valobj_sp;
}
void SwiftLanguageRuntime::RegisterGlobalError(Target &target, ConstString name,
lldb::addr_t addr) {
auto type_system_or_err = target.GetScratchTypeSystemForLanguage(eLanguageTypeSwift);
if (!type_system_or_err) {
llvm::consumeError(type_system_or_err.takeError());
return;
}
auto *ast_context = llvm::dyn_cast_or_null<SwiftASTContext>(&*type_system_or_err);
if (ast_context && !ast_context->HasFatalErrors()) {
SwiftPersistentExpressionState *persistent_state =
llvm::cast<SwiftPersistentExpressionState>(
target.GetPersistentExpressionStateForLanguage(
lldb::eLanguageTypeSwift));
std::string module_name = "$__lldb_module_for_";
module_name.append(&name.GetCString()[1]);
SourceModule module_info;
module_info.path.push_back(ConstString(module_name));
Status module_creation_error;
swift::ModuleDecl *module_decl =
ast_context->CreateModule(module_info, module_creation_error);
if (module_creation_error.Success() && module_decl) {
const bool is_static = false;
const auto introducer = swift::VarDecl::Introducer::Let;
const bool is_capture_list = false;
swift::VarDecl *var_decl = new (*ast_context->GetASTContext())
swift::VarDecl(is_static, introducer, is_capture_list, swift::SourceLoc(),
ast_context->GetIdentifier(name.GetCString()),
module_decl);
var_decl->setType(GetSwiftType(ast_context->GetErrorType()));
var_decl->setInterfaceType(var_decl->getType());
var_decl->setDebuggerVar(true);
persistent_state->RegisterSwiftPersistentDecl(var_decl);
ConstString mangled_name;
{
swift::Mangle::ASTMangler mangler(true);
mangled_name = ConstString(mangler.mangleGlobalVariableFull(var_decl));
}
lldb::addr_t symbol_addr;
{
ProcessSP process_sp(target.GetProcessSP());
Status alloc_error;
symbol_addr = process_sp->AllocateMemory(
process_sp->GetAddressByteSize(),
lldb::ePermissionsWritable | lldb::ePermissionsReadable,
alloc_error);
if (alloc_error.Success() && symbol_addr != LLDB_INVALID_ADDRESS) {
Status write_error;
process_sp->WritePointerToMemory(symbol_addr, addr, write_error);
if (write_error.Success()) {
persistent_state->RegisterSymbol(mangled_name, symbol_addr);
}
}
}
}
}
}
lldb::BreakpointPreconditionSP
SwiftLanguageRuntime::GetBreakpointExceptionPrecondition(LanguageType language,
bool throw_bp) {
if (language != eLanguageTypeSwift)
return lldb::BreakpointPreconditionSP();
if (!throw_bp)
return lldb::BreakpointPreconditionSP();
BreakpointPreconditionSP precondition_sp(
new SwiftLanguageRuntime::SwiftExceptionPrecondition());
return precondition_sp;
}
bool SwiftLanguageRuntime::SwiftExceptionPrecondition::EvaluatePrecondition(
StoppointCallbackContext &context) {
if (!m_type_names.empty()) {
StackFrameSP frame_sp = context.exe_ctx_ref.GetFrameSP();
if (!frame_sp)
return true;
ValueObjectSP error_valobj_sp =
CalculateErrorValue(frame_sp, ConstString("__swift_error_var"));
if (!error_valobj_sp || error_valobj_sp->GetError().Fail())
return true;
// This shouldn't fail, since at worst it will return me the object I just
// successfully got.
std::string full_error_name(
error_valobj_sp->GetCompilerType().GetTypeName().AsCString());
size_t last_dot_pos = full_error_name.rfind('.');
std::string type_name_base;
if (last_dot_pos == std::string::npos)
type_name_base = full_error_name;
else {
if (last_dot_pos + 1 <= full_error_name.size())
type_name_base =
full_error_name.substr(last_dot_pos + 1, full_error_name.size());
}
// The type name will be the module and then the type. If the match name
// has a dot, we require a complete
// match against the type, if the type name has no dot, we match it against
// the base.
for (std::string name : m_type_names) {
if (name.rfind('.') != std::string::npos) {
if (name == full_error_name)
return true;
} else {
if (name == type_name_base)
return true;
}
}
return false;
}
return true;
}
void SwiftLanguageRuntime::SwiftExceptionPrecondition::GetDescription(
Stream &stream, lldb::DescriptionLevel level) {
if (level == eDescriptionLevelFull || level == eDescriptionLevelVerbose) {
if (m_type_names.size() > 0) {
stream.Printf("\nType Filters:");
for (std::string name : m_type_names) {
stream.Printf(" %s", name.c_str());
}
stream.Printf("\n");
}
}
}
Status SwiftLanguageRuntime::SwiftExceptionPrecondition::ConfigurePrecondition(
Args &args) {
Status error;
std::vector<std::string> object_typenames;
args.GetOptionValuesAsStrings("exception-typename", object_typenames);
for (auto type_name : object_typenames)
AddTypeName(type_name.c_str());
return error;
}
void SwiftLanguageRuntime::AddToLibraryNegativeCache(StringRef library_name) {
std::lock_guard<std::mutex> locker(m_negative_cache_mutex);
m_library_negative_cache.insert(library_name);
}
bool SwiftLanguageRuntime::IsInLibraryNegativeCache(StringRef library_name) {
std::lock_guard<std::mutex> locker(m_negative_cache_mutex);
return m_library_negative_cache.count(library_name) == 1;
}
lldb::addr_t
SwiftLanguageRuntime::MaskMaybeBridgedPointer(lldb::addr_t addr,
lldb::addr_t *masked_bits) {
if (!m_process)
return addr;
const ArchSpec &arch_spec(m_process->GetTarget().GetArchitecture());
ArchSpec::Core core_kind = arch_spec.GetCore();
bool is_arm = false;
bool is_intel = false;
bool is_s390x = false;
bool is_32 = false;
bool is_64 = false;
if (core_kind == ArchSpec::Core::eCore_arm_arm64) {
is_arm = is_64 = true;
} else if (core_kind >= ArchSpec::Core::kCore_arm_first &&
core_kind <= ArchSpec::Core::kCore_arm_last) {
is_arm = true;
} else if (core_kind >= ArchSpec::Core::kCore_x86_64_first &&
core_kind <= ArchSpec::Core::kCore_x86_64_last) {
is_intel = true;
} else if (core_kind >= ArchSpec::Core::kCore_x86_32_first &&
core_kind <= ArchSpec::Core::kCore_x86_32_last) {
is_intel = true;
} else if (core_kind == ArchSpec::Core::eCore_s390x_generic) {
is_s390x = true;
} else {
// this is a really random CPU core to be running on - just get out fast
return addr;
}
switch (arch_spec.GetAddressByteSize()) {
case 4:
is_32 = true;
break;
case 8:
is_64 = true;
break;
default:
// this is a really random pointer size to be running on - just get out fast
return addr;
}
lldb::addr_t mask = 0;
if (is_arm && is_64)
mask = SWIFT_ABI_ARM64_SWIFT_SPARE_BITS_MASK;
if (is_arm && is_32)
mask = SWIFT_ABI_ARM_SWIFT_SPARE_BITS_MASK;
if (is_intel && is_64)
mask = SWIFT_ABI_X86_64_SWIFT_SPARE_BITS_MASK;
if (is_intel && is_32)
mask = SWIFT_ABI_I386_SWIFT_SPARE_BITS_MASK;
if (is_s390x && is_64)
mask = SWIFT_ABI_S390X_SWIFT_SPARE_BITS_MASK;
if (masked_bits)
*masked_bits = addr & mask;
return addr & ~mask;
}
lldb::addr_t
SwiftLanguageRuntime::MaybeMaskNonTrivialReferencePointer(
lldb::addr_t addr,
SwiftASTContext::NonTriviallyManagedReferenceStrategy strategy) {
if (addr == 0)
return addr;
AppleObjCRuntime *objc_runtime = GetObjCRuntime();
if (objc_runtime) {
// tagged pointers don't perform any masking
if (objc_runtime->IsTaggedPointer(addr))
return addr;
}
if (!m_process)
return addr;
const ArchSpec &arch_spec(m_process->GetTarget().GetArchitecture());
ArchSpec::Core core_kind = arch_spec.GetCore();
bool is_arm = false;
bool is_intel = false;
bool is_32 = false;
bool is_64 = false;
if (core_kind == ArchSpec::Core::eCore_arm_arm64) {
is_arm = is_64 = true;
} else if (core_kind >= ArchSpec::Core::kCore_arm_first &&
core_kind <= ArchSpec::Core::kCore_arm_last) {
is_arm = true;
} else if (core_kind >= ArchSpec::Core::kCore_x86_64_first &&
core_kind <= ArchSpec::Core::kCore_x86_64_last) {
is_intel = true;
} else if (core_kind >= ArchSpec::Core::kCore_x86_32_first &&
core_kind <= ArchSpec::Core::kCore_x86_32_last) {
is_intel = true;
} else {
// this is a really random CPU core to be running on - just get out fast
return addr;
}
switch (arch_spec.GetAddressByteSize()) {
case 4:
is_32 = true;
break;
case 8:
is_64 = true;
break;
default:
// this is a really random pointer size to be running on - just get out fast
return addr;
}
lldb::addr_t mask = 0;
if (strategy == SwiftASTContext::NonTriviallyManagedReferenceStrategy::eWeak) {
bool is_indirect = true;
// On non-objc platforms, the weak reference pointer always pointed to a
// runtime structure.
// For ObjC platforms, the masked value determines whether it is indirect.
uint32_t value = 0;
if (objc_runtime)
{
if (is_intel) {
if (is_64) {
mask = SWIFT_ABI_X86_64_OBJC_WEAK_REFERENCE_MARKER_MASK;
value = SWIFT_ABI_X86_64_OBJC_WEAK_REFERENCE_MARKER_VALUE;
} else {
mask = SWIFT_ABI_I386_OBJC_WEAK_REFERENCE_MARKER_MASK;
value = SWIFT_ABI_I386_OBJC_WEAK_REFERENCE_MARKER_VALUE;
}
} else if (is_arm) {
if (is_64) {
mask = SWIFT_ABI_ARM64_OBJC_WEAK_REFERENCE_MARKER_MASK;
value = SWIFT_ABI_ARM64_OBJC_WEAK_REFERENCE_MARKER_VALUE;
} else {
mask = SWIFT_ABI_ARM_OBJC_WEAK_REFERENCE_MARKER_MASK;
value = SWIFT_ABI_ARM_OBJC_WEAK_REFERENCE_MARKER_VALUE;
}
}
} else {
// This name is a little confusing. The "DEFAULT" marking in System.h
// is supposed to mean: the value for non-ObjC platforms. So
// DEFAULT_OBJC here actually means "non-ObjC".
mask = SWIFT_ABI_DEFAULT_OBJC_WEAK_REFERENCE_MARKER_MASK;
value = SWIFT_ABI_DEFAULT_OBJC_WEAK_REFERENCE_MARKER_VALUE;
}
is_indirect = ((addr & mask) == value);
if (!is_indirect)
return addr;
// The masked value of address is a pointer to the runtime structure.
// The first field of the structure is the actual pointer.
Process *process = GetProcess();
Status error;
lldb::addr_t masked_addr = addr & ~mask;
lldb::addr_t isa_addr = process->ReadPointerFromMemory(masked_addr, error);
if (error.Fail())
{
// FIXME: do some logging here.
return addr;
}
return isa_addr;
} else {
if (is_arm && is_64)
mask = SWIFT_ABI_ARM64_OBJC_NUM_RESERVED_LOW_BITS;
else if (is_intel && is_64)
mask = SWIFT_ABI_X86_64_OBJC_NUM_RESERVED_LOW_BITS;
else
mask = SWIFT_ABI_DEFAULT_OBJC_NUM_RESERVED_LOW_BITS;
mask = (1 << mask) | (1 << (mask + 1));
return addr & ~mask;
}
return addr;
}
ConstString SwiftLanguageRuntime::GetErrorBackstopName() {
return ConstString("swift_errorInMain");
}
ConstString SwiftLanguageRuntime::GetStandardLibraryBaseName() {
static ConstString g_swiftCore("swiftCore");
return g_swiftCore;
}
ConstString SwiftLanguageRuntime::GetStandardLibraryName() {
PlatformSP platform_sp(m_process->GetTarget().GetPlatform());
if (platform_sp)
return platform_sp->GetFullNameForDylib(GetStandardLibraryBaseName());
return GetStandardLibraryBaseName();
}
class ProjectionSyntheticChildren : public SyntheticChildren {
public:
struct FieldProjection {
ConstString name;
CompilerType type;
int32_t byte_offset;
FieldProjection(CompilerType parent_type, ExecutionContext *exe_ctx,
size_t idx) {
const bool transparent_pointers = false;
const bool omit_empty_base_classes = true;
const bool ignore_array_bounds = false;
bool child_is_base_class = false;
bool child_is_deref_of_parent = false;
std::string child_name;
uint32_t child_byte_size;
uint32_t child_bitfield_bit_size;
uint32_t child_bitfield_bit_offset;
uint64_t language_flags;
type = parent_type.GetChildCompilerTypeAtIndex(
exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
ignore_array_bounds, child_name, child_byte_size, byte_offset,
child_bitfield_bit_size, child_bitfield_bit_offset,
child_is_base_class, child_is_deref_of_parent, nullptr,
language_flags);
if (child_is_base_class)
type.Clear(); // invalidate - base classes are dealt with outside of the
// projection
else
name.SetCStringWithLength(child_name.c_str(), child_name.size());
}
bool IsValid() { return !name.IsEmpty() && type.IsValid(); }
explicit operator bool() { return IsValid(); }
};
struct TypeProjection {
std::vector<FieldProjection> field_projections;
ConstString type_name;
};
typedef std::unique_ptr<TypeProjection> TypeProjectionUP;
bool IsScripted() { return false; }
std::string GetDescription() { return "projection synthetic children"; }
ProjectionSyntheticChildren(const Flags &flags, TypeProjectionUP &&projection)
: SyntheticChildren(flags), m_projection(std::move(projection)) {}
protected:
TypeProjectionUP m_projection;
class ProjectionFrontEndProvider : public SyntheticChildrenFrontEnd {
public:
ProjectionFrontEndProvider(ValueObject &backend,
TypeProjectionUP &projection)
: SyntheticChildrenFrontEnd(backend), m_num_bases(0),
m_projection(projection.get()) {
lldbassert(m_projection && "need a valid projection");
CompilerType type(backend.GetCompilerType());
m_num_bases = type.GetNumDirectBaseClasses();
}
size_t CalculateNumChildren() override {
return m_projection->field_projections.size() + m_num_bases;
}
lldb::ValueObjectSP GetChildAtIndex(size_t idx) override {
if (idx < m_num_bases) {
if (ValueObjectSP base_object_sp =
m_backend.GetChildAtIndex(idx, true)) {
CompilerType base_type(base_object_sp->GetCompilerType());
ConstString base_type_name(base_type.GetTypeName());
if (base_type_name.IsEmpty() ||
!SwiftLanguageRuntime::IsSwiftClassName(
base_type_name.GetCString()))
return base_object_sp;
base_object_sp = m_backend.GetSyntheticBase(
0, base_type, true,
Mangled(base_type_name, true)
.GetDemangledName(lldb::eLanguageTypeSwift));
return base_object_sp;
} else
return nullptr;
}
idx -= m_num_bases;
if (idx < m_projection->field_projections.size()) {
auto &projection(m_projection->field_projections.at(idx));
return m_backend.GetSyntheticChildAtOffset(
projection.byte_offset, projection.type, true, projection.name);
}
return nullptr;
}
size_t GetIndexOfChildWithName(ConstString name) override {
for (size_t idx = 0; idx < m_projection->field_projections.size();
idx++) {
if (m_projection->field_projections.at(idx).name == name)
return idx;
}
return UINT32_MAX;
}
bool Update() override { return false; }
bool MightHaveChildren() override { return true; }
ConstString GetSyntheticTypeName() override {
return m_projection->type_name;
}
private:
size_t m_num_bases;
TypeProjectionUP::element_type *m_projection;
};
public:
SyntheticChildrenFrontEnd::AutoPointer GetFrontEnd(ValueObject &backend) {
return SyntheticChildrenFrontEnd::AutoPointer(
new ProjectionFrontEndProvider(backend, m_projection));
}
};
lldb::SyntheticChildrenSP
SwiftLanguageRuntime::GetBridgedSyntheticChildProvider(ValueObject &valobj) {
ConstString type_name = valobj.GetCompilerType().GetTypeName();
if (!type_name.IsEmpty()) {
auto iter = m_bridged_synthetics_map.find(type_name.AsCString()),
end = m_bridged_synthetics_map.end();
if (iter != end)
return iter->second;
}
ProjectionSyntheticChildren::TypeProjectionUP type_projection(
new ProjectionSyntheticChildren::TypeProjectionUP::element_type());
if (auto swift_ast_ctx = valobj.GetScratchSwiftASTContext()) {
Status error;
CompilerType swift_type =
swift_ast_ctx->GetTypeFromMangledTypename(type_name, error);
if (swift_type.IsValid()) {
ExecutionContext exe_ctx(GetProcess());
bool any_projected = false;
for (size_t idx = 0, e = swift_type.GetNumChildren(true, &exe_ctx);
idx < e; idx++) {
// if a projection fails, keep going - we have offsets here, so it
// should be OK to skip some members
if (auto projection = ProjectionSyntheticChildren::FieldProjection(
swift_type, &exe_ctx, idx)) {
any_projected = true;
type_projection->field_projections.push_back(projection);
}
}
if (any_projected) {
type_projection->type_name = swift_type.GetDisplayTypeName();
SyntheticChildrenSP synth_sp =
SyntheticChildrenSP(new ProjectionSyntheticChildren(
SyntheticChildren::Flags(), std::move(type_projection)));
m_bridged_synthetics_map.insert({type_name.AsCString(), synth_sp});
return synth_sp;
}
}
}
return nullptr;
}
void SwiftLanguageRuntime::WillStartExecutingUserExpression(
bool runs_in_playground_or_repl) {
std::lock_guard<std::mutex> lock(m_active_user_expr_mutex);
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (m_active_user_expr_count == 0 && m_dynamic_exclusivity_flag_addr &&
!runs_in_playground_or_repl) {
// We're executing the first user expression. Toggle the flag.
auto type_system_or_err = m_process->GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC_plus_plus);
if (!type_system_or_err) {
LLDB_LOG_ERROR(log, type_system_or_err.takeError(),
"SwiftLanguageRuntime: Unable to get pointer to type system");
return;
}
ConstString BoolName("bool");
llvm::Optional<uint64_t> bool_size =
type_system_or_err->GetBuiltinTypeByName(BoolName).GetByteSize(nullptr);
if (!bool_size)
return;
Status error;
Scalar original_value;
m_process->ReadScalarIntegerFromMemory(*m_dynamic_exclusivity_flag_addr,
*bool_size, false, original_value,
error);
m_original_dynamic_exclusivity_flag_state = original_value.UInt() != 0;
if (error.Fail()) {
if (log)
log->Printf("SwiftLanguageRuntime: Unable to read "
"disableExclusivityChecking flag state: %s",
error.AsCString());
} else {
Scalar new_value(1U);
m_process->WriteScalarToMemory(*m_dynamic_exclusivity_flag_addr,
new_value, *bool_size, error);
if (error.Fail()) {
if (log)
log->Printf("SwiftLanguageRuntime: Unable to set "
"disableExclusivityChecking flag state: %s",
error.AsCString());
} else {
if (log)
log->Printf("SwiftLanguageRuntime: Changed "
"disableExclusivityChecking flag state from %u to 1",
m_original_dynamic_exclusivity_flag_state);
}
}
}
++m_active_user_expr_count;
if (log)
log->Printf("SwiftLanguageRuntime: starting user expression. "
"Number active: %u", m_active_user_expr_count);
}
void SwiftLanguageRuntime::DidFinishExecutingUserExpression(
bool runs_in_playground_or_repl) {
std::lock_guard<std::mutex> lock(m_active_user_expr_mutex);
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
--m_active_user_expr_count;
if (log)
log->Printf("SwiftLanguageRuntime: finished user expression. "
"Number active: %u", m_active_user_expr_count);
if (m_active_user_expr_count == 0 && m_dynamic_exclusivity_flag_addr &&
!runs_in_playground_or_repl) {
auto type_system_or_err = m_process->GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC_plus_plus);
if (!type_system_or_err) {
LLDB_LOG_ERROR(log, type_system_or_err.takeError(),
"SwiftLanguageRuntime: Unable to get pointer to type system");
return;
}
ConstString BoolName("bool");
llvm::Optional<uint64_t> bool_size =
type_system_or_err->GetBuiltinTypeByName(BoolName).GetByteSize(nullptr);
if (!bool_size)
return;
Status error;
Scalar original_value(m_original_dynamic_exclusivity_flag_state ? 1U : 0U);
m_process->WriteScalarToMemory(*m_dynamic_exclusivity_flag_addr,
original_value, *bool_size, error);
if (error.Fail()) {
if (log)
log->Printf("SwiftLanguageRuntime: Unable to reset "
"disableExclusivityChecking flag state: %s",
error.AsCString());
} else {
if (log)
log->Printf("SwiftLanguageRuntime: Changed "
"disableExclusivityChecking flag state back to %u",
m_original_dynamic_exclusivity_flag_state);
}
}
}
llvm::Optional<Value> SwiftLanguageRuntime::GetErrorReturnLocationAfterReturn(
lldb::StackFrameSP frame_sp)
{
llvm::Optional<Value> error_val;
llvm::StringRef error_reg_name;
ArchSpec arch_spec(GetTargetRef().GetArchitecture());
switch (arch_spec.GetMachine()) {
case llvm::Triple::ArchType::arm:
error_reg_name = "r6";
break;
case llvm::Triple::ArchType::aarch64:
error_reg_name = "x21";
break;
case llvm::Triple::ArchType::x86_64:
error_reg_name = "r12";
break;
default:
break;
}
if (error_reg_name.empty())
return error_val;
RegisterContextSP reg_ctx = frame_sp->GetRegisterContext();
const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(error_reg_name);
lldbassert(reg_info && "didn't get the right register name for swift error register");
if (!reg_info)
return error_val;
RegisterValue reg_value;
if (!reg_ctx->ReadRegister(reg_info, reg_value))
{
// Do some logging here.
return error_val;
}
lldb::addr_t error_addr = reg_value.GetAsUInt64();
if (error_addr == 0)
return error_val;
Value val;
if (reg_value.GetScalarValue(val.GetScalar())) {
val.SetValueType(Value::eValueTypeScalar);
val.SetContext(Value::eContextTypeRegisterInfo,
const_cast<RegisterInfo *>(reg_info));
error_val = val;
}
return error_val;
}
llvm::Optional<Value> SwiftLanguageRuntime::GetErrorReturnLocationBeforeReturn(
lldb::StackFrameSP frame_sp, bool &need_to_check_after_return) {
llvm::Optional<Value> error_val;
if (!frame_sp)
{
need_to_check_after_return = false;
return error_val;
}
// For Architectures where the error isn't returned in a register,
// there's a magic variable that points to the value. Check that first:
ConstString error_location_name("$error");
VariableListSP variables_sp = frame_sp->GetInScopeVariableList(false);
VariableSP error_loc_var_sp = variables_sp->FindVariable(
error_location_name, eValueTypeVariableArgument);
if (error_loc_var_sp) {
need_to_check_after_return = false;
ValueObjectSP error_loc_val_sp = frame_sp->GetValueObjectForFrameVariable(
error_loc_var_sp, eNoDynamicValues);
if (error_loc_val_sp && error_loc_val_sp->GetError().Success())
error_val = error_loc_val_sp->GetValue();
return error_val;
}
// Otherwise, see if we know which register it lives in from the calling convention.
// This should probably go in the ABI plugin not here, but the Swift ABI can change with
// swiftlang versions and that would make it awkward in the ABI.
Function *func = frame_sp->GetSymbolContext(eSymbolContextFunction).function;
if (!func)
{
need_to_check_after_return = false;
return error_val;
}
need_to_check_after_return = func->CanThrow();
return error_val;
}
//------------------------------------------------------------------
// Static Functions
//------------------------------------------------------------------
LanguageRuntime *
SwiftLanguageRuntime::CreateInstance(Process *process,
lldb::LanguageType language) {
if (language == eLanguageTypeSwift)
return new SwiftLanguageRuntime(process);
else
return NULL;
}
lldb::BreakpointResolverSP
SwiftLanguageRuntime::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp,
bool throw_bp) {
BreakpointResolverSP resolver_sp;
if (throw_bp)
resolver_sp.reset(new BreakpointResolverName(
bkpt, "swift_willThrow", eFunctionNameTypeBase, eLanguageTypeUnknown,
Breakpoint::Exact, 0, eLazyBoolNo));
// FIXME: We don't do catch breakpoints for ObjC yet.
// Should there be some way for the runtime to specify what it can do in this
// regard?
return resolver_sp;
}
static const char *
SwiftDemangleNodeKindToCString(const swift::Demangle::Node::Kind node_kind) {
#define NODE(e) \
case swift::Demangle::Node::Kind::e: \
return #e;
switch (node_kind) {
#include "swift/Demangling/DemangleNodes.def"
}
return "swift::Demangle::Node::Kind::???";
#undef NODE
}
static OptionDefinition g_swift_demangle_options[] = {
// clang-format off
{LLDB_OPT_SET_1, false, "expand", 'e', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Whether LLDB should print the demangled tree"},
// clang-format on
};
class CommandObjectSwift_Demangle : public CommandObjectParsed {
public:
CommandObjectSwift_Demangle(CommandInterpreter &interpreter)
: CommandObjectParsed(interpreter, "demangle",
"Demangle a Swift mangled name",
"language swift demangle"),
m_options() {}
~CommandObjectSwift_Demangle() {}
virtual Options *GetOptions() { return &m_options; }
class CommandOptions : public Options {
public:
CommandOptions() : Options(), m_expand(false, false) {
OptionParsingStarting(nullptr);
}
virtual ~CommandOptions() {}
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
ExecutionContext *execution_context) override {
Status error;
const int short_option = m_getopt_table[option_idx].val;
switch (short_option) {
case 'e':
m_expand.SetCurrentValue(true);
break;
default:
error.SetErrorStringWithFormat("invalid short option character '%c'",
short_option);
break;
}
return error;
}
void OptionParsingStarting(ExecutionContext *execution_context) override {
m_expand.Clear();
}
llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
return llvm::makeArrayRef(g_swift_demangle_options);
}
// Options table: Required for subclasses of Options.
OptionValueBoolean m_expand;
};
protected:
void PrintNode(swift::Demangle::NodePointer node_ptr, Stream &stream,
int depth = 0) {
if (!node_ptr)
return;
std::string indent(2 * depth, ' ');
stream.Printf("%s", indent.c_str());
stream.Printf("kind=%s",
SwiftDemangleNodeKindToCString(node_ptr->getKind()));
if (node_ptr->hasText()) {
std::string Text = node_ptr->getText();
stream.Printf(", text=\"%s\"", Text.c_str());
}
if (node_ptr->hasIndex())
stream.Printf(", index=%" PRIu64, node_ptr->getIndex());
stream.Printf("\n");
for (auto &&child : *node_ptr) {
PrintNode(child, stream, depth + 1);
}
}
bool DoExecute(Args &command, CommandReturnObject &result) {
for (size_t i = 0; i < command.GetArgumentCount(); i++) {
const char *arg = command.GetArgumentAtIndex(i);
if (arg && *arg) {
swift::Demangle::Context demangle_ctx;
auto node_ptr = demangle_ctx.demangleSymbolAsNode(llvm::StringRef(arg));
if (node_ptr) {
if (m_options.m_expand) {
PrintNode(node_ptr, result.GetOutputStream());
}
result.GetOutputStream().Printf(
"%s ---> %s\n", arg,
swift::Demangle::nodeToString(node_ptr).c_str());
}
}
}
result.SetStatus(lldb::eReturnStatusSuccessFinishResult);
return true;
}
CommandOptions m_options;
};
class CommandObjectSwift_RefCount : public CommandObjectRaw {
public:
CommandObjectSwift_RefCount(CommandInterpreter &interpreter)
: CommandObjectRaw(interpreter, "refcount",
"Inspect the reference count data for a Swift object",
"language swift refcount",
eCommandProcessMustBePaused | eCommandRequiresFrame) {}
~CommandObjectSwift_RefCount() {}
virtual Options *GetOptions() { return nullptr; }
private:
enum class ReferenceCountType {
eReferenceStrong,
eReferenceUnowned,
eReferenceWeak,
};
llvm::Optional<uint32_t> getReferenceCount(StringRef ObjName,
ReferenceCountType Type,
ExecutionContext &exe_ctx,
StackFrameSP &Frame) {
std::string Kind;
switch (Type) {
case ReferenceCountType::eReferenceStrong:
Kind = "";
break;
case ReferenceCountType::eReferenceUnowned:
Kind = "Unowned";
break;
case ReferenceCountType::eReferenceWeak:
Kind = "Weak";
break;
}
EvaluateExpressionOptions eval_options;
eval_options.SetLanguage(lldb::eLanguageTypeSwift);
eval_options.SetResultIsInternal(true);
ValueObjectSP result_valobj_sp;
std::string Expr =
(llvm::Twine("Swift._get") + Kind + llvm::Twine("RetainCount(") +
ObjName + llvm::Twine(")"))
.str();
bool evalStatus = exe_ctx.GetTargetSP()->EvaluateExpression(
Expr, Frame.get(), result_valobj_sp, eval_options);
if (evalStatus != eExpressionCompleted)
return llvm::None;
bool success = false;
uint32_t count = result_valobj_sp->GetSyntheticValue()->GetValueAsUnsigned(
UINT32_MAX, &success);
if (!success)
return llvm::None;
return count;
}
protected:
bool DoExecute(llvm::StringRef command, CommandReturnObject &result) {
StackFrameSP frame_sp(m_exe_ctx.GetFrameSP());
EvaluateExpressionOptions options;
options.SetLanguage(lldb::eLanguageTypeSwift);
options.SetResultIsInternal(true);
ValueObjectSP result_valobj_sp;
// We want to evaluate first the object we're trying to get the
// refcount of, in order, to, e.g. see whether it's available.
// So, given `language swift refcount patatino`, we try to
// evaluate `expr patatino` and fail early in case there is
// an error.
bool evalStatus = m_exe_ctx.GetTargetSP()->EvaluateExpression(
command, frame_sp.get(), result_valobj_sp, options);
if (evalStatus != eExpressionCompleted) {
result.SetStatus(lldb::eReturnStatusFailed);
if (result_valobj_sp && result_valobj_sp->GetError().Fail())
result.AppendError(result_valobj_sp->GetError().AsCString());
return false;
}
// At this point, we're sure we're grabbing in our hands a valid
// object and we can ask questions about it. `refcounts` are only
// defined on class objects, so we throw an error in case we're
// trying to look at something else.
result_valobj_sp = result_valobj_sp->GetQualifiedRepresentationIfAvailable(
lldb::eDynamicCanRunTarget, true);
CompilerType result_type(result_valobj_sp->GetCompilerType());
if (!(result_type.GetTypeInfo() & lldb::eTypeInstanceIsPointer)) {
result.AppendError("refcount only available for class types");
result.SetStatus(lldb::eReturnStatusFailed);
return false;
}
// Ask swift debugger support in the compiler about the objects
// reference counts, and return them to the user.
llvm::Optional<uint32_t> strong = getReferenceCount(
command, ReferenceCountType::eReferenceStrong, m_exe_ctx, frame_sp);
llvm::Optional<uint32_t> unowned = getReferenceCount(
command, ReferenceCountType::eReferenceUnowned, m_exe_ctx, frame_sp);
llvm::Optional<uint32_t> weak = getReferenceCount(
command, ReferenceCountType::eReferenceWeak, m_exe_ctx, frame_sp);
std::string unavailable = "<unavailable>";
result.AppendMessageWithFormat(
"refcount data: (strong = %s, unowned = %s, weak = %s)\n",
strong ? std::to_string(*strong).c_str() : unavailable.c_str(),
unowned ? std::to_string(*unowned).c_str() : unavailable.c_str(),
weak ? std::to_string(*weak).c_str() : unavailable.c_str());
result.SetStatus(lldb::eReturnStatusSuccessFinishResult);
return true;
}
};
class CommandObjectMultiwordSwift : public CommandObjectMultiword {
public:
CommandObjectMultiwordSwift(CommandInterpreter &interpreter)
: CommandObjectMultiword(
interpreter, "swift",
"A set of commands for operating on the Swift Language Runtime.",
"swift <subcommand> [<subcommand-options>]") {
LoadSubCommand("demangle", CommandObjectSP(new CommandObjectSwift_Demangle(
interpreter)));
LoadSubCommand("refcount", CommandObjectSP(new CommandObjectSwift_RefCount(
interpreter)));
}
virtual ~CommandObjectMultiwordSwift() {}
};
void SwiftLanguageRuntime::Initialize() {
PluginManager::RegisterPlugin(
GetPluginNameStatic(), "Language runtime for the Swift language",
CreateInstance,
[](CommandInterpreter &interpreter) -> lldb::CommandObjectSP {
return CommandObjectSP(new CommandObjectMultiwordSwift(interpreter));
},
GetBreakpointExceptionPrecondition);
}
void SwiftLanguageRuntime::Terminate() {
PluginManager::UnregisterPlugin(CreateInstance);
}
lldb_private::ConstString SwiftLanguageRuntime::GetPluginNameStatic() {
static ConstString g_name("swift");
return g_name;
}
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
lldb_private::ConstString SwiftLanguageRuntime::GetPluginName() {
return GetPluginNameStatic();
}
uint32_t SwiftLanguageRuntime::GetPluginVersion() { return 1; }
| 1 | 19,876 | This one is unrelated to the GetSymbolVendor removal ... the API to GetValueAsData was changed. | apple-swift-lldb | cpp |
@@ -45,6 +45,7 @@ func TestMarshalUnmarshalJSON(t *testing.T) {
desiredStatusUnsafe: resourcestatus.ResourceCreated,
knownStatusUnsafe: resourcestatus.ResourceCreated,
appliedStatusUnsafe: resourcestatus.ResourceCreated,
+ networkMode: bridgeNetworkMode,
}
bytes, err := json.Marshal(firelensResIn) | 1 | // +build linux,unit
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package firelens
import (
"encoding/json"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
resourcestatus "github.com/aws/amazon-ecs-agent/agent/taskresource/status"
)
func TestMarshalUnmarshalJSON(t *testing.T) {
testCreatedAt := time.Now()
testContainerToLogOptions := map[string]map[string]string{
"container": testFluentdOptions,
}
firelensResIn := &FirelensResource{
cluster: testCluster,
taskARN: testTaskARN,
taskDefinition: testTaskDefinition,
ec2InstanceID: testEC2InstanceID,
resourceDir: testResourceDir,
firelensConfigType: FirelensConfigTypeFluentd,
ecsMetadataEnabled: true,
containerToLogOptions: testContainerToLogOptions,
terminalReason: testTerminalResason,
createdAtUnsafe: testCreatedAt,
desiredStatusUnsafe: resourcestatus.ResourceCreated,
knownStatusUnsafe: resourcestatus.ResourceCreated,
appliedStatusUnsafe: resourcestatus.ResourceCreated,
}
bytes, err := json.Marshal(firelensResIn)
require.NoError(t, err)
firelensResOut := &FirelensResource{}
err = json.Unmarshal(bytes, firelensResOut)
require.NoError(t, err)
assert.Equal(t, testCluster, firelensResOut.cluster)
assert.Equal(t, testTaskARN, firelensResOut.taskARN)
assert.Equal(t, testTaskDefinition, firelensResOut.taskDefinition)
assert.True(t, firelensResOut.ecsMetadataEnabled)
assert.Equal(t, testContainerToLogOptions, firelensResOut.containerToLogOptions)
assert.Equal(t, testTerminalResason, firelensResOut.terminalReason)
// Can't use assert.Equal for time here. See https://github.com/golang/go/issues/22957.
assert.True(t, testCreatedAt.Equal(firelensResOut.createdAtUnsafe))
assert.Equal(t, resourcestatus.ResourceCreated, firelensResOut.desiredStatusUnsafe)
assert.Equal(t, resourcestatus.ResourceCreated, firelensResOut.knownStatusUnsafe)
assert.Equal(t, resourcestatus.ResourceCreated, firelensResOut.appliedStatusUnsafe)
assert.Equal(t, testTerminalResason, firelensResOut.terminalReason)
}
| 1 | 23,280 | can you assert the value of this field below similar to other fields? | aws-amazon-ecs-agent | go |
@@ -11,6 +11,7 @@ package net.sourceforge.pmd.lang.java.ast;
* <pre class="grammar">
*
* PrimaryExpression ::= {@linkplain ASTLiteral Literal}
+ * | {@link ASTClassLiteral ClassLiteral}
* | {@linkplain ASTMethodCall MethodCall}
* | {@linkplain ASTFieldAccess FieldAccess}
* | {@linkplain ASTConstructorCall ConstructorCall} | 1 | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
/**
* Tags those {@link ASTExpression expressions} that are categorised as primary
* by the JLS.
*
* <pre class="grammar">
*
* PrimaryExpression ::= {@linkplain ASTLiteral Literal}
* | {@linkplain ASTMethodCall MethodCall}
* | {@linkplain ASTFieldAccess FieldAccess}
* | {@linkplain ASTConstructorCall ConstructorCall}
* | {@linkplain ASTArrayAllocation ArrayAllocation}
* | {@linkplain ASTArrayAccess ArrayAccess}
* | {@linkplain ASTVariableReference VariableReference}
* | {@linkplain ASTParenthesizedExpression ParenthesizedExpression}
* | {@linkplain ASTMethodReference MethodReference}
* | {@linkplain ASTThisExpression ThisExpression}
* | {@linkplain ASTSuperExpression SuperExpression}
*
*
* </pre>
*
*
*/
public interface ASTPrimaryExpression extends ASTExpression {
}
| 1 | 16,014 | I'll change that to "linkplain" for consistency :) | pmd-pmd | java |
@@ -196,7 +196,12 @@ class RouteFactory(object):
self.resource_name,
**matchdict)
if object_id == '*':
- object_uri = object_uri.replace('%2A', '*')
+ # Express the object_uri pattern with precision
+ # XXX: we could get the model.id_generator pattern, but
+ # since the backend replace * by .* we can't.
+ # See Kinto/kinto#970
+ id_pattern = "[a-zA-Z0-9_-]+"
+ object_uri = object_uri.replace('%2A', id_pattern)
except KeyError:
# Maybe the resource has no single record endpoint.
# We consider that object URIs in permissions backend will | 1 | import functools
import six
from pyramid.settings import aslist
from pyramid.security import IAuthorizationPolicy, Authenticated
from zope.interface import implementer
from kinto.core import utils
from kinto.core.storage import exceptions as storage_exceptions
# A permission is called "dynamic" when it's computed at request time.
DYNAMIC = 'dynamic'
# When permission is set to "private", only the current user is allowed.
PRIVATE = 'private'
def groupfinder(userid, request):
"""Fetch principals from permission backend for the specified `userid`.
This is plugged by default using the ``multiauth.groupfinder`` setting.
"""
backend = getattr(request.registry, 'permission', None)
# Permission backend not configured. Ignore.
if not backend:
return []
# Safety check when Kinto-Core is used without pyramid_multiauth.
if request.prefixed_userid:
userid = request.prefixed_userid
# Query the permission backend only once per request (e.g. batch).
reify_key = userid + '_principals'
if reify_key not in request.bound_data:
principals = backend.get_user_principals(userid)
request.bound_data[reify_key] = principals
return request.bound_data[reify_key]
@implementer(IAuthorizationPolicy)
class AuthorizationPolicy(object):
"""Default authorization class, that leverages the permission backend
for shareable resources.
"""
get_bound_permissions = None
"""Callable that takes an object id and a permission and returns
a list of tuples (<object id>, <permission>). Useful when objects
permission depend on others."""
def permits(self, context, principals, permission):
if permission == PRIVATE:
return Authenticated in principals
principals = context.get_prefixed_principals()
if permission == DYNAMIC:
permission = context.required_permission
create_permission = '%s:create' % context.resource_name
if permission == 'create':
permission = create_permission
object_id = context.permission_object_id
if self.get_bound_permissions is None:
bound_perms = [(object_id, permission)]
else:
bound_perms = self.get_bound_permissions(object_id, permission)
allowed = context.check_permission(principals, bound_perms)
# If not allowed on this collection, but some records are shared with
# the current user, then authorize.
# The ShareableResource class will take care of the filtering.
is_list_operation = (context.on_collection and not permission.endswith('create'))
if not allowed and is_list_operation:
shared = context.fetch_shared_records(permission,
principals,
self.get_bound_permissions)
# If allowed to create this kind of object on parent, then allow to obtain the list.
if len(bound_perms) > 0:
# Here we consider that parent URI is one path level above.
parent_uri = '/'.join(object_id.split('/')[:-1])
parent_create_perm = [(parent_uri, create_permission)]
else:
parent_create_perm = [('', 'create')] # Root object.
allowed_to_create = context.check_permission(principals, parent_create_perm)
allowed = shared or allowed_to_create
return allowed
def principals_allowed_by_permission(self, context, permission):
raise NotImplementedError() # PRAGMA NOCOVER
class RouteFactory(object):
resource_name = None
on_collection = False
required_permission = None
permission_object_id = None
current_record = None
shared_ids = None
method_permissions = {
"head": "read",
"get": "read",
"post": "create",
"delete": "write",
"patch": "write"
}
def __init__(self, request):
# Store some shortcuts.
permission = request.registry.permission
self._check_permission = permission.check_permission
self._get_accessible_objects = permission.get_accessible_objects
self.get_prefixed_principals = functools.partial(utils.prefixed_principals, request)
# Store current resource and required permission.
service = utils.current_service(request)
is_on_resource = (service is not None and
hasattr(service, 'viewset') and
hasattr(service, 'resource'))
if is_on_resource:
self.resource_name = request.current_resource_name
self.on_collection = getattr(service, "type", None) == "collection"
self.permission_object_id, self.required_permission = (
self._find_required_permission(request, service))
# To obtain shared records on a collection endpoint, use a match:
self._object_id_match = self.get_permission_object_id(request, '*')
self._settings = request.registry.settings
def check_permission(self, principals, bound_perms):
"""Read allowed principals from settings, if not any, query the permission
backend to check if view is allowed.
"""
if not bound_perms:
bound_perms = [(self.resource_name, self.required_permission)]
for (_, permission) in bound_perms:
setting = '%s_%s_principals' % (self.resource_name, permission)
allowed_principals = aslist(self._settings.get(setting, ''))
if allowed_principals:
if bool(set(allowed_principals) & set(principals)):
return True
return self._check_permission(principals, bound_perms)
def fetch_shared_records(self, perm, principals, get_bound_permissions):
"""Fetch records that are readable or writable for the current
principals.
See :meth:`kinto.core.authorization.AuthorizationPolicy.permits`
If no record is shared, it returns None.
.. warning::
This sets the ``shared_ids`` attribute to the context with the
return value. The attribute is then read by
:class:`kinto.core.resource.ShareableResource`
"""
if get_bound_permissions:
bound_perms = get_bound_permissions(self._object_id_match, perm)
else:
bound_perms = [(self._object_id_match, perm)]
by_obj_id = self._get_accessible_objects(principals, bound_perms)
ids = by_obj_id.keys()
# Store for later use in ``ShareableResource``.
self.shared_ids = [self._extract_object_id(id_) for id_ in ids]
return self.shared_ids
def get_permission_object_id(self, request, object_id=None):
"""Returns the permission object id for the current request.
In the nominal case, it is just the current URI without version prefix.
For collections, it is the related record URI using the specified
`object_id`.
See :meth:`kinto.core.resource.model.SharableModel` and
:meth:`kinto.core.authorization.RouteFactory.__init__`
"""
object_uri = utils.strip_uri_prefix(request.path)
if self.on_collection and object_id is not None:
# With the current request on a collection, the record URI must
# be found out by inspecting the collection service and its sibling
# record service.
matchdict = request.matchdict.copy()
matchdict['id'] = object_id
try:
object_uri = utils.instance_uri(request,
self.resource_name,
**matchdict)
if object_id == '*':
object_uri = object_uri.replace('%2A', '*')
except KeyError:
# Maybe the resource has no single record endpoint.
# We consider that object URIs in permissions backend will
# be stored naively:
object_uri = object_uri + '/' + object_id
return object_uri
def _extract_object_id(self, object_uri):
# XXX: Rewrite using kinto.core.utils.view_lookup() and matchdict['id']
return object_uri.split('/')[-1]
def _find_required_permission(self, request, service):
"""Find out what is the permission object id and the required
permission.
.. note::
This method saves an attribute ``self.current_record`` used
in :class:`kinto.core.resource.UserResource`.
"""
# By default, it's a URI a and permission associated to the method.
permission_object_id = self.get_permission_object_id(request)
method = request.method.lower()
required_permission = self.method_permissions.get(method)
# For create permission, the object id is the plural endpoint.
collection_path = six.text_type(service.collection_path)
collection_path = collection_path.format(**request.matchdict)
# In the case of a "PUT", check if the targetted record already
# exists, return "write" if it does, "create" otherwise.
if request.method.lower() == "put":
resource = service.resource(request=request, context=self)
try:
record = resource.model.get_record(resource.record_id)
# Save a reference, to avoid refetching from storage in
# resource.
self.current_record = record
except storage_exceptions.RecordNotFoundError:
# The record does not exist, the permission to create on
# the related collection is required.
permission_object_id = collection_path
required_permission = "create"
else:
# For safe creations, the user needs a create permission.
# See Kinto/kinto#792
if request.headers.get('If-None-Match') == '*':
permission_object_id = collection_path
required_permission = "create"
else:
required_permission = "write"
return (permission_object_id, required_permission)
| 1 | 10,267 | This is fix. But since the history resource was relying on the bug to work, I had to do some changes regarding the history entries (eg. explicit declare that the permissions inherit from bucket) | Kinto-kinto | py |
@@ -142,6 +142,11 @@ public class DocsStreamer implements Iterator<SolrDocument> {
return docIterator.hasNext();
}
+ // called at the end of the stream
+ public void finish(){
+ if (transformer != null) transformer.finish();
+ }
+
public SolrDocument next() {
int id = docIterator.nextDoc();
idx++; | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.response;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.util.BytesRef;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrException;
import org.apache.solr.response.transform.DocTransformer;
import org.apache.solr.schema.BinaryField;
import org.apache.solr.schema.BoolField;
import org.apache.solr.schema.DatePointField;
import org.apache.solr.schema.DoublePointField;
import org.apache.solr.schema.FieldType;
import org.apache.solr.schema.FloatPointField;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.IntPointField;
import org.apache.solr.schema.LongPointField;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.schema.StrField;
import org.apache.solr.schema.TextField;
import org.apache.solr.schema.TrieDateField;
import org.apache.solr.schema.TrieDoubleField;
import org.apache.solr.schema.TrieField;
import org.apache.solr.schema.TrieFloatField;
import org.apache.solr.schema.TrieIntField;
import org.apache.solr.schema.TrieLongField;
import org.apache.solr.search.DocIterator;
import org.apache.solr.search.DocList;
import org.apache.solr.search.ReturnFields;
import org.apache.solr.search.SolrDocumentFetcher;
import org.apache.solr.search.SolrReturnFields;
/**
* This streams SolrDocuments from a DocList and applies transformer
*/
public class DocsStreamer implements Iterator<SolrDocument> {
public static final Set<Class> KNOWN_TYPES = new HashSet<>();
private final org.apache.solr.response.ResultContext rctx;
private final SolrDocumentFetcher docFetcher; // a collaborator of SolrIndexSearcher
private final DocList docs;
private final DocTransformer transformer;
private final DocIterator docIterator;
private final Set<String> fnames; // returnFields.getLuceneFieldNames(). Maybe null. Not empty.
private final boolean onlyPseudoFields;
private final Set<String> dvFieldsToReturn; // maybe null. Not empty.
private int idx = -1;
public DocsStreamer(ResultContext rctx) {
this.rctx = rctx;
this.docs = rctx.getDocList();
transformer = rctx.getReturnFields().getTransformer();
docIterator = this.docs.iterator();
fnames = rctx.getReturnFields().getLuceneFieldNames();
//TODO move onlyPseudoFields calc to ReturnFields
onlyPseudoFields = (fnames == null && !rctx.getReturnFields().wantsAllFields() && !rctx.getReturnFields().hasPatternMatching())
|| (fnames != null && fnames.size() == 1 && SolrReturnFields.SCORE.equals(fnames.iterator().next()));
// add non-stored DV fields that may have been requested
docFetcher = rctx.getSearcher().getDocFetcher();
dvFieldsToReturn = calcDocValueFieldsForReturn(docFetcher, rctx.getReturnFields());
if (transformer != null) transformer.setContext(rctx);
}
// TODO move to ReturnFields ? Or SolrDocumentFetcher ?
public static Set<String> calcDocValueFieldsForReturn(SolrDocumentFetcher docFetcher, ReturnFields returnFields) {
Set<String> result = null;
if (returnFields.wantsAllFields()) {
// check whether there are no additional fields
Set<String> fieldNames = returnFields.getLuceneFieldNames(true);
if (fieldNames == null) {
result = docFetcher.getNonStoredDVs(true);
} else {
result = new HashSet<>(docFetcher.getNonStoredDVs(true)); // copy
// add all requested fields that may be useDocValuesAsStored=false
for (String fl : fieldNames) {
if (docFetcher.getNonStoredDVs(false).contains(fl)) {
result.add(fl);
}
}
}
} else {
if (returnFields.hasPatternMatching()) {
for (String s : docFetcher.getNonStoredDVs(true)) {
if (returnFields.wantsField(s)) {
if (null == result) {
result = new HashSet<>();
}
result.add(s);
}
}
} else {
Set<String> fnames = returnFields.getLuceneFieldNames();
if (fnames == null) {
return null;
}
result = new HashSet<>(fnames); // copy
// here we get all non-stored dv fields because even if a user has set
// useDocValuesAsStored=false in schema, he may have requested a field
// explicitly using the fl parameter
result.retainAll(docFetcher.getNonStoredDVs(false));
}
}
if (result != null && result.isEmpty()) {
return null;
}
return result;
}
public int currentIndex() {
return idx;
}
public boolean hasNext() {
return docIterator.hasNext();
}
public SolrDocument next() {
int id = docIterator.nextDoc();
idx++;
SolrDocument sdoc = null;
if (onlyPseudoFields) {
// no need to get stored fields of the document, see SOLR-5968
sdoc = new SolrDocument();
} else {
try {
Document doc = docFetcher.doc(id, fnames);
sdoc = convertLuceneDocToSolrDoc(doc, rctx.getSearcher().getSchema()); // make sure to use the schema from the searcher and not the request (cross-core)
// decorate the document with non-stored docValues fields
if (dvFieldsToReturn != null) {
docFetcher.decorateDocValueFields(sdoc, id, dvFieldsToReturn);
}
} catch (IOException e) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error reading document with docId " + id, e);
}
}
if (transformer != null) {
boolean doScore = rctx.wantsScores();
try {
transformer.transform(sdoc, id, doScore ? docIterator.score() : 0);
} catch (IOException e) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error applying transformer", e);
}
}
return sdoc;
}
// TODO move to SolrDocumentFetcher ? Refactor to also call docFetcher.decorateDocValueFields(...) ?
public static SolrDocument convertLuceneDocToSolrDoc(Document doc, final IndexSchema schema) {
SolrDocument out = new SolrDocument();
for (IndexableField f : doc.getFields()) {
// Make sure multivalued fields are represented as lists
Object existing = out.get(f.name());
if (existing == null) {
SchemaField sf = schema.getFieldOrNull(f.name());
if (sf != null && sf.multiValued()) {
List<Object> vals = new ArrayList<>();
vals.add(f);
out.setField(f.name(), vals);
} else {
out.setField(f.name(), f);
}
} else {
out.addField(f.name(), f);
}
}
return out;
}
@Override
public void remove() { //do nothing
}
public static Object getValue(SchemaField sf, IndexableField f) {
FieldType ft = null;
if (sf != null) ft = sf.getType();
if (ft == null) { // handle fields not in the schema
BytesRef bytesRef = f.binaryValue();
if (bytesRef != null) {
if (bytesRef.offset == 0 && bytesRef.length == bytesRef.bytes.length) {
return bytesRef.bytes;
} else {
final byte[] bytes = new byte[bytesRef.length];
System.arraycopy(bytesRef.bytes, bytesRef.offset, bytes, 0, bytesRef.length);
return bytes;
}
} else return f.stringValue();
} else {
if (KNOWN_TYPES.contains(ft.getClass())) {
return ft.toObject(f);
} else {
return ft.toExternal(f);
}
}
}
static {
KNOWN_TYPES.add(BoolField.class);
KNOWN_TYPES.add(StrField.class);
KNOWN_TYPES.add(TextField.class);
KNOWN_TYPES.add(TrieField.class);
KNOWN_TYPES.add(TrieIntField.class);
KNOWN_TYPES.add(TrieLongField.class);
KNOWN_TYPES.add(TrieFloatField.class);
KNOWN_TYPES.add(TrieDoubleField.class);
KNOWN_TYPES.add(TrieDateField.class);
KNOWN_TYPES.add(BinaryField.class);
KNOWN_TYPES.add(IntPointField.class);
KNOWN_TYPES.add(LongPointField.class);
KNOWN_TYPES.add(DoublePointField.class);
KNOWN_TYPES.add(FloatPointField.class);
KNOWN_TYPES.add(DatePointField.class);
// We do not add UUIDField because UUID object is not a supported type in JavaBinCodec
// and if we write UUIDField.toObject, we wouldn't know how to handle it in the client side
}
}
| 1 | 26,373 | can't we leverage Closeable here and get some sugar&warns? Also, line 89 still calls setContext() .. is it right? or I'm missing something? | apache-lucene-solr | java |
@@ -52,7 +52,7 @@ func TestPing(t *testing.T) {
// ping
peerID := "124"
greetings := []string{"hey", "there", "fella"}
- rtt, err := client.Ping(context.Background(), peerID, greetings...)
+ rtt, err := client.Ping(context.Background(), []byte(peerID), greetings...)
if err != nil {
t.Fatal(err)
} | 1 | // Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pingpong_test
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"runtime"
"testing"
"time"
"github.com/ethersphere/bee/pkg/logging"
"github.com/ethersphere/bee/pkg/p2p"
"github.com/ethersphere/bee/pkg/p2p/protobuf"
"github.com/ethersphere/bee/pkg/p2p/streamtest"
"github.com/ethersphere/bee/pkg/pingpong"
"github.com/ethersphere/bee/pkg/pingpong/pb"
)
func TestPing(t *testing.T) {
logger := logging.New(ioutil.Discard, 0)
// create a pingpong server that handles the incoming stream
server := pingpong.New(pingpong.Options{
Logger: logger,
})
// setup the stream recorder to record stream data
recorder := streamtest.New(
streamtest.WithProtocols(server.Protocol()),
streamtest.WithMiddlewares(func(f p2p.HandlerFunc) p2p.HandlerFunc {
if runtime.GOOS == "windows" {
// windows has a bit lower time resolution
// so, slow down the handler with a middleware
// not to get 0s for rtt value
time.Sleep(100 * time.Millisecond)
}
return f
}),
)
// create a pingpong client that will do pinging
client := pingpong.New(pingpong.Options{
Streamer: recorder,
Logger: logger,
})
// ping
peerID := "124"
greetings := []string{"hey", "there", "fella"}
rtt, err := client.Ping(context.Background(), peerID, greetings...)
if err != nil {
t.Fatal(err)
}
// check that RTT is a sane value
if rtt <= 0 {
t.Errorf("invalid RTT value %v", rtt)
}
// get a record for this stream
records, err := recorder.Records(peerID, "pingpong", "pingpong", "1.0.0")
if err != nil {
t.Fatal(err)
}
if l := len(records); l != 1 {
t.Fatalf("got %v records, want %v", l, 1)
}
record := records[0]
// validate received ping greetings from the client
wantGreetings := greetings
messages, err := protobuf.ReadMessages(
bytes.NewReader(record.In()),
func() protobuf.Message { return new(pb.Ping) },
)
if err != nil {
t.Fatal(err)
}
var gotGreetings []string
for _, m := range messages {
gotGreetings = append(gotGreetings, m.(*pb.Ping).Greeting)
}
if fmt.Sprint(gotGreetings) != fmt.Sprint(wantGreetings) {
t.Errorf("got greetings %v, want %v", gotGreetings, wantGreetings)
}
// validate sent pong responses by handler
var wantResponses []string
for _, g := range greetings {
wantResponses = append(wantResponses, "{"+g+"}")
}
messages, err = protobuf.ReadMessages(
bytes.NewReader(record.Out()),
func() protobuf.Message { return new(pb.Pong) },
)
if err != nil {
t.Fatal(err)
}
var gotResponses []string
for _, m := range messages {
gotResponses = append(gotResponses, m.(*pb.Pong).Response)
}
if fmt.Sprint(gotResponses) != fmt.Sprint(wantResponses) {
t.Errorf("got responses %v, want %v", gotResponses, wantResponses)
}
}
| 1 | 8,718 | Use explicit swarm.Address when defining peerID, by using NewAddress, and remove conversion here. | ethersphere-bee | go |
@@ -30,9 +30,13 @@ const (
rootMountPoint = "/"
rootUser = "root"
+ // RpmDependenciesDirectory is the directory which contains RPM database. It is not required for images that do not contain RPM.
+ RpmDependenciesDirectory = "/var/lib/rpm"
+
// /boot directory should be only accesible by root. The directories need the execute bit as well.
bootDirectoryFileMode = 0600
bootDirectoryDirMode = 0700
+ shadowFile = "/etc/shadow"
)
// PackageList represents the list of packages to install into an image | 1 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package installutils
import (
"crypto/rand"
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"syscall"
"time"
"microsoft.com/pkggen/imagegen/configuration"
"microsoft.com/pkggen/imagegen/diskutils"
"microsoft.com/pkggen/internal/file"
"microsoft.com/pkggen/internal/jsonutils"
"microsoft.com/pkggen/internal/logger"
"microsoft.com/pkggen/internal/pkgjson"
"microsoft.com/pkggen/internal/retry"
"microsoft.com/pkggen/internal/safechroot"
"microsoft.com/pkggen/internal/shell"
)
const (
rootMountPoint = "/"
rootUser = "root"
// /boot directory should be only accesible by root. The directories need the execute bit as well.
bootDirectoryFileMode = 0600
bootDirectoryDirMode = 0700
)
// PackageList represents the list of packages to install into an image
type PackageList struct {
Packages []string `json:"packages"`
}
// CreateMountPointPartitionMap creates a map between the mountpoint supplied in the config file and the device path
// of the partition
// - partDevPathMap is a map of partition IDs to partition device paths
// - partIDToFsTypeMap is a map of partition IDs to filesystem type
// - config is the SystemConfig from a config file
// Output
// - mountPointDevPathMap is a map of mountpoint to partition device path
// - mountPointToFsTypeMap is a map of mountpoint to filesystem type
// - mountPointToMountArgsMap is a map of mountpoint to mount arguments to be passed on a call to mount
func CreateMountPointPartitionMap(partDevPathMap, partIDToFsTypeMap map[string]string, config configuration.SystemConfig) (mountPointDevPathMap, mountPointToFsTypeMap, mountPointToMountArgsMap map[string]string) {
mountPointDevPathMap = make(map[string]string)
mountPointToFsTypeMap = make(map[string]string)
mountPointToMountArgsMap = make(map[string]string)
// Go through each PartitionSetting
for _, partitionSetting := range config.PartitionSettings {
logger.Log.Tracef("%v[%v]", partitionSetting.ID, partitionSetting.MountPoint)
partDevPath, ok := partDevPathMap[partitionSetting.ID]
if ok {
mountPointDevPathMap[partitionSetting.MountPoint] = partDevPath
mountPointToFsTypeMap[partitionSetting.MountPoint] = partIDToFsTypeMap[partitionSetting.ID]
mountPointToMountArgsMap[partitionSetting.MountPoint] = partitionSetting.MountOptions
}
logger.Log.Tracef("%v", mountPointDevPathMap)
}
return
}
// CreateInstallRoot walks through the map of mountpoints and mounts the partitions into installroot
// - installRoot is the destination path to mount these partitions
// - mountPointMap is the map of mountpoint to partition device path
func CreateInstallRoot(installRoot string, mountPointMap, mountPointToMountArgsMap map[string]string) (installMap map[string]string, err error) {
installMap = make(map[string]string)
// Always mount root first
err = mountSingleMountPoint(installRoot, rootMountPoint, mountPointMap[rootMountPoint], mountPointToMountArgsMap[rootMountPoint])
if err != nil {
return
}
installMap[rootMountPoint] = mountPointMap[rootMountPoint]
// Mount rest of the mountpoints
for mountPoint, device := range mountPointMap {
if mountPoint != "" && mountPoint != rootMountPoint {
err = mountSingleMountPoint(installRoot, mountPoint, device, mountPointToMountArgsMap[mountPoint])
if err != nil {
return
}
installMap[mountPoint] = device
}
}
return
}
// DestroyInstallRoot unmounts each of the installroot mountpoints in order, ensuring that the root mountpoint is last
// - installRoot is the path to the root where the mountpoints exist
// - installMap is the map of mountpoints to partition device paths
func DestroyInstallRoot(installRoot string, installMap map[string]string) (err error) {
logger.Log.Trace("Destroying InstallRoot")
// Convert the installMap into a slice of mount points so it can be sorted
var allMountsToUnmount []string
for mountPoint := range installMap {
// Skip empty mount points
if mountPoint == "" {
continue
}
allMountsToUnmount = append(allMountsToUnmount, mountPoint)
}
// Sort the mount points
// This way nested mounts will be handled correctly:
// e.g.: /dev/pts is unmounted and then /dev is.
sort.Sort(sort.Reverse(sort.StringSlice(allMountsToUnmount)))
for _, mountPoint := range allMountsToUnmount {
err = unmountSingleMountPoint(installRoot, mountPoint)
if err != nil {
return
}
}
return
}
func mountSingleMountPoint(installRoot, mountPoint, device, extraOptions string) (err error) {
mountPath := filepath.Join(installRoot, mountPoint)
err = os.MkdirAll(mountPath, os.ModePerm)
if err != nil {
logger.Log.Warnf("Failed to create mountpoint: %v", err)
return
}
err = mount(mountPath, device, extraOptions)
return
}
func unmountSingleMountPoint(installRoot, mountPoint string) (err error) {
mountPath := filepath.Join(installRoot, mountPoint)
err = umount(mountPath)
return
}
func mount(path, device, extraOptions string) (err error) {
const squashErrors = false
if extraOptions == "" {
err = shell.ExecuteLive(squashErrors, "mount", device, path)
} else {
err = shell.ExecuteLive(squashErrors, "mount", "-o", extraOptions, device, path)
}
if err != nil {
return
}
return
}
func umount(path string) (err error) {
const (
retryAttempts = 3
retryDuration = time.Second
unmountFlags = 0
)
err = retry.Run(func() error {
return syscall.Unmount(path, unmountFlags)
}, retryAttempts, retryDuration)
return
}
// PackageNamesFromSingleSystemConfig goes through the packageslist field in the systemconfig and extracts the list of packages
// from each of the packagelists
// - systemConfig is the systemconfig field from the config file
// Since kernel is not part of the packagelist, it is added separately from KernelOptions.
func PackageNamesFromSingleSystemConfig(systemConfig configuration.SystemConfig) (finalPkgList []string, err error) {
var packages PackageList
for _, packageList := range systemConfig.PackageLists {
// Read json
logger.Log.Tracef("Processing packages from packagelist %v", packageList)
packages, err = getPackagesFromJSON(packageList)
if err != nil {
return
}
logger.Log.Tracef("packages %v", packages)
finalPkgList = append(finalPkgList, packages.Packages...)
}
logger.Log.Tracef("finalPkgList = %v", finalPkgList)
return
}
// SelectKernelPackage selects the kernel to use for the current installation
// based on the KernelOptions field of the system configuration.
func SelectKernelPackage(systemConfig configuration.SystemConfig, isLiveInstall bool) (kernelPkg string, err error) {
const (
defaultOption = "default"
hypervOption = "hyperv"
)
optionToUse := defaultOption
// Only consider Hyper-V for an ISO
if isLiveInstall {
// Only check if running on Hyper V if there's a kernel option for it
_, found := systemConfig.KernelOptions[hypervOption]
if found {
isHyperV, err := isRunningInHyperV()
if err != nil {
logger.Log.Warnf("Unable to detect if the current system is Hyper-V, using the default kernel")
} else if isHyperV {
optionToUse = hypervOption
}
}
}
kernelPkg = systemConfig.KernelOptions[optionToUse]
if kernelPkg == "" {
err = fmt.Errorf("no kernel for option (%s) set", optionToUse)
return
}
return
}
// PackageNamesFromConfig takes the union of top level package names for every system configuration in a top level
// config file.
// - config is the config file to proccess
func PackageNamesFromConfig(config configuration.Config) (packageList []*pkgjson.PackageVer, err error) {
// For each system config, clone all packages that go into it
for _, systemCfg := range config.SystemConfigs {
var packagesToInstall []string
// Get list of packages to install into image
packagesToInstall, err = PackageNamesFromSingleSystemConfig(systemCfg)
if err != nil {
return
}
packages := make([]*pkgjson.PackageVer, 0, len(packagesToInstall))
for _, pkg := range packagesToInstall {
packages = append(packages, &pkgjson.PackageVer{
Name: pkg,
})
}
packageList = append(packageList, packages...)
}
return
}
// PopulateInstallRoot fills the installroot with packages and configures the image for boot
// - installChroot is a pointer to the install Chroot object
// - packagesToInstall is a slice of packages to install
// - config is the systemconfig field from the config file
// - installMap is a map of mountpoints to physical device paths
// - mountPointToFsTypeMap is a map of mountpoints to filesystem type
// - mountPointToMountArgsMap is a map of mountpoints to mount options
// - isRootFS specifies if the installroot is either backed by a directory (rootfs) or a raw disk
// - encryptedRoot stores information about the encrypted root device if root encryption is enabled
func PopulateInstallRoot(installChroot *safechroot.Chroot, packagesToInstall []string, config configuration.SystemConfig, installMap, mountPointToFsTypeMap, mountPointToMountArgsMap map[string]string, isRootFS bool, encryptedRoot diskutils.EncryptedRootDevice) (err error) {
const (
filesystemPkg = "filesystem"
)
defer stopGPGAgent(installChroot)
ReportAction("Initializing RPM Database")
installRoot := filepath.Join(rootMountPoint, installChroot.RootDir())
// Initialize RPM Database so we can install RPMs into the installroot
err = initializeRpmDatabase(installRoot)
if err != nil {
return
}
// Calculate how many packages need to be installed so an accurate percent complete can be reported
totalPackages, err := calculateTotalPackages(packagesToInstall, installRoot)
if err != nil {
return
}
// Keep a running total of how many packages have be installed through all the `tdnfInstall` invocations
packagesInstalled := 0
// Install filesystem package first
packagesInstalled, err = tdnfInstall(filesystemPkg, installRoot, packagesInstalled, totalPackages)
if err != nil {
return
}
hostname := config.Hostname
if !isRootFS {
// Add /etc/hostname
err = updateHostname(installChroot.RootDir(), hostname)
if err != nil {
return
}
}
// Install packages one-by-one to avoid exhausting memory
// on low resource systems
for _, pkg := range packagesToInstall {
packagesInstalled, err = tdnfInstall(pkg, installRoot, packagesInstalled, totalPackages)
if err != nil {
return
}
}
// Copy additional files
err = copyAdditionalFiles(installChroot, config)
if err != nil {
return
}
if !isRootFS {
// Configure system files
err = configureSystemFiles(installChroot, hostname, installMap, mountPointToFsTypeMap, mountPointToMountArgsMap, encryptedRoot)
if err != nil {
return
}
// Add groups
err = addGroups(installChroot, config.Groups)
if err != nil {
return
}
}
// Add users
err = addUsers(installChroot, config.Users)
if err != nil {
return
}
// Add machine-id
err = addMachineID(installChroot)
if err != nil {
return
}
// Configure for encryption
if config.Encryption.Enable {
err = updateInitramfsForEncrypt(installChroot)
if err != nil {
return
}
}
// Run post-install scripts from within the installroot chroot
err = runPostInstallScripts(installChroot, config)
return
}
func initializeRpmDatabase(installRoot string) (err error) {
stdout, stderr, err := shell.Execute("rpm", "--root", installRoot, "--initdb")
if err != nil {
logger.Log.Warnf("Failed to create rpm database: %v", err)
logger.Log.Warn(stdout)
logger.Log.Warn(stderr)
return
}
err = initializeTdnfConfiguration(installRoot)
return
}
// initializeTdnfConfiguration installs the 'mariner-release' package
// into the clean RPM root. The package is used by tdnf to properly set
// the default values for its variables and internal configuration.
func initializeTdnfConfiguration(installRoot string) (err error) {
const (
squashErrors = false
releasePackage = "mariner-release"
)
logger.Log.Debugf("Downloading '%s' package to a clean RPM root under '%s'.", releasePackage, installRoot)
err = shell.ExecuteLive(squashErrors, "tdnf", "download", "--alldeps", "--destdir", installRoot, releasePackage)
if err != nil {
logger.Log.Errorf("Failed to prepare the RPM database on downloading the 'mariner-release' package: %v", err)
return
}
rpmSearch := filepath.Join(installRoot, "*.rpm")
rpmFiles, err := filepath.Glob(rpmSearch)
if err != nil {
logger.Log.Errorf("Failed to prepare the RPM database while searching for RPM files: %v", err)
return
}
defer func() {
logger.Log.Tracef("Cleaning up leftover RPM files after installing 'mariner-release' package under '%s'.", installRoot)
for _, file := range rpmFiles {
err = os.Remove(file)
if err != nil {
logger.Log.Errorf("Failed to prepare the RPM database on removing leftover file (%s): %v", file, err)
return
}
}
}()
logger.Log.Debugf("Installing 'mariner-release' package to a clean RPM root under '%s'.", installRoot)
rpmArgs := []string{"-i", "--root", installRoot}
rpmArgs = append(rpmArgs, rpmFiles...)
err = shell.ExecuteLive(squashErrors, "rpm", rpmArgs...)
if err != nil {
logger.Log.Errorf("Failed to prepare the RPM database on installing the 'mariner-release' package: %v", err)
return
}
return
}
func configureSystemFiles(installChroot *safechroot.Chroot, hostname string, installMap, mountPointToFsTypeMap, mountPointToMountArgsMap map[string]string, encryptedRoot diskutils.EncryptedRootDevice) (err error) {
// Update hosts file
err = updateHosts(installChroot.RootDir(), hostname)
if err != nil {
return
}
// Update fstab
err = updateFstab(installChroot.RootDir(), installMap, mountPointToFsTypeMap, mountPointToMountArgsMap)
if err != nil {
return
}
// Update crypttab
err = updateCrypttab(installChroot.RootDir(), installMap, encryptedRoot)
if err != nil {
return
}
return
}
func calculateTotalPackages(packages []string, installRoot string) (totalPackages int, err error) {
allPackageNames := make(map[string]bool)
const tdnfAssumeNoStdErr = "Error(1032) : Operation aborted.\n"
// For every package calculate what dependencies would also be installed from it.
for _, pkg := range packages {
var (
stdout string
stderr string
)
// Issue an install request but stop right before actually performing the install (assumeno)
stdout, stderr, err = shell.Execute("tdnf", "install", "--assumeno", "--nogpgcheck", pkg, "--installroot", installRoot)
if err != nil {
// tdnf aborts the process when it detects an install with --assumeno.
if stderr == tdnfAssumeNoStdErr {
err = nil
} else {
logger.Log.Error(stderr)
return
}
}
splitStdout := strings.Split(stdout, "\n")
// Search for the list of packages to be installed,
// it will be prefixed with a line "Installing:" and will
// end with an empty line.
inPackageList := false
for _, line := range splitStdout {
const (
packageListPrefix = "Installing:"
packageNameDelimiter = " "
)
const (
packageNameIndex = iota
extraInformationIndex = iota
totalPackageNameParts = iota
)
if !inPackageList {
inPackageList = strings.HasPrefix(line, packageListPrefix)
continue
} else if strings.TrimSpace(line) == "" {
break
}
// Each package to be installed will list its name, followed by a space and then various extra information
pkgSplit := strings.SplitN(line, packageNameDelimiter, totalPackageNameParts)
if len(pkgSplit) != totalPackageNameParts {
err = fmt.Errorf("unexpected TDNF package name output: %s", line)
return
}
allPackageNames[pkgSplit[packageNameIndex]] = true
}
}
totalPackages = len(allPackageNames)
logger.Log.Debugf("All packages to be installed (%d): %v", totalPackages, allPackageNames)
return
}
// addMachineID creates the /etc/machine-id file in the installChroot
func addMachineID(installChroot *safechroot.Chroot) (err error) {
// From https://www.freedesktop.org/software/systemd/man/machine-id.html:
// For operating system images which are created once and used on multiple
// machines, for example for containers or in the cloud, /etc/machine-id
// should be an empty file in the generic file system image. An ID will be
// generated during boot and saved to this file if possible.
const (
machineIDFile = "/etc/machine-id"
machineIDFilePerms = 0644
)
ReportAction("Configuring machine id")
err = installChroot.UnsafeRun(func() error {
return file.Create(machineIDFile, machineIDFilePerms)
})
return
}
func updateInitramfsForEncrypt(installChroot *safechroot.Chroot) (err error) {
err = installChroot.UnsafeRun(func() (err error) {
const (
libModDir = "/lib/modules"
dracutModules = "dm crypt crypt-gpg crypt-loop lvm"
initrdPrefix = "/boot/initrd.img-"
cryptTabPath = "/etc/crypttab"
)
initrdPattern := fmt.Sprintf("%v%v", initrdPrefix, "*")
initrdImageSlice, err := filepath.Glob(initrdPattern)
if err != nil {
logger.Log.Warnf("Unable to get initrd image: %v", err)
return
}
// Assume only one initrd image present
if len(initrdImageSlice) != 1 {
logger.Log.Warn("Unable to find one initrd image")
logger.Log.Warnf("Initrd images found: %v", initrdImageSlice)
err = fmt.Errorf("unable to find one intird image: %v", initrdImageSlice)
return
}
initrdImage := initrdImageSlice[0]
// Get the kernel version
kernel := strings.TrimPrefix(initrdImage, initrdPrefix)
// Construct list of files to install in initramfs
installFiles := fmt.Sprintf("%v %v", cryptTabPath, diskutils.DefaultKeyFilePath)
// Regenerate initramfs via Dracut
dracutArgs := []string{
"-f",
"--no-hostonly",
"--fstab",
"--kmoddir", filepath.Join(libModDir, kernel),
"--add", dracutModules,
"-I", installFiles,
initrdImage, kernel,
}
_, stderr, err := shell.Execute("dracut", dracutArgs...)
if err != nil {
logger.Log.Warnf("Unable to execute dracut: %v", stderr)
return
}
return
})
return
}
func updateFstab(installRoot string, installMap, mountPointToFsTypeMap, mountPointToMountArgsMap map[string]string) (err error) {
ReportAction("Configuring fstab")
for mountPoint, devicePath := range installMap {
if mountPoint != "" {
err = addEntryToFstab(installRoot, mountPoint, devicePath, mountPointToFsTypeMap[mountPoint], mountPointToMountArgsMap[mountPoint])
if err != nil {
return
}
}
}
return
}
func addEntryToFstab(installRoot, mountPoint, devicePath, fsType, mountArgs string) (err error) {
const (
uuidPrefix = "UUID="
fstabPath = "/etc/fstab"
rootfsMountPoint = "/"
defaultOptions = "defaults"
defaultDump = "0"
disablePass = "0"
rootPass = "1"
defaultPass = "2"
)
var options string
if mountArgs == "" {
options = defaultOptions
} else {
options = mountArgs
}
fullFstabPath := filepath.Join(installRoot, fstabPath)
// Get the block device
var device string
if diskutils.IsEncryptedDevice(devicePath) {
device = devicePath
} else {
uuid, err := GetUUID(devicePath)
if err != nil {
logger.Log.Warnf("Failed to get UUID for block device %v", devicePath)
return err
}
device = fmt.Sprintf("%v%v", uuidPrefix, uuid)
}
// Note: Rootfs should always have a pass number of 1. All other mountpoints are either 0 or 2
pass := defaultPass
if mountPoint == rootfsMountPoint {
pass = rootPass
}
// Construct fstab entry and append to fstab file
newEntry := fmt.Sprintf("%v %v %v %v %v %v\n", device, mountPoint, fsType, options, defaultDump, pass)
err = file.Append(newEntry, fullFstabPath)
if err != nil {
logger.Log.Warnf("Failed to append to fstab file")
return
}
return
}
func updateCrypttab(installRoot string, installMap map[string]string, encryptedRoot diskutils.EncryptedRootDevice) (err error) {
ReportAction("Configuring Crypttab")
for _, devicePath := range installMap {
if diskutils.IsEncryptedDevice(devicePath) {
err = addEntryToCrypttab(installRoot, devicePath, encryptedRoot)
if err != nil {
return
}
}
}
return
}
// Add an encryption mapping to crypttab
func addEntryToCrypttab(installRoot string, devicePath string, encryptedRoot diskutils.EncryptedRootDevice) (err error) {
const (
cryptTabPath = "/etc/crypttab"
Options = "luks,discard"
uuidPrefix = "UUID="
)
fullCryptTabPath := filepath.Join(installRoot, cryptTabPath)
uuid := encryptedRoot.LuksUUID
blockDevice := diskutils.GetLuksMappingName(uuid)
encryptedUUID := fmt.Sprintf("%v%v", uuidPrefix, uuid)
encryptionPassword := diskutils.DefaultKeyFilePath
// Construct crypttab entry and append crypttab file
newEntry := fmt.Sprintf("%v %v %v %v\n", blockDevice, encryptedUUID, encryptionPassword, Options)
err = file.Append(newEntry, fullCryptTabPath)
if err != nil {
logger.Log.Warnf("Failed to append crypttab")
return
}
return
}
// InstallGrubCfg installs the main grub config to the boot partition
// - installRoot is the base install directory
// - rootDevice holds the root partition
// - bootUUID is the UUID for the boot partition
// - encryptedRoot holds the encrypted root information if encrypted root is enabled
// - kernelCommandLine contains additional kernel parameters which may be optionally set
// Note: this boot partition could be different than the boot partition specified in the bootloader.
// This boot partition specifically indicates where to find the kernel, config files, and initrd
func InstallGrubCfg(installRoot, rootDevice, bootUUID string, encryptedRoot diskutils.EncryptedRootDevice, kernelCommandLine configuration.KernelCommandLine) (err error) {
const (
assetGrubcfgFile = "/installer/grub2/grub.cfg"
grubCfgFile = "boot/grub2/grub.cfg"
)
// Copy the bootloader's grub.cfg and set the file permission
installGrubCfgFile := filepath.Join(installRoot, grubCfgFile)
err = file.CopyAndChangeMode(assetGrubcfgFile, installGrubCfgFile, bootDirectoryDirMode, bootDirectoryFileMode)
if err != nil {
return
}
// Add in bootUUID
err = setGrubCfgBootUUID(bootUUID, installGrubCfgFile)
if err != nil {
logger.Log.Warnf("Failed to set bootUUID in grub.cfg: %v", err)
return
}
// Add in rootDevice
err = setGrubCfgRootDevice(rootDevice, installGrubCfgFile, encryptedRoot.LuksUUID)
if err != nil {
logger.Log.Warnf("Failed to set rootDevice in grub.cfg: %v", err)
return
}
// Add in rootLuksUUID
err = setGrubCfgLuksUUID(installGrubCfgFile, encryptedRoot.LuksUUID)
if err != nil {
logger.Log.Warnf("Failed to set luksUUID in grub.cfg: %v", err)
return
}
// Add in logical volumes to active
err = setGrubCfgLVM(installGrubCfgFile, encryptedRoot.LuksUUID)
if err != nil {
logger.Log.Warnf("Failed to set lvm.lv in grub.cfg: %v", err)
return
}
// Configure IMA policy
err = setGrubCfgIMA(installGrubCfgFile, kernelCommandLine)
if err != nil {
logger.Log.Warnf("Failed to set ima_policy in grub.cfg: %v", err)
return
}
// Append any additional command line parameters
err = setGrubCfgAdditionalCmdLine(installGrubCfgFile, kernelCommandLine)
if err != nil {
logger.Log.Warnf("Failed to append extra command line parameterse in grub.cfg: %v", err)
return
}
return
}
func updateHostname(installRoot, hostname string) (err error) {
ReportAction("Configuring hostname")
// Update the environment variables to use the new hostname.
env := append(shell.CurrentEnvironment(), fmt.Sprintf("HOSTNAME=%s", hostname))
shell.SetEnvironment(env)
hostnameFilePath := filepath.Join(installRoot, "etc/hostname")
err = file.Write(hostname, hostnameFilePath)
if err != nil {
logger.Log.Warnf("Failed to write hostname")
return
}
return
}
func updateHosts(installRoot, hostname string) (err error) {
const (
lineNumber = "6"
hostsFile = "etc/hosts"
)
ReportAction("Configuring hosts file")
newHost := fmt.Sprintf("127.0.0.1 %v", hostname)
hostsFilePath := filepath.Join(installRoot, hostsFile)
err = sedInsert(lineNumber, newHost, hostsFilePath)
if err != nil {
logger.Log.Warnf("Failed to write hosts file")
return
}
return
}
func addGroups(installChroot *safechroot.Chroot, groups []configuration.Group) (err error) {
const squashErrors = false
for _, group := range groups {
logger.Log.Infof("Adding group (%s)", group.Name)
ReportActionf("Adding group: %s", group.Name)
var args = []string{group.Name}
if group.GID != "" {
args = append(args, "-g", group.GID)
}
err = installChroot.UnsafeRun(func() error {
return shell.ExecuteLive(squashErrors, "groupadd", args...)
})
}
return
}
func addUsers(installChroot *safechroot.Chroot, users []configuration.User) (err error) {
const (
squashErrors = false
)
rootUserAdded := false
for _, user := range users {
logger.Log.Infof("Adding user (%s)", user.Name)
ReportActionf("Adding user: %s", user.Name)
var (
homeDir string
isRoot bool
)
homeDir, isRoot, err = createUserWithPassword(installChroot, user)
if err != nil {
return
}
if isRoot {
rootUserAdded = true
}
err = configureUserGroupMembership(installChroot, user)
if err != nil {
return
}
err = provisionUserSSHCerts(installChroot, user, homeDir)
if err != nil {
return
}
err = configureUserStartupCommand(installChroot, user)
if err != nil {
return
}
}
// If no root entry was specified in the config file, never expire the root password
if !rootUserAdded {
logger.Log.Debugf("No root user entry found in config file. Setting root password to never expire.")
err = installChroot.UnsafeRun(func() error {
return shell.ExecuteLive(squashErrors, "chage", "-M", "-1", "root")
})
}
return
}
func createUserWithPassword(installChroot *safechroot.Chroot, user configuration.User) (homeDir string, isRoot bool, err error) {
const (
squashErrors = false
rootHomeDir = "/root"
userHomeDirPrefix = "/home"
passwordExpiresBase = 10
postfixLength = 12
alphaNumeric = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
var (
hashedPassword string
stdout string
stderr string
salt string
)
// Get the hashed password for the user
if user.PasswordHashed {
hashedPassword = user.Password
} else {
salt, err = randomString(postfixLength, alphaNumeric)
if err != nil {
return
}
// Generate hashed password based on salt value provided.
// -6 option indicates to use the SHA256/SHA512 algorithm
stdout, stderr, err = shell.Execute("openssl", "passwd", "-6", "-salt", salt, user.Password)
if err != nil {
logger.Log.Warnf("Failed to generate hashed password")
logger.Log.Warn(stderr)
return
}
hashedPassword = strings.TrimSpace(stdout)
}
logger.Log.Tracef("hashed password: %v", hashedPassword)
if strings.TrimSpace(hashedPassword) == "" {
err = fmt.Errorf("empty password for user (%s) is not allowed", user.Name)
return
}
// Create the user with the given hashed password
if user.Name == rootUser {
homeDir = rootHomeDir
if user.UID != "" {
logger.Log.Warnf("Ignoring UID for (%s) user, using default", rootUser)
}
// Update shadow file
err = updateUserPassword(installChroot.RootDir(), user.Name, hashedPassword)
isRoot = true
} else {
homeDir = filepath.Join(userHomeDirPrefix, user.Name)
var args = []string{user.Name, "-m", "-p", hashedPassword}
if user.UID != "" {
args = append(args, "-u", user.UID)
}
err = installChroot.UnsafeRun(func() error {
return shell.ExecuteLive(squashErrors, "useradd", args...)
})
}
if err != nil {
return
}
// Update password expiration
if user.PasswordExpiresDays != 0 {
err = installChroot.UnsafeRun(func() error {
return shell.ExecuteLive(squashErrors, "chage", "-M", strconv.FormatUint(user.PasswordExpiresDays, passwordExpiresBase), user.Name)
})
}
return
}
func configureUserGroupMembership(installChroot *safechroot.Chroot, user configuration.User) (err error) {
const squashErrors = false
// Update primary group
if user.PrimaryGroup != "" {
err = installChroot.UnsafeRun(func() error {
return shell.ExecuteLive(squashErrors, "usermod", "-g", user.PrimaryGroup, user.Name)
})
if err != nil {
return
}
}
// Update secondary groups
if len(user.SecondaryGroups) != 0 {
allGroups := strings.Join(user.SecondaryGroups, ",")
err = installChroot.UnsafeRun(func() error {
return shell.ExecuteLive(squashErrors, "usermod", "-a", "-G", allGroups, user.Name)
})
if err != nil {
return
}
}
return
}
func configureUserStartupCommand(installChroot *safechroot.Chroot, user configuration.User) (err error) {
const (
passwdFilePath = "etc/passwd"
sedDelimiter = "|"
)
if user.StartupCommand == "" {
return
}
logger.Log.Debugf("Updating user '%s' startup command to '%s'.", user.Name, user.StartupCommand)
findPattern := fmt.Sprintf(`^\(%s.*\):[^:]*$`, user.Name)
replacePattern := fmt.Sprintf(`\1:%s`, user.StartupCommand)
filePath := filepath.Join(installChroot.RootDir(), passwdFilePath)
err = sed(findPattern, replacePattern, sedDelimiter, filePath)
if err != nil {
logger.Log.Errorf("Failed to update user's startup command.")
return
}
return
}
func provisionUserSSHCerts(installChroot *safechroot.Chroot, user configuration.User, homeDir string) (err error) {
const squashErrors = false
userSSHKeyDir := filepath.Join(homeDir, ".ssh")
for _, pubKey := range user.SSHPubKeyPaths {
logger.Log.Infof("Adding ssh key (%s) to user (%s)", filepath.Base(pubKey), user.Name)
relativeDst := filepath.Join(userSSHKeyDir, filepath.Base(pubKey))
fileToCopy := safechroot.FileToCopy{
Src: pubKey,
Dest: relativeDst,
}
err = installChroot.AddFiles(fileToCopy)
if err != nil {
return
}
}
if len(user.SSHPubKeyPaths) != 0 {
const sshDirectoryPermission = "0700"
// Change ownership of the folder to belong to the user and their primary group
err = installChroot.UnsafeRun(func() (err error) {
// Find the primary group of the user
stdout, stderr, err := shell.Execute("id", "-g", user.Name)
if err != nil {
logger.Log.Warnf(stderr)
return
}
primaryGroup := strings.TrimSpace(stdout)
logger.Log.Debugf("Primary group for user (%s) is (%s)", user.Name, primaryGroup)
ownership := fmt.Sprintf("%s:%s", user.Name, primaryGroup)
err = shell.ExecuteLive(squashErrors, "chown", "-R", ownership, userSSHKeyDir)
if err != nil {
return
}
err = shell.ExecuteLive(squashErrors, "chmod", "-R", sshDirectoryPermission, userSSHKeyDir)
return
})
if err != nil {
return
}
}
return
}
func updateUserPassword(installRoot, username, password string) (err error) {
const (
shadowFilePath = "etc/shadow"
sedDelimiter = "|"
)
findPattern := fmt.Sprintf("%v:x:", username)
replacePattern := fmt.Sprintf("%v:%v:", username, password)
filePath := filepath.Join(installRoot, shadowFilePath)
err = sed(findPattern, replacePattern, sedDelimiter, filePath)
if err != nil {
logger.Log.Warnf("Failed to write hashed password to shadow file")
return
}
return
}
func tdnfInstall(packageName, installRoot string, currentPackagesInstalled, totalPackages int) (packagesInstalled int, err error) {
packagesInstalled = currentPackagesInstalled
onStdout := func(args ...interface{}) {
const tdnfInstallPrefix = "Installing/Updating: "
// Only process lines that match tdnfInstallPrefix
if len(args) == 0 {
return
}
line := args[0].(string)
if !strings.HasPrefix(line, tdnfInstallPrefix) {
return
}
status := fmt.Sprintf("Installing: %s", strings.TrimPrefix(line, tdnfInstallPrefix))
ReportAction(status)
packagesInstalled++
// Calculate and report what percentage of packages have been installed
percentOfPackagesInstalled := float32(packagesInstalled) / float32(totalPackages)
progress := int(percentOfPackagesInstalled * 100)
ReportPercentComplete(progress)
}
err = shell.ExecuteLiveWithCallback(onStdout, logger.Log.Warn, "tdnf", "install", packageName, "--installroot", installRoot, "--nogpgcheck", "--assumeyes")
if err != nil {
logger.Log.Warnf("Failed to tdnf install: %v. Package name: %v", err, packageName)
}
return
}
func sed(find, replace, delimiter, file string) (err error) {
const squashErrors = false
replacement := fmt.Sprintf("s%s%s%s%s%s", delimiter, find, delimiter, replace, delimiter)
return shell.ExecuteLive(squashErrors, "sed", "-i", replacement, file)
}
func sedInsert(line, replace, file string) (err error) {
const squashErrors = false
insertAtLine := fmt.Sprintf("%si%s", line, replace)
return shell.ExecuteLive(squashErrors, "sed", "-i", insertAtLine, file)
}
func getPackagesFromJSON(file string) (pkgList PackageList, err error) {
err = jsonutils.ReadJSONFile(file, &pkgList)
if err != nil {
logger.Log.Warnf("Could not read JSON file: %v", err)
return
}
return
}
// InstallBootloader installs the proper bootloader for this type of image
// - installChroot is a pointer to the install Chroot object
// - bootType indicates the type of boot loader to add.
// - bootUUID is the UUID of the boot partition
// Note: this boot partition could be different than the boot partition specified in the main grub config.
// This boot partition specifically indicates where to find the main grub cfg
func InstallBootloader(installChroot *safechroot.Chroot, encryptEnabled bool, bootType, bootUUID, bootDevPath string) (err error) {
const (
efiMountPoint = "/boot/efi"
efiBootType = "efi"
legacyBootType = "legacy"
noneBootType = "none"
)
ReportAction("Configuring bootloader")
switch bootType {
case legacyBootType:
err = installLegacyBootloader(installChroot, bootDevPath)
if err != nil {
return
}
case efiBootType:
efiPath := filepath.Join(installChroot.RootDir(), efiMountPoint)
err = installEfiBootloader(encryptEnabled, efiPath, bootUUID)
if err != nil {
return
}
case noneBootType:
// Nothing to do here
default:
err = fmt.Errorf("unknown boot type: %v", bootType)
return
}
return
}
// Note: We assume that the /boot directory is present. Whether it is backed by an explicit "boot" partition or present
// as part of a general "root" partition is assumed to have been done already.
func installLegacyBootloader(installChroot *safechroot.Chroot, bootDevPath string) (err error) {
const (
squashErrors = false
)
// Since we do not have grub2-pc installed in the setup environment, we need to generate the legacy grub bootloader
// inside of the install environment. This assumes the install environment has the grub2-pc package installed
err = installChroot.UnsafeRun(func() (err error) {
err = shell.ExecuteLive(squashErrors, "grub2-install", "--target=i386-pc", "--boot-directory=/boot", bootDevPath)
err = shell.ExecuteLive(squashErrors, "chmod", "-R", "go-rwx", "/boot/grub2/")
return
})
return
}
// EnableCryptoDisk enables Grub to boot from an encrypted disk
// - installChroot is the installation chroot
func EnableCryptoDisk(installChroot *safechroot.Chroot) (err error) {
const (
grubPath = "/etc/default/grub"
grubCryptoDisk = "GRUB_ENABLE_CRYPTODISK=y\n"
grubPreloadModules = `GRUB_PRELOAD_MODULES="lvm"`
)
err = installChroot.UnsafeRun(func() error {
err := file.Append(grubCryptoDisk, grubPath)
if err != nil {
logger.Log.Warnf("Failed to add grub cryptodisk: %v", err)
return err
}
err = file.Append(grubPreloadModules, grubPath)
if err != nil {
logger.Log.Warnf("Failed to add grub preload modules: %v", err)
return err
}
return err
})
return
}
// GetUUID queries the UUID of the given partition
// - device is the device path of the desired partition
func GetUUID(device string) (stdout string, err error) {
stdout, _, err = shell.Execute("blkid", device, "-s", "UUID", "-o", "value")
if err != nil {
return
}
logger.Log.Trace(stdout)
stdout = strings.TrimSpace(stdout)
return
}
// GetPartUUID queries the PARTUUID of the given partition
// - device is the device path of the desired partition
func GetPartUUID(device string) (stdout string, err error) {
stdout, _, err = shell.Execute("blkid", device, "-s", "PARTUUID", "-o", "value")
if err != nil {
return
}
logger.Log.Trace(stdout)
stdout = strings.TrimSpace(stdout)
return
}
// installEfi copies the efi binaries and grub configuration to the appropriate
// installRoot/boot/efi folder
// It is expected that shim (bootx64.efi) and grub2 (grub2.efi) are installed
// into the EFI directory via the package list installation mechanism.
func installEfiBootloader(encryptEnabled bool, installRoot, bootUUID string) (err error) {
const (
defaultCfgFilename = "grub.cfg"
encryptCfgFilename = "grubEncrypt.cfg"
efiAssetDir = "/installer/efi/x86_64"
grubAssetDir = "/installer/efi/grub"
efiFinalDir = "EFI/BOOT"
grubFinalDir = "boot/grub2"
)
// Copy the bootloader's grub.cfg
grubAssetPath := filepath.Join(grubAssetDir, defaultCfgFilename)
if encryptEnabled {
grubAssetPath = filepath.Join(grubAssetDir, encryptCfgFilename)
}
grubFinalPath := filepath.Join(installRoot, grubFinalDir, defaultCfgFilename)
err = file.CopyAndChangeMode(grubAssetPath, grubFinalPath, bootDirectoryDirMode, bootDirectoryFileMode)
if err != nil {
logger.Log.Warnf("Failed to copy grub.cfg: %v", err)
return
}
// Add in bootUUID
err = setGrubCfgBootUUID(bootUUID, grubFinalPath)
if err != nil {
logger.Log.Warnf("Failed to set bootUUID in grub.cfg: %v", err)
return
}
// Add in encrypted volume
if encryptEnabled {
err = setGrubCfgEncryptedVolume(grubFinalPath)
if err != nil {
logger.Log.Warnf("Failed to set encrypted volume in grub.cfg: %v", err)
return
}
}
return
}
func copyAdditionalFiles(installChroot *safechroot.Chroot, config configuration.SystemConfig) (err error) {
ReportAction("Copying additional files")
for srcFile, dstFile := range config.AdditionalFiles {
fileToCopy := safechroot.FileToCopy{
Src: srcFile,
Dest: dstFile,
}
err = installChroot.AddFiles(fileToCopy)
if err != nil {
return
}
}
return
}
func runPostInstallScripts(installChroot *safechroot.Chroot, config configuration.SystemConfig) (err error) {
const squashErrors = false
for _, script := range config.PostInstallScripts {
// Copy the script from this chroot into the install chroot before running it
scriptPath := script.Path
fileToCopy := safechroot.FileToCopy{
Src: scriptPath,
Dest: scriptPath,
}
installChroot.AddFiles(fileToCopy)
if err != nil {
return
}
ReportActionf("Running post-install script: %s", path.Base(script.Path))
logger.Log.Infof("Running post-install script: %s", script.Path)
err = installChroot.UnsafeRun(func() error {
err := shell.ExecuteLive(squashErrors, shell.ShellProgram, "-c", scriptPath, script.Args)
if err != nil {
return err
}
err = os.Remove(scriptPath)
if err != nil {
logger.Log.Errorf("Failed to cleanup post-install script (%s). Error: %s", scriptPath, err)
}
return err
})
if err != nil {
return
}
}
return
}
func setGrubCfgAdditionalCmdLine(grubPath string, kernelCommandline configuration.KernelCommandLine) (err error) {
const (
extraPattern = "{{.ExtraCommandLine}}"
)
logger.Log.Debugf("Adding ExtraCommandLine('%s') to %s", kernelCommandline.ExtraCommandLine, grubPath)
err = sed(extraPattern, kernelCommandline.ExtraCommandLine, kernelCommandline.GetSedDelimeter(), grubPath)
if err != nil {
logger.Log.Warnf("Failed to append extra paramters to grub.cfg: %v", err)
}
return
}
func setGrubCfgIMA(grubPath string, kernelCommandline configuration.KernelCommandLine) (err error) {
const (
imaPrefix = "ima_policy="
imaPattern = "{{.IMAPolicy}}"
)
var ima string
for _, policy := range kernelCommandline.ImaPolicy {
ima += fmt.Sprintf("%v%v ", imaPrefix, policy)
}
logger.Log.Debugf("Adding ImaPolicy('%s') to %s", ima, grubPath)
err = sed(imaPattern, ima, kernelCommandline.GetSedDelimeter(), grubPath)
if err != nil {
logger.Log.Warnf("Failed to set grub.cfg's IMA setting: %v", err)
}
return
}
func setGrubCfgLVM(grubPath, luksUUID string) (err error) {
const (
lvmPrefix = "rd.lvm.lv="
lvmPattern = "{{.LVM}}"
)
var cmdline configuration.KernelCommandLine
var lvm string
if luksUUID != "" {
lvm = fmt.Sprintf("%v%v", lvmPrefix, diskutils.GetEncryptedRootVolPath())
}
logger.Log.Debugf("Adding lvm('%s') to %s", lvm, grubPath)
err = sed(lvmPattern, lvm, cmdline.GetSedDelimeter(), grubPath)
if err != nil {
logger.Log.Warnf("Failed to set grub.cfg's LVM setting: %v", err)
}
return
}
func setGrubCfgLuksUUID(grubPath, uuid string) (err error) {
const (
luksUUIDPrefix = "luks.uuid="
luksUUIDPattern = "{{.LuksUUID}}"
)
var (
cmdline configuration.KernelCommandLine
luksUUID string
)
if uuid != "" {
luksUUID = fmt.Sprintf("%v%v", luksUUIDPrefix, uuid)
}
logger.Log.Debugf("Adding luks('%s') to %s", luksUUID, grubPath)
err = sed(luksUUIDPattern, luksUUID, cmdline.GetSedDelimeter(), grubPath)
if err != nil {
logger.Log.Warnf("Failed to set grub.cfg's luksUUID: %v", err)
return
}
return
}
func setGrubCfgBootUUID(bootUUID, grubPath string) (err error) {
const (
bootUUIDPattern = "{{.BootUUID}}"
)
var cmdline configuration.KernelCommandLine
logger.Log.Debugf("Adding UUID('%s') to %s", bootUUID, grubPath)
err = sed(bootUUIDPattern, bootUUID, cmdline.GetSedDelimeter(), grubPath)
if err != nil {
logger.Log.Warnf("Failed to set grub.cfg's bootUUID: %v", err)
return
}
return
}
func setGrubCfgEncryptedVolume(grubPath string) (err error) {
const (
encryptedVolPattern = "{{.EncryptedVolume}}"
lvmPrefix = "lvm/"
)
var cmdline configuration.KernelCommandLine
encryptedVol := fmt.Sprintf("%v%v%v%v", "(", lvmPrefix, diskutils.GetEncryptedRootVol(), ")")
logger.Log.Debugf("Adding EncryptedVolume('%s') to %s", encryptedVol, grubPath)
err = sed(encryptedVolPattern, encryptedVol, cmdline.GetSedDelimeter(), grubPath)
if err != nil {
logger.Log.Warnf("Failed to grub.cfg's encryptedVolume: %v", err)
return
}
return
}
func setGrubCfgRootDevice(rootDevice, grubPath, luksUUID string) (err error) {
const (
rootDevicePattern = "{{.RootPartition}}"
)
var cmdline configuration.KernelCommandLine
if luksUUID != "" {
rootDevice = diskutils.GetEncryptedRootVolMapping()
}
logger.Log.Debugf("Adding RootDevice('%s') to %s", rootDevice, grubPath)
err = sed(rootDevicePattern, rootDevice, cmdline.GetSedDelimeter(), grubPath)
if err != nil {
logger.Log.Warnf("Failed to set grub.cfg's rootDevice: %v", err)
return
}
return
}
// ExtractPartitionArtifacts scans through the SystemConfig and generates all the partition-based artifacts specified.
// - workDirPath is the directory to place the artifacts
// - partIDToDevPathMap is a map of partition IDs to partition device paths
func ExtractPartitionArtifacts(workDirPath string, diskIndex int, disk configuration.Disk, partIDToDevPathMap map[string]string) (err error) {
const (
ext4ArtifactType = "ext4"
)
// Scan each partition for Artifacts
for i, partition := range disk.Partitions {
for _, artifact := range partition.Artifacts {
if artifact.Type == ext4ArtifactType {
devPath := partIDToDevPathMap[partition.ID]
// Ext4 artifact type output is a .raw of the partition
finalName := fmt.Sprintf("disk%d.partition%d.raw", diskIndex, i)
err = createRawArtifact(workDirPath, devPath, finalName)
if err != nil {
return err
}
}
}
}
return
}
func createRawArtifact(workDirPath, devPath, name string) (err error) {
const (
defaultBlockSize = 1024 * 1024 // 1MB
squashErrors = true
)
fullPath := filepath.Join(workDirPath, name)
ddArgs := []string{
fmt.Sprintf("if=%s", devPath), // Input file.
fmt.Sprintf("of=%s", fullPath), // Output file.
fmt.Sprintf("bs=%d", defaultBlockSize), // Size of one copied block.
}
return shell.ExecuteLive(squashErrors, "dd", ddArgs...)
}
// randomString generates a random string of the length specified
// using the provided legalCharacters. crypto.rand is more secure
// than math.rand and does not need to be seeded.
func randomString(length int, legalCharacters string) (output string, err error) {
b := make([]byte, length)
_, err = rand.Read(b)
if err != nil {
return
}
count := byte(len(legalCharacters))
for i := range b {
idx := b[i] % count
b[i] = legalCharacters[idx]
}
output = string(b)
return
}
// isRunningInHyperV checks if the program is running in a Hyper-V Virtual Machine.
func isRunningInHyperV() (isHyperV bool, err error) {
const (
dmesgHypervTag = "Hyper-V"
)
stdout, stderr, err := shell.Execute("dmesg")
if err != nil {
logger.Log.Warnf("stderr: %v", stderr)
return
}
logger.Log.Debugf("dmesg system: %s", stdout)
// dmesg will print information about Hyper-V if it detects that Hyper-V is the hypervisor.
// There will be multiple mentions of Hyper-V in the output (entry for BIOS as well as hypervisor)
// and diagnostic information about hypervisor version.
// Outside of Hyper-V, this name will not be reported.
if strings.Contains(stdout, dmesgHypervTag) {
logger.Log.Infof("Detected Hyper-V Host")
isHyperV = true
}
return
}
//KernelPackages returns a list of kernel packages obtained from KernelOptions in the config's SystemConfigs
func KernelPackages(config configuration.Config) []*pkgjson.PackageVer {
var packageList []*pkgjson.PackageVer
// Add all the provided kernels to the package list
for _, cfg := range config.SystemConfigs {
for name, kernelPath := range cfg.KernelOptions {
// Ignore comments
if name[0] == '_' {
continue
}
kernelName := filepath.Base(kernelPath)
logger.Log.Tracef("Processing kernel %s derived from %s (required for option %s)", kernelName, kernelPath, name)
packageList = append(packageList, &pkgjson.PackageVer{Name: kernelName})
}
}
return packageList
}
// stopGPGAgent stops gpg-agent if it is running inside the installChroot.
//
// It is possible that one of the packages or post-install scripts started a GPG agent.
// e.g. when installing the mariner-repos SPEC, a GPG import occurs. This starts the gpg-agent process inside the chroot.
// To be able to cleanly exit the setup chroot, we must stop it.
func stopGPGAgent(installChroot *safechroot.Chroot) {
installChroot.UnsafeRun(func() error {
err := shell.ExecuteLiveWithCallback(logger.Log.Debug, logger.Log.Warn, "gpgconf", "--kill", "gpg-agent")
if err != nil {
// This is non-fatal, as there is no guarentee the image has gpg agent started.
logger.Log.Warnf("Failed to stop gpg-agent. This is expected if it is not installed: %s", err)
}
return nil
})
}
| 1 | 12,840 | `RpmDependenciesDirectory` should start with a lowercase character so it's not exported outside of this package, it looks like its only referenced in this file. | microsoft-CBL-Mariner | go |
@@ -25,9 +25,13 @@ class BasicBlock(nn.Module):
conv_cfg=None,
norm_cfg=dict(type='BN'),
dcn=None,
+ rfp_inplanes=None,
+ sac=None,
plugins=None):
super(BasicBlock, self).__init__()
assert dcn is None, 'Not implemented yet.'
+ assert rfp_inplanes is None, 'Not implemented yet.'
+ assert sac is None, 'Not implemented yet.'
assert plugins is None, 'Not implemented yet.'
self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1) | 1 | import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init,
kaiming_init)
from mmcv.runner import load_checkpoint
from torch.nn.modules.batchnorm import _BatchNorm
from mmdet.ops import build_plugin_layer
from mmdet.utils import get_root_logger
from ..builder import BACKBONES
from ..utils import ResLayer
class BasicBlock(nn.Module):
expansion = 1
def __init__(self,
inplanes,
planes,
stride=1,
dilation=1,
downsample=None,
style='pytorch',
with_cp=False,
conv_cfg=None,
norm_cfg=dict(type='BN'),
dcn=None,
plugins=None):
super(BasicBlock, self).__init__()
assert dcn is None, 'Not implemented yet.'
assert plugins is None, 'Not implemented yet.'
self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1)
self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2)
self.conv1 = build_conv_layer(
conv_cfg,
inplanes,
planes,
3,
stride=stride,
padding=dilation,
dilation=dilation,
bias=False)
self.add_module(self.norm1_name, norm1)
self.conv2 = build_conv_layer(
conv_cfg, planes, planes, 3, padding=1, bias=False)
self.add_module(self.norm2_name, norm2)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.dilation = dilation
self.with_cp = with_cp
@property
def norm1(self):
return getattr(self, self.norm1_name)
@property
def norm2(self):
return getattr(self, self.norm2_name)
def forward(self, x):
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.norm2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self,
inplanes,
planes,
stride=1,
dilation=1,
downsample=None,
style='pytorch',
with_cp=False,
conv_cfg=None,
norm_cfg=dict(type='BN'),
dcn=None,
plugins=None):
"""Bottleneck block for ResNet.
If style is "pytorch", the stride-two layer is the 3x3 conv layer,
if it is "caffe", the stride-two layer is the first 1x1 conv layer.
"""
super(Bottleneck, self).__init__()
assert style in ['pytorch', 'caffe']
assert dcn is None or isinstance(dcn, dict)
assert plugins is None or isinstance(plugins, list)
if plugins is not None:
allowed_position = ['after_conv1', 'after_conv2', 'after_conv3']
assert all(p['position'] in allowed_position for p in plugins)
self.inplanes = inplanes
self.planes = planes
self.stride = stride
self.dilation = dilation
self.style = style
self.with_cp = with_cp
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.dcn = dcn
self.with_dcn = dcn is not None
self.plugins = plugins
self.with_plugins = plugins is not None
if self.with_plugins:
# collect plugins for conv1/conv2/conv3
self.after_conv1_plugins = [
plugin['cfg'] for plugin in plugins
if plugin['position'] == 'after_conv1'
]
self.after_conv2_plugins = [
plugin['cfg'] for plugin in plugins
if plugin['position'] == 'after_conv2'
]
self.after_conv3_plugins = [
plugin['cfg'] for plugin in plugins
if plugin['position'] == 'after_conv3'
]
if self.style == 'pytorch':
self.conv1_stride = 1
self.conv2_stride = stride
else:
self.conv1_stride = stride
self.conv2_stride = 1
self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1)
self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2)
self.norm3_name, norm3 = build_norm_layer(
norm_cfg, planes * self.expansion, postfix=3)
self.conv1 = build_conv_layer(
conv_cfg,
inplanes,
planes,
kernel_size=1,
stride=self.conv1_stride,
bias=False)
self.add_module(self.norm1_name, norm1)
fallback_on_stride = False
if self.with_dcn:
fallback_on_stride = dcn.pop('fallback_on_stride', False)
if not self.with_dcn or fallback_on_stride:
self.conv2 = build_conv_layer(
conv_cfg,
planes,
planes,
kernel_size=3,
stride=self.conv2_stride,
padding=dilation,
dilation=dilation,
bias=False)
else:
assert self.conv_cfg is None, 'conv_cfg must be None for DCN'
self.conv2 = build_conv_layer(
dcn,
planes,
planes,
kernel_size=3,
stride=self.conv2_stride,
padding=dilation,
dilation=dilation,
bias=False)
self.add_module(self.norm2_name, norm2)
self.conv3 = build_conv_layer(
conv_cfg,
planes,
planes * self.expansion,
kernel_size=1,
bias=False)
self.add_module(self.norm3_name, norm3)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
if self.with_plugins:
self.after_conv1_plugin_names = self.make_block_plugins(
planes, self.after_conv1_plugins)
self.after_conv2_plugin_names = self.make_block_plugins(
planes, self.after_conv2_plugins)
self.after_conv3_plugin_names = self.make_block_plugins(
planes * self.expansion, self.after_conv3_plugins)
def make_block_plugins(self, in_channels, plugins):
""" make plugins for block
Args:
in_channels (int): Input channels of plugin.
plugins (list[dict]): List of plugins cfg to build.
Returns:
list[str]: List of the names of plugin.
"""
assert isinstance(plugins, list)
plugin_names = []
for plugin in plugins:
plugin = plugin.copy()
name, layer = build_plugin_layer(
plugin,
in_channels=in_channels,
postfix=plugin.pop('postfix', ''))
assert not hasattr(self, name), f'duplicate plugin {name}'
self.add_module(name, layer)
plugin_names.append(name)
return plugin_names
def forward_plugin(self, x, plugin_names):
out = x
for name in plugin_names:
out = getattr(self, name)(x)
return out
@property
def norm1(self):
return getattr(self, self.norm1_name)
@property
def norm2(self):
return getattr(self, self.norm2_name)
@property
def norm3(self):
return getattr(self, self.norm3_name)
def forward(self, x):
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu(out)
if self.with_plugins:
out = self.forward_plugin(out, self.after_conv1_plugin_names)
out = self.conv2(out)
out = self.norm2(out)
out = self.relu(out)
if self.with_plugins:
out = self.forward_plugin(out, self.after_conv2_plugin_names)
out = self.conv3(out)
out = self.norm3(out)
if self.with_plugins:
out = self.forward_plugin(out, self.after_conv3_plugin_names)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
return out
@BACKBONES.register_module()
class ResNet(nn.Module):
"""ResNet backbone.
Args:
depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.
stem_channels (int): Number of stem channels. Default: 64.
base_channels (int): Number of base channels of res layer. Default: 64.
in_channels (int): Number of input image channels. Default: 3.
num_stages (int): Resnet stages. Default: 4.
strides (Sequence[int]): Strides of the first block of each stage.
dilations (Sequence[int]): Dilation of each stage.
out_indices (Sequence[int]): Output from which stages.
style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
layer is the 3x3 conv layer, otherwise the stride-two layer is
the first 1x1 conv layer.
deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv
avg_down (bool): Use AvgPool instead of stride conv when
downsampling in the bottleneck.
frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
-1 means not freezing any parameters.
norm_cfg (dict): Dictionary to construct and config norm layer.
norm_eval (bool): Whether to set norm layers to eval mode, namely,
freeze running stats (mean and var). Note: Effect on Batch Norm
and its variants only.
plugins (list[dict]): List of plugins for stages, each dict contains:
- cfg (dict, required): Cfg dict to build plugin.
- position (str, required): Position inside block to insert
plugin, options are 'after_conv1', 'after_conv2', 'after_conv3'.
- stages (tuple[bool], optional): Stages to apply plugin, length
should be same as 'num_stages'.
with_cp (bool): Use checkpoint or not. Using checkpoint will save some
memory while slowing down the training speed.
zero_init_residual (bool): Whether to use zero init for last norm layer
in resblocks to let them behave as identity.
Example:
>>> from mmdet.models import ResNet
>>> import torch
>>> self = ResNet(depth=18)
>>> self.eval()
>>> inputs = torch.rand(1, 3, 32, 32)
>>> level_outputs = self.forward(inputs)
>>> for level_out in level_outputs:
... print(tuple(level_out.shape))
(1, 64, 8, 8)
(1, 128, 4, 4)
(1, 256, 2, 2)
(1, 512, 1, 1)
"""
arch_settings = {
18: (BasicBlock, (2, 2, 2, 2)),
34: (BasicBlock, (3, 4, 6, 3)),
50: (Bottleneck, (3, 4, 6, 3)),
101: (Bottleneck, (3, 4, 23, 3)),
152: (Bottleneck, (3, 8, 36, 3))
}
def __init__(self,
depth,
in_channels=3,
stem_channels=64,
base_channels=64,
num_stages=4,
strides=(1, 2, 2, 2),
dilations=(1, 1, 1, 1),
out_indices=(0, 1, 2, 3),
style='pytorch',
deep_stem=False,
avg_down=False,
frozen_stages=-1,
conv_cfg=None,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
dcn=None,
stage_with_dcn=(False, False, False, False),
plugins=None,
with_cp=False,
zero_init_residual=True):
super(ResNet, self).__init__()
if depth not in self.arch_settings:
raise KeyError(f'invalid depth {depth} for resnet')
self.depth = depth
self.stem_channels = stem_channels
self.base_channels = base_channels
self.num_stages = num_stages
assert num_stages >= 1 and num_stages <= 4
self.strides = strides
self.dilations = dilations
assert len(strides) == len(dilations) == num_stages
self.out_indices = out_indices
assert max(out_indices) < num_stages
self.style = style
self.deep_stem = deep_stem
self.avg_down = avg_down
self.frozen_stages = frozen_stages
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.with_cp = with_cp
self.norm_eval = norm_eval
self.dcn = dcn
self.stage_with_dcn = stage_with_dcn
if dcn is not None:
assert len(stage_with_dcn) == num_stages
self.plugins = plugins
self.zero_init_residual = zero_init_residual
self.block, stage_blocks = self.arch_settings[depth]
self.stage_blocks = stage_blocks[:num_stages]
self.inplanes = stem_channels
self._make_stem_layer(in_channels, stem_channels)
self.res_layers = []
for i, num_blocks in enumerate(self.stage_blocks):
stride = strides[i]
dilation = dilations[i]
dcn = self.dcn if self.stage_with_dcn[i] else None
if plugins is not None:
stage_plugins = self.make_stage_plugins(plugins, i)
else:
stage_plugins = None
planes = base_channels * 2**i
res_layer = self.make_res_layer(
block=self.block,
inplanes=self.inplanes,
planes=planes,
num_blocks=num_blocks,
stride=stride,
dilation=dilation,
style=self.style,
avg_down=self.avg_down,
with_cp=with_cp,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
dcn=dcn,
plugins=stage_plugins)
self.inplanes = planes * self.block.expansion
layer_name = f'layer{i + 1}'
self.add_module(layer_name, res_layer)
self.res_layers.append(layer_name)
self._freeze_stages()
self.feat_dim = self.block.expansion * base_channels * 2**(
len(self.stage_blocks) - 1)
def make_stage_plugins(self, plugins, stage_idx):
""" make plugins for ResNet 'stage_idx'th stage .
Currently we support to insert 'context_block',
'empirical_attention_block', 'nonlocal_block' into the backbone like
ResNet/ResNeXt. They could be inserted after conv1/conv2/conv3 of
Bottleneck.
An example of plugins format could be:
>>> plugins=[
... dict(cfg=dict(type='xxx', arg1='xxx'),
... stages=(False, True, True, True),
... position='after_conv2'),
... dict(cfg=dict(type='yyy'),
... stages=(True, True, True, True),
... position='after_conv3'),
... dict(cfg=dict(type='zzz', postfix='1'),
... stages=(True, True, True, True),
... position='after_conv3'),
... dict(cfg=dict(type='zzz', postfix='2'),
... stages=(True, True, True, True),
... position='after_conv3')
... ]
>>> self = ResNet(depth=18)
>>> stage_plugins = self.make_stage_plugins(plugins, 0)
>>> assert len(stage_plugins) == 3
Suppose 'stage_idx=0', the structure of blocks in the stage would be:
.. code-block:: none
conv1-> conv2->conv3->yyy->zzz1->zzz2
Suppose 'stage_idx=1', the structure of blocks in the stage would be:
.. code-block:: none
conv1-> conv2->xxx->conv3->yyy->zzz1->zzz2
If stages is missing, the plugin would be applied to all stages.
Args:
plugins (list[dict]): List of plugins cfg to build. The postfix is
required if multiple same type plugins are inserted.
stage_idx (int): Index of stage to build
Returns:
list[dict]: Plugins for current stage
"""
stage_plugins = []
for plugin in plugins:
plugin = plugin.copy()
stages = plugin.pop('stages', None)
assert stages is None or len(stages) == self.num_stages
# whether to insert plugin into current stage
if stages is None or stages[stage_idx]:
stage_plugins.append(plugin)
return stage_plugins
def make_res_layer(self, **kwargs):
return ResLayer(**kwargs)
@property
def norm1(self):
return getattr(self, self.norm1_name)
def _make_stem_layer(self, in_channels, stem_channels):
if self.deep_stem:
self.stem = nn.Sequential(
build_conv_layer(
self.conv_cfg,
in_channels,
stem_channels // 2,
kernel_size=3,
stride=2,
padding=1,
bias=False),
build_norm_layer(self.norm_cfg, stem_channels // 2)[1],
nn.ReLU(inplace=True),
build_conv_layer(
self.conv_cfg,
stem_channels // 2,
stem_channels // 2,
kernel_size=3,
stride=1,
padding=1,
bias=False),
build_norm_layer(self.norm_cfg, stem_channels // 2)[1],
nn.ReLU(inplace=True),
build_conv_layer(
self.conv_cfg,
stem_channels // 2,
stem_channels,
kernel_size=3,
stride=1,
padding=1,
bias=False),
build_norm_layer(self.norm_cfg, stem_channels)[1],
nn.ReLU(inplace=True))
else:
self.conv1 = build_conv_layer(
self.conv_cfg,
in_channels,
stem_channels,
kernel_size=7,
stride=2,
padding=3,
bias=False)
self.norm1_name, norm1 = build_norm_layer(
self.norm_cfg, stem_channels, postfix=1)
self.add_module(self.norm1_name, norm1)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
def _freeze_stages(self):
if self.frozen_stages >= 0:
if self.deep_stem:
self.stem.eval()
for param in self.stem.parameters():
param.requires_grad = False
else:
self.norm1.eval()
for m in [self.conv1, self.norm1]:
for param in m.parameters():
param.requires_grad = False
for i in range(1, self.frozen_stages + 1):
m = getattr(self, f'layer{i}')
m.eval()
for param in m.parameters():
param.requires_grad = False
def init_weights(self, pretrained=None):
if isinstance(pretrained, str):
logger = get_root_logger()
load_checkpoint(self, pretrained, strict=False, logger=logger)
elif pretrained is None:
for m in self.modules():
if isinstance(m, nn.Conv2d):
kaiming_init(m)
elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
constant_init(m, 1)
if self.dcn is not None:
for m in self.modules():
if isinstance(m, Bottleneck) and hasattr(
m.conv2, 'conv_offset'):
constant_init(m.conv2.conv_offset, 0)
if self.zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck):
constant_init(m.norm3, 0)
elif isinstance(m, BasicBlock):
constant_init(m.norm2, 0)
else:
raise TypeError('pretrained must be a str or None')
def forward(self, x):
if self.deep_stem:
x = self.stem(x)
else:
x = self.conv1(x)
x = self.norm1(x)
x = self.relu(x)
x = self.maxpool(x)
outs = []
for i, layer_name in enumerate(self.res_layers):
res_layer = getattr(self, layer_name)
x = res_layer(x)
if i in self.out_indices:
outs.append(x)
return tuple(outs)
def train(self, mode=True):
super(ResNet, self).train(mode)
self._freeze_stages()
if mode and self.norm_eval:
for m in self.modules():
# trick: eval have effect on BatchNorm only
if isinstance(m, _BatchNorm):
m.eval()
@BACKBONES.register_module()
class ResNetV1d(ResNet):
"""ResNetV1d variant described in
`Bag of Tricks <https://arxiv.org/pdf/1812.01187.pdf>`_.
Compared with default ResNet(ResNetV1b), ResNetV1d replaces the 7x7 conv
in the input stem with three 3x3 convs. And in the downsampling block,
a 2x2 avg_pool with stride 2 is added before conv, whose stride is
changed to 1.
"""
def __init__(self, **kwargs):
super(ResNetV1d, self).__init__(
deep_stem=True, avg_down=True, **kwargs)
| 1 | 20,149 | If we make a new backbone class, we don't need to support `BasicBlock` | open-mmlab-mmdetection | py |
@@ -359,11 +359,6 @@ configRetry:
// Start up the dataplane driver. This may be the internal go-based driver or an external
// one.
- if configParams.BPFEnabled && !bpf.SyscallSupport() {
- log.Error("BPFEnabled is set but BPF mode is not supported on this platform. Continuing with BPF disabled.")
- configParams.BPFEnabled = false
- }
-
var dpDriver dp.DataplaneDriver
var dpDriverCmd *exec.Cmd
| 1 | // Copyright (c) 2020 Tigera, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package daemon
import (
"context"
"errors"
"fmt"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"runtime"
"runtime/debug"
"strconv"
"sync"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"github.com/projectcalico/felix/bpf"
"github.com/projectcalico/felix/buildinfo"
"github.com/projectcalico/felix/calc"
"github.com/projectcalico/felix/config"
_ "github.com/projectcalico/felix/config"
dp "github.com/projectcalico/felix/dataplane"
"github.com/projectcalico/felix/jitter"
"github.com/projectcalico/felix/logutils"
"github.com/projectcalico/felix/policysync"
"github.com/projectcalico/felix/proto"
"github.com/projectcalico/felix/statusrep"
"github.com/projectcalico/felix/usagerep"
"github.com/projectcalico/libcalico-go/lib/apiconfig"
apiv3 "github.com/projectcalico/libcalico-go/lib/apis/v3"
"github.com/projectcalico/libcalico-go/lib/backend"
bapi "github.com/projectcalico/libcalico-go/lib/backend/api"
"github.com/projectcalico/libcalico-go/lib/backend/k8s"
"github.com/projectcalico/libcalico-go/lib/backend/model"
"github.com/projectcalico/libcalico-go/lib/backend/syncersv1/felixsyncer"
"github.com/projectcalico/libcalico-go/lib/backend/syncersv1/updateprocessors"
"github.com/projectcalico/libcalico-go/lib/backend/watchersyncer"
client "github.com/projectcalico/libcalico-go/lib/clientv3"
cerrors "github.com/projectcalico/libcalico-go/lib/errors"
"github.com/projectcalico/libcalico-go/lib/health"
lclogutils "github.com/projectcalico/libcalico-go/lib/logutils"
"github.com/projectcalico/libcalico-go/lib/options"
"github.com/projectcalico/libcalico-go/lib/set"
"github.com/projectcalico/pod2daemon/binder"
"github.com/projectcalico/typha/pkg/syncclient"
)
const (
// Our default value for GOGC if it is not set. This is the percentage that heap usage must
// grow by to trigger a garbage collection. Go's default is 100, meaning that 50% of the
// heap can be lost to garbage. We reduce it to this value to trade increased CPU usage for
// lower occupancy.
defaultGCPercent = 20
// String sent on the failure report channel to indicate we're shutting down for config
// change.
reasonConfigChanged = "config changed"
// Process return code used to report a config change. This is the same as the code used
// by SIGHUP, which means that the wrapper script also restarts Felix on a SIGHUP.
configChangedRC = 129
)
// Run is the entry point to run a Felix instance.
//
// Its main role is to sequence Felix's startup by:
//
// Initialising early logging config (log format and early debug settings).
//
// Parsing command line parameters.
//
// Loading datastore configuration from the environment or config file.
//
// Loading more configuration from the datastore (this is retried until success).
//
// Starting the configured internal (golang) or external dataplane driver.
//
// Starting the background processing goroutines, which load and keep in sync with the
// state from the datastore, the "calculation graph".
//
// Starting the usage reporting and prometheus metrics endpoint threads (if configured).
//
// Then, it defers to monitorAndManageShutdown(), which blocks until one of the components
// fails, then attempts a graceful shutdown. At that point, all the processing is in
// background goroutines.
//
// To avoid having to maintain rarely-used code paths, Felix handles updates to its
// main config parameters by exiting and allowing itself to be restarted by the init
// daemon.
func Run(configFile string, gitVersion string, buildDate string, gitRevision string) {
// Go's RNG is not seeded by default. Do that now.
rand.Seed(time.Now().UTC().UnixNano())
// Special-case handling for environment variable-configured logging:
// Initialise early so we can trace out config parsing.
logutils.ConfigureEarlyLogging()
ctx := context.Background()
if os.Getenv("GOGC") == "" {
// Tune the GC to trade off a little extra CPU usage for significantly lower
// occupancy at high scale. This is worthwhile because Felix runs per-host so
// any occupancy improvement is multiplied by the number of hosts.
log.Debugf("No GOGC value set, defaulting to %d%%.", defaultGCPercent)
debug.SetGCPercent(defaultGCPercent)
}
if len(buildinfo.GitVersion) == 0 && len(gitVersion) != 0 {
buildinfo.GitVersion = gitVersion
buildinfo.BuildDate = buildDate
buildinfo.GitRevision = gitRevision
}
buildInfoLogCxt := log.WithFields(log.Fields{
"version": buildinfo.GitVersion,
"builddate": buildinfo.BuildDate,
"gitcommit": buildinfo.GitRevision,
"GOMAXPROCS": runtime.GOMAXPROCS(0),
})
buildInfoLogCxt.Info("Felix starting up")
// Health monitoring, for liveness and readiness endpoints. The following loop can take a
// while before the datastore reports itself as ready - for example when there is data that
// needs to be migrated from a previous version - and we still want to Felix to report
// itself as live (but not ready) while we are waiting for that. So we create the
// aggregator upfront and will start serving health status over HTTP as soon as we see _any_
// config that indicates that.
healthAggregator := health.NewHealthAggregator()
const healthName = "felix-startup"
// Register this function as a reporter of liveness and readiness, with no timeout.
healthAggregator.RegisterReporter(healthName, &health.HealthReport{Live: true, Ready: true}, 0)
// Load the configuration from all the different sources including the
// datastore and merge. Keep retrying on failure. We'll sit in this
// loop until the datastore is ready.
log.Info("Loading configuration...")
var backendClient bapi.Client
var v3Client client.Interface
var datastoreConfig apiconfig.CalicoAPIConfig
var configParams *config.Config
var typhaAddr string
var numClientsCreated int
var k8sClientSet *kubernetes.Clientset
var kubernetesVersion string
configRetry:
for {
if numClientsCreated > 60 {
// If we're in a restart loop, periodically exit (so we can be restarted) since
// - it may solve the problem if there's something wrong with our process
// - it prevents us from leaking connections to the datastore.
exitWithCustomRC(configChangedRC, "Restarting to avoid leaking datastore connections")
}
// Make an initial report that says we're live but not yet ready.
healthAggregator.Report(healthName, &health.HealthReport{Live: true, Ready: false})
// Load locally-defined config, including the datastore connection
// parameters. First the environment variables.
configParams = config.New()
envConfig := config.LoadConfigFromEnvironment(os.Environ())
// Then, the config file.
log.Infof("Loading config file: %v", configFile)
fileConfig, err := config.LoadConfigFile(configFile)
if err != nil {
log.WithError(err).WithField("configFile", configFile).Error(
"Failed to load configuration file")
time.Sleep(1 * time.Second)
continue configRetry
}
// Parse and merge the local config.
_, err = configParams.UpdateFrom(envConfig, config.EnvironmentVariable)
if err != nil {
log.WithError(err).WithField("configFile", configFile).Error(
"Failed to parse configuration environment variable")
time.Sleep(1 * time.Second)
continue configRetry
}
_, err = configParams.UpdateFrom(fileConfig, config.ConfigFile)
if err != nil {
log.WithError(err).WithField("configFile", configFile).Error(
"Failed to parse configuration file")
time.Sleep(1 * time.Second)
continue configRetry
}
// Each time round this loop, check that we're serving health reports if we should
// be, or cancel any existing server if we should not be serving any more.
healthAggregator.ServeHTTP(configParams.HealthEnabled, configParams.HealthHost, configParams.HealthPort)
// We should now have enough config to connect to the datastore
// so we can load the remainder of the config.
datastoreConfig = configParams.DatastoreConfig()
// Can't dump the whole config because it may have sensitive information...
log.WithField("datastore", datastoreConfig.Spec.DatastoreType).Info("Connecting to datastore")
v3Client, err = client.New(datastoreConfig)
if err != nil {
log.WithError(err).Error("Failed to create datastore client")
time.Sleep(1 * time.Second)
continue configRetry
}
log.Info("Created datastore client")
numClientsCreated++
backendClient = v3Client.(interface{ Backend() bapi.Client }).Backend()
for {
globalConfig, hostConfig, err := loadConfigFromDatastore(
ctx, backendClient, datastoreConfig, configParams.FelixHostname)
if err == ErrNotReady {
log.Warn("Waiting for datastore to be initialized (or migrated)")
time.Sleep(1 * time.Second)
healthAggregator.Report(healthName, &health.HealthReport{Live: true, Ready: true})
continue
} else if err != nil {
log.WithError(err).Error("Failed to get config from datastore")
time.Sleep(1 * time.Second)
continue configRetry
}
_, err = configParams.UpdateFrom(globalConfig, config.DatastoreGlobal)
if err != nil {
log.WithError(err).Error("Failed update global config from datastore")
time.Sleep(1 * time.Second)
continue configRetry
}
_, err = configParams.UpdateFrom(hostConfig, config.DatastorePerHost)
if err != nil {
log.WithError(err).Error("Failed update host config from datastore")
time.Sleep(1 * time.Second)
continue configRetry
}
break
}
err = configParams.Validate()
if err != nil {
log.WithError(err).Error("Failed to parse/validate configuration from datastore.")
time.Sleep(1 * time.Second)
continue configRetry
}
// We now have some config flags that affect how we configure the syncer.
// After loading the config from the datastore, reconnect, possibly with new
// config. We don't need to re-load the configuration _again_ because the
// calculation graph will spot if the config has changed since we were initialised.
datastoreConfig = configParams.DatastoreConfig()
backendClient, err = backend.NewClient(datastoreConfig)
if err != nil {
log.WithError(err).Error("Failed to (re)connect to datastore")
time.Sleep(1 * time.Second)
continue configRetry
}
numClientsCreated++
// Try to get a Kubernetes client. This is needed for discovering Typha and for the BPF mode of the dataplane.
k8sClientSet = nil
if kc, ok := backendClient.(*k8s.KubeClient); ok {
// Opportunistically share the k8s client with the datastore driver. This is the best option since
// it reduces the number of connections and it lets us piggy-back on the datastore driver's config.
log.Info("Using Kubernetes datastore driver, sharing Kubernetes client with datastore driver.")
k8sClientSet = kc.ClientSet
} else {
// Not using KDD, fall back on trying to get a Kubernetes client from the environment.
log.Info("Not using Kubernetes datastore driver, trying to get a Kubernetes client...")
k8sconf, err := rest.InClusterConfig()
if err != nil {
log.WithError(err).Info("Kubernetes in-cluster config not available. " +
"Assuming we're not in a Kubernetes deployment.")
} else {
k8sClientSet, err = kubernetes.NewForConfig(k8sconf)
if err != nil {
log.WithError(err).Error("Got in-cluster config but failed to create Kubernetes client.")
time.Sleep(1 * time.Second)
continue configRetry
}
}
}
if k8sClientSet != nil {
serverVersion, err := k8sClientSet.Discovery().ServerVersion()
if err != nil {
log.WithError(err).Error("Couldn't read server version from server")
}
log.Infof("Server Version: %#v\n", *serverVersion)
kubernetesVersion = serverVersion.GitVersion
} else {
log.Info("no Kubernetes client available")
}
// If we're configured to discover Typha, do that now so we can retry if we fail.
typhaAddr, err = discoverTyphaAddr(configParams, func(namespace, name string) (service *v1.Service, e error) {
if k8sClientSet == nil {
return nil, errors.New("failed to look up Typha, no Kubernetes client available")
}
return k8sClientSet.CoreV1().Services(namespace).Get(name, metav1.GetOptions{})
})
if err != nil {
log.WithError(err).Error("Typha discovery enabled but discovery failed.")
time.Sleep(1 * time.Second)
continue configRetry
}
break configRetry
}
if numClientsCreated > 2 {
// We don't have a way to close datastore connection so, if we reconnected after
// a failure to load config, restart felix to avoid leaking connections.
exitWithCustomRC(configChangedRC, "Restarting to avoid leaking datastore connections")
}
if configParams.BPFEnabled {
// Check for BPF dataplane support before we do anything that relies on the flag being set one way or another.
if err := bpf.SupportsBPFDataplane(); err != nil {
log.Error("BPF dataplane mode enabled but not supported by the kernel. Disabling BPF mode.")
_, err := configParams.OverrideParam("BPFEnabled", "false")
if err != nil {
log.WithError(err).Panic("Bug: failed to override config parameter")
}
}
}
// We're now both live and ready.
healthAggregator.Report(healthName, &health.HealthReport{Live: true, Ready: true})
// Enable or disable the health HTTP server according to coalesced config.
healthAggregator.ServeHTTP(configParams.HealthEnabled, configParams.HealthHost, configParams.HealthPort)
// If we get here, we've loaded the configuration successfully.
// Update log levels before we do anything else.
logutils.ConfigureLogging(configParams)
// Since we may have enabled more logging, log with the build context
// again.
buildInfoLogCxt.WithField("config", configParams).Info(
"Successfully loaded configuration.")
// Start up the dataplane driver. This may be the internal go-based driver or an external
// one.
if configParams.BPFEnabled && !bpf.SyscallSupport() {
log.Error("BPFEnabled is set but BPF mode is not supported on this platform. Continuing with BPF disabled.")
configParams.BPFEnabled = false
}
var dpDriver dp.DataplaneDriver
var dpDriverCmd *exec.Cmd
failureReportChan := make(chan string)
configChangedRestartCallback := func() { failureReportChan <- reasonConfigChanged }
dpDriver, dpDriverCmd = dp.StartDataplaneDriver(configParams, healthAggregator, configChangedRestartCallback, k8sClientSet)
// Initialise the glue logic that connects the calculation graph to/from the dataplane driver.
log.Info("Connect to the dataplane driver.")
var connToUsageRepUpdChan chan map[string]string
if configParams.UsageReportingEnabled {
// Make a channel for the connector to use to send updates to the usage reporter.
// (Otherwise, we pass in a nil channel, which disables such updates.)
connToUsageRepUpdChan = make(chan map[string]string, 1)
}
dpConnector := newConnector(configParams, connToUsageRepUpdChan, backendClient, v3Client, dpDriver, failureReportChan)
// If enabled, create a server for the policy sync API. This allows clients to connect to
// Felix over a socket and receive policy updates.
var policySyncServer *policysync.Server
var policySyncProcessor *policysync.Processor
var policySyncAPIBinder binder.Binder
calcGraphClientChannels := []chan<- interface{}{dpConnector.ToDataplane}
if configParams.PolicySyncPathPrefix != "" {
log.WithField("policySyncPathPrefix", configParams.PolicySyncPathPrefix).Info(
"Policy sync API enabled. Creating the policy sync server.")
toPolicySync := make(chan interface{})
policySyncUIDAllocator := policysync.NewUIDAllocator()
policySyncProcessor = policysync.NewProcessor(toPolicySync)
policySyncServer = policysync.NewServer(
policySyncProcessor.JoinUpdates,
policySyncUIDAllocator.NextUID,
)
policySyncAPIBinder = binder.NewBinder(configParams.PolicySyncPathPrefix)
policySyncServer.RegisterGrpc(policySyncAPIBinder.Server())
calcGraphClientChannels = append(calcGraphClientChannels, toPolicySync)
}
// Now create the calculation graph, which receives updates from the
// datastore and outputs dataplane updates for the dataplane driver.
//
// The Syncer has its own thread and we use an extra thread for the
// Validator, just to pipeline that part of the calculation then the
// main calculation graph runs in a single thread for simplicity.
// The output of the calculation graph arrives at the dataplane
// connection via channel.
//
// Syncer -chan-> Validator -chan-> Calc graph -chan-> dataplane
// KVPair KVPair protobufs
// Get a Syncer from the datastore, or a connection to our remote sync daemon, Typha,
// which will feed the calculation graph with updates, bringing Felix into sync.
var syncer Startable
var typhaConnection *syncclient.SyncerClient
syncerToValidator := calc.NewSyncerCallbacksDecoupler()
if typhaAddr != "" {
// Use a remote Syncer, via the Typha server.
log.WithField("addr", typhaAddr).Info("Connecting to Typha.")
typhaConnection = syncclient.New(
typhaAddr,
buildinfo.GitVersion,
configParams.FelixHostname,
fmt.Sprintf("Revision: %s; Build date: %s",
buildinfo.GitRevision, buildinfo.BuildDate),
syncerToValidator,
&syncclient.Options{
ReadTimeout: configParams.TyphaReadTimeout,
WriteTimeout: configParams.TyphaWriteTimeout,
KeyFile: configParams.TyphaKeyFile,
CertFile: configParams.TyphaCertFile,
CAFile: configParams.TyphaCAFile,
ServerCN: configParams.TyphaCN,
ServerURISAN: configParams.TyphaURISAN,
},
)
} else {
// Use the syncer locally.
syncer = felixsyncer.New(backendClient, datastoreConfig.Spec, syncerToValidator)
log.Info("using resource updates where applicable")
configParams.SetUseNodeResourceUpdates(true)
}
log.WithField("syncer", syncer).Info("Created Syncer")
// Start the background processing threads.
if syncer != nil {
log.Infof("Starting the datastore Syncer")
syncer.Start()
} else {
log.Infof("Starting the Typha connection")
err := typhaConnection.Start(context.Background())
if err != nil {
log.WithError(err).Error("Failed to connect to Typha. Retrying...")
startTime := time.Now()
for err != nil && time.Since(startTime) < 30*time.Second {
// Set Ready to false and Live to true when unable to connect to typha
healthAggregator.Report(healthName, &health.HealthReport{Live: true, Ready: false})
err = typhaConnection.Start(context.Background())
if err == nil {
break
}
log.WithError(err).Debug("Retrying Typha connection")
time.Sleep(1 * time.Second)
}
if err != nil {
log.WithError(err).Fatal("Failed to connect to Typha")
} else {
log.Info("Connected to Typha after retries.")
healthAggregator.Report(healthName, &health.HealthReport{Live: true, Ready: true})
}
}
supportsNodeResourceUpdates, err := typhaConnection.SupportsNodeResourceUpdates(10 * time.Second)
if err != nil {
log.WithError(err).Error("Did not get hello message from Typha in time, assuming it does not support node resource updates")
return
}
log.Debugf("Typha supports node resource updates: %v", supportsNodeResourceUpdates)
configParams.SetUseNodeResourceUpdates(supportsNodeResourceUpdates)
go func() {
typhaConnection.Finished.Wait()
failureReportChan <- "Connection to Typha failed"
}()
}
// Create the ipsets/active policy calculation graph, which will
// do the dynamic calculation of ipset memberships and active policies
// etc.
asyncCalcGraph := calc.NewAsyncCalcGraph(
configParams,
calcGraphClientChannels,
healthAggregator,
)
if configParams.UsageReportingEnabled {
// Usage reporting enabled, add stats collector to graph. When it detects an update
// to the stats, it makes a callback, which we use to send an update on a channel.
// We use a buffered channel here to avoid blocking the calculation graph.
statsChanIn := make(chan calc.StatsUpdate, 1)
statsCollector := calc.NewStatsCollector(func(stats calc.StatsUpdate) error {
statsChanIn <- stats
return nil
})
statsCollector.RegisterWith(asyncCalcGraph.CalcGraph)
// Rather than sending the updates directly to the usage reporting thread, we
// decouple with an extra goroutine. This prevents blocking the calculation graph
// goroutine if the usage reporting goroutine is blocked on IO, for example.
// Using a buffered channel wouldn't work here because the usage reporting
// goroutine can block for a long time on IO so we could build up a long queue.
statsChanOut := make(chan calc.StatsUpdate)
go func() {
var statsChanOutOrNil chan calc.StatsUpdate
var stats calc.StatsUpdate
for {
select {
case stats = <-statsChanIn:
// Got a stats update, activate the output channel.
log.WithField("stats", stats).Debug("Buffer: stats update received")
statsChanOutOrNil = statsChanOut
case statsChanOutOrNil <- stats:
// Passed on the update, deactivate the output channel until
// the next update.
log.WithField("stats", stats).Debug("Buffer: stats update sent")
statsChanOutOrNil = nil
}
}
}()
usageRep := usagerep.New(
usagerep.StaticItems{KubernetesVersion: kubernetesVersion},
configParams.UsageReportingInitialDelaySecs,
configParams.UsageReportingIntervalSecs,
statsChanOut,
connToUsageRepUpdChan,
)
go usageRep.PeriodicallyReportUsage(context.Background())
} else {
// Usage reporting disabled, but we still want a stats collector for the
// felix_cluster_* metrics. Register a no-op function as the callback.
statsCollector := calc.NewStatsCollector(func(stats calc.StatsUpdate) error {
return nil
})
statsCollector.RegisterWith(asyncCalcGraph.CalcGraph)
}
// Create the validator, which sits between the syncer and the
// calculation graph.
validator := calc.NewValidationFilter(asyncCalcGraph)
go syncerToValidator.SendTo(validator)
asyncCalcGraph.Start()
log.Infof("Started the processing graph")
var stopSignalChans []chan<- *sync.WaitGroup
if configParams.EndpointReportingEnabled {
delay := configParams.EndpointReportingDelaySecs
log.WithField("delay", delay).Info(
"Endpoint status reporting enabled, starting status reporter")
dpConnector.statusReporter = statusrep.NewEndpointStatusReporter(
configParams.FelixHostname,
configParams.OpenstackRegion,
dpConnector.StatusUpdatesFromDataplane,
dpConnector.InSync,
dpConnector.datastore,
delay,
delay*180,
)
dpConnector.statusReporter.Start()
}
// Start communicating with the dataplane driver.
dpConnector.Start()
if policySyncProcessor != nil {
log.WithField("policySyncPathPrefix", configParams.PolicySyncPathPrefix).Info(
"Policy sync API enabled. Starting the policy sync server.")
policySyncProcessor.Start()
sc := make(chan *sync.WaitGroup)
stopSignalChans = append(stopSignalChans, sc)
go policySyncAPIBinder.SearchAndBind(sc)
}
// Send the opening message to the dataplane driver, giving it its
// config.
dpConnector.ToDataplane <- &proto.ConfigUpdate{
Config: configParams.RawValues(),
}
if configParams.PrometheusMetricsEnabled {
log.Info("Prometheus metrics enabled. Starting server.")
gaugeHost := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "felix_host",
Help: "Configured Felix hostname (as a label), typically used in grouping/aggregating stats; the label defaults to the hostname of the host but can be overridden by configuration. The value of the gauge is always set to 1.",
ConstLabels: prometheus.Labels{"host": configParams.FelixHostname},
})
gaugeHost.Set(1)
prometheus.MustRegister(gaugeHost)
go servePrometheusMetrics(configParams)
}
// Register signal handlers to dump memory/CPU profiles.
logutils.RegisterProfilingSignalHandlers(configParams)
// Now monitor the worker process and our worker threads and shut
// down the process gracefully if they fail.
monitorAndManageShutdown(failureReportChan, dpDriverCmd, stopSignalChans)
}
func servePrometheusMetrics(configParams *config.Config) {
for {
log.WithFields(log.Fields{
"host": configParams.PrometheusMetricsHost,
"port": configParams.PrometheusMetricsPort,
}).Info("Starting prometheus metrics endpoint")
if configParams.PrometheusGoMetricsEnabled && configParams.PrometheusProcessMetricsEnabled {
log.Info("Including Golang & Process metrics")
} else {
if !configParams.PrometheusGoMetricsEnabled {
log.Info("Discarding Golang metrics")
prometheus.Unregister(prometheus.NewGoCollector())
}
if !configParams.PrometheusProcessMetricsEnabled {
log.Info("Discarding process metrics")
prometheus.Unregister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
}
}
http.Handle("/metrics", promhttp.Handler())
err := http.ListenAndServe(net.JoinHostPort(configParams.PrometheusMetricsHost, strconv.Itoa(configParams.PrometheusMetricsPort)), nil)
log.WithError(err).Error(
"Prometheus metrics endpoint failed, trying to restart it...")
time.Sleep(1 * time.Second)
}
}
func monitorAndManageShutdown(failureReportChan <-chan string, driverCmd *exec.Cmd, stopSignalChans []chan<- *sync.WaitGroup) {
// Ask the runtime to tell us if we get a term/int signal.
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGTERM)
signal.Notify(signalChan, syscall.SIGINT)
signal.Notify(signalChan, syscall.SIGHUP)
// Start a background thread to tell us when the dataplane driver stops.
// If the driver stops unexpectedly, we'll terminate this process.
// If this process needs to stop, we'll kill the driver and then wait
// for the message from the background thread.
driverStoppedC := make(chan bool)
go func() {
if driverCmd == nil {
log.Info("No driver process to monitor")
return
}
err := driverCmd.Wait()
log.WithError(err).Warn("Driver process stopped")
driverStoppedC <- true
}()
// Wait for one of the channels to give us a reason to shut down.
driverAlreadyStopped := driverCmd == nil
receivedFatalSignal := false
var reason string
select {
case <-driverStoppedC:
reason = "Driver stopped"
driverAlreadyStopped = true
case sig := <-signalChan:
if sig == syscall.SIGHUP {
log.Warning("Received a SIGHUP, treating as a request to reload config")
reason = reasonConfigChanged
} else {
reason = fmt.Sprintf("Received OS signal %v", sig)
receivedFatalSignal = true
}
case reason = <-failureReportChan:
}
logCxt := log.WithField("reason", reason)
logCxt.Warn("Felix is shutting down")
// Notify other components to stop. Each notified component must call Done() on the wait
// group when it has completed its shutdown.
var stopWG sync.WaitGroup
for _, c := range stopSignalChans {
stopWG.Add(1)
select {
case c <- &stopWG:
default:
stopWG.Done()
}
}
stopWG.Wait()
if !driverAlreadyStopped {
// Driver may still be running, just in case the driver is
// unresponsive, start a thread to kill this process if we
// don't manage to kill the driver.
logCxt.Info("Driver still running, trying to shut it down...")
giveUpOnSigTerm := make(chan bool)
go func() {
time.Sleep(4 * time.Second)
giveUpOnSigTerm <- true
time.Sleep(1 * time.Second)
log.Fatal("Failed to wait for driver to exit, giving up.")
}()
// Signal to the driver to exit.
err := driverCmd.Process.Signal(syscall.SIGTERM)
if err != nil {
logCxt.Error("failed to signal driver to exit")
}
select {
case <-driverStoppedC:
logCxt.Info("Driver shut down after SIGTERM")
case <-giveUpOnSigTerm:
logCxt.Error("Driver did not respond to SIGTERM, sending SIGKILL")
_ = driverCmd.Process.Kill()
<-driverStoppedC
logCxt.Info("Driver shut down after SIGKILL")
}
}
if !receivedFatalSignal {
// We're exiting due to a failure or a config change, wait
// a couple of seconds to ensure that we don't go into a tight
// restart loop (which would make the init daemon in calico/node give
// up trying to restart us).
logCxt.Info("Sleeping to avoid tight restart loop.")
go func() {
time.Sleep(2 * time.Second)
if reason == reasonConfigChanged {
exitWithCustomRC(configChangedRC, "Exiting for config change")
return
}
logCxt.Fatal("Exiting.")
}()
for {
sig := <-signalChan
if sig == syscall.SIGHUP {
logCxt.Warning("Ignoring SIGHUP because we're already shutting down")
continue
}
logCxt.WithField("signal", sig).Fatal(
"Signal received while shutting down, exiting immediately")
}
}
logCxt.Fatal("Exiting immediately")
}
func exitWithCustomRC(rc int, message string) {
// Since log writing is done a background thread, we set the force-flush flag on this log to ensure that
// all the in-flight logs get written before we exit.
log.WithFields(log.Fields{
"rc": rc,
lclogutils.FieldForceFlush: true,
}).Info(message)
os.Exit(rc)
}
var (
ErrNotReady = errors.New("datastore is not ready or has not been initialised")
)
func loadConfigFromDatastore(
ctx context.Context, client bapi.Client, cfg apiconfig.CalicoAPIConfig, hostname string,
) (globalConfig, hostConfig map[string]string, err error) {
// The configuration is split over 3 different resource types and 4 different resource
// instances in the v3 data model:
// - ClusterInformation (global): name "default"
// - FelixConfiguration (global): name "default"
// - FelixConfiguration (per-host): name "node.<hostname>"
// - Node (per-host): name: <hostname>
// Get the global values and host specific values separately. We re-use the updateprocessor
// logic to convert the single v3 resource to a set of v1 key/values.
hostConfig = make(map[string]string)
globalConfig = make(map[string]string)
var ready bool
err = getAndMergeConfig(
ctx, client, globalConfig,
apiv3.KindClusterInformation, "default",
updateprocessors.NewClusterInfoUpdateProcessor(),
&ready,
)
if err != nil {
return
}
if !ready {
// The ClusterInformation struct should contain the ready flag, if it is not set, abort.
err = ErrNotReady
return
}
err = getAndMergeConfig(
ctx, client, globalConfig,
apiv3.KindFelixConfiguration, "default",
updateprocessors.NewFelixConfigUpdateProcessor(),
&ready,
)
if err != nil {
return
}
err = getAndMergeConfig(
ctx, client, hostConfig,
apiv3.KindFelixConfiguration, "node."+hostname,
updateprocessors.NewFelixConfigUpdateProcessor(),
&ready,
)
if err != nil {
return
}
err = getAndMergeConfig(
ctx, client, hostConfig,
apiv3.KindNode, hostname,
updateprocessors.NewFelixNodeUpdateProcessor(cfg.Spec.K8sUsePodCIDR),
&ready,
)
if err != nil {
return
}
return
}
// getAndMergeConfig gets the v3 resource configuration extracts the separate config values
// (where each configuration value is stored in a field of the v3 resource Spec) and merges into
// the supplied map, as required by our v1-style configuration loader.
func getAndMergeConfig(
ctx context.Context, client bapi.Client, config map[string]string,
kind string, name string,
configConverter watchersyncer.SyncerUpdateProcessor,
ready *bool,
) error {
logCxt := log.WithFields(log.Fields{"kind": kind, "name": name})
cfg, err := client.Get(ctx, model.ResourceKey{
Kind: kind,
Name: name,
Namespace: "",
}, "")
if err != nil {
switch err.(type) {
case cerrors.ErrorResourceDoesNotExist:
logCxt.Info("No config of this type")
return nil
default:
logCxt.WithError(err).Info("Failed to load config from datastore")
return err
}
}
// Re-use the update processor logic implemented for the Syncer. We give it a v3 config
// object in a KVPair and it uses the annotations defined on it to split it into v1-style
// KV pairs. Log any errors - but don't fail completely to avoid cyclic restarts.
v1kvs, err := configConverter.Process(cfg)
if err != nil {
logCxt.WithError(err).Error("Failed to convert configuration")
}
// Loop through the converted values and update our config map with values from either the
// Global or Host configs.
for _, v1KV := range v1kvs {
if _, ok := v1KV.Key.(model.ReadyFlagKey); ok {
logCxt.WithField("ready", v1KV.Value).Info("Loaded ready flag")
if v1KV.Value == true {
*ready = true
}
} else if v1KV.Value != nil {
switch k := v1KV.Key.(type) {
case model.GlobalConfigKey:
config[k.Name] = v1KV.Value.(string)
case model.HostConfigKey:
config[k.Name] = v1KV.Value.(string)
default:
logCxt.WithField("KV", v1KV).Debug("Skipping config - not required for initial loading")
}
}
}
return nil
}
type DataplaneConnector struct {
config *config.Config
configUpdChan chan<- map[string]string
ToDataplane chan interface{}
StatusUpdatesFromDataplane chan interface{}
InSync chan bool
failureReportChan chan<- string
dataplane dp.DataplaneDriver
datastore bapi.Client
datastorev3 client.Interface
statusReporter *statusrep.EndpointStatusReporter
datastoreInSync bool
firstStatusReportSent bool
wireguardStatUpdateFromDataplane chan *proto.WireguardStatusUpdate
}
type Startable interface {
Start()
}
func newConnector(configParams *config.Config,
configUpdChan chan<- map[string]string,
datastore bapi.Client,
datastorev3 client.Interface,
dataplane dp.DataplaneDriver,
failureReportChan chan<- string,
) *DataplaneConnector {
felixConn := &DataplaneConnector{
config: configParams,
configUpdChan: configUpdChan,
datastore: datastore,
datastorev3: datastorev3,
ToDataplane: make(chan interface{}),
StatusUpdatesFromDataplane: make(chan interface{}),
InSync: make(chan bool, 1),
failureReportChan: failureReportChan,
dataplane: dataplane,
wireguardStatUpdateFromDataplane: make(chan *proto.WireguardStatusUpdate, 1),
}
return felixConn
}
func (fc *DataplaneConnector) readMessagesFromDataplane() {
defer func() {
fc.shutDownProcess("Failed to read messages from dataplane")
}()
log.Info("Reading from dataplane driver pipe...")
ctx := context.Background()
for {
payload, err := fc.dataplane.RecvMessage()
if err != nil {
log.WithError(err).Error("Failed to read from front-end socket")
fc.shutDownProcess("Failed to read from front-end socket")
}
log.WithField("payload", payload).Debug("New message from dataplane")
switch msg := payload.(type) {
case *proto.ProcessStatusUpdate:
fc.handleProcessStatusUpdate(ctx, msg)
case *proto.WorkloadEndpointStatusUpdate:
if fc.statusReporter != nil {
fc.StatusUpdatesFromDataplane <- msg
}
case *proto.WorkloadEndpointStatusRemove:
if fc.statusReporter != nil {
fc.StatusUpdatesFromDataplane <- msg
}
case *proto.HostEndpointStatusUpdate:
if fc.statusReporter != nil {
fc.StatusUpdatesFromDataplane <- msg
}
case *proto.HostEndpointStatusRemove:
if fc.statusReporter != nil {
fc.StatusUpdatesFromDataplane <- msg
}
case *proto.WireguardStatusUpdate:
fc.wireguardStatUpdateFromDataplane <- msg
default:
log.WithField("msg", msg).Warning("Unknown message from dataplane")
}
log.Debug("Finished handling message from front-end")
}
}
func (fc *DataplaneConnector) handleProcessStatusUpdate(ctx context.Context, msg *proto.ProcessStatusUpdate) {
log.Debugf("Status update from dataplane driver: %v", *msg)
statusReport := model.StatusReport{
Timestamp: msg.IsoTimestamp,
UptimeSeconds: msg.Uptime,
FirstUpdate: !fc.firstStatusReportSent,
}
kv := model.KVPair{
Key: model.ActiveStatusReportKey{Hostname: fc.config.FelixHostname, RegionString: model.RegionString(fc.config.OpenstackRegion)},
Value: &statusReport,
TTL: fc.config.ReportingTTLSecs,
}
applyCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
_, err := fc.datastore.Apply(applyCtx, &kv)
cancel()
if err != nil {
if _, ok := err.(cerrors.ErrorOperationNotSupported); ok {
log.Debug("Datastore doesn't support status reports.")
return // and it won't support the last status key either.
} else {
log.Warningf("Failed to write status to datastore: %v", err)
}
} else {
fc.firstStatusReportSent = true
}
kv = model.KVPair{
Key: model.LastStatusReportKey{Hostname: fc.config.FelixHostname, RegionString: model.RegionString(fc.config.OpenstackRegion)},
Value: &statusReport,
}
applyCtx, cancel = context.WithTimeout(ctx, 2*time.Second)
_, err = fc.datastore.Apply(applyCtx, &kv)
cancel()
if err != nil {
log.Warningf("Failed to write status to datastore: %v", err)
}
}
func (fc *DataplaneConnector) reconcileWireguardStatUpdate(dpPubKey string) error {
// In case of a recoverable failure (ErrorResourceUpdateConflict), retry update 3 times.
for iter := 0; iter < 3; iter++ {
// Read node resource from datastore and compare it with the publicKey from dataplane.
getCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
node, err := fc.datastorev3.Nodes().Get(getCtx, fc.config.FelixHostname, options.GetOptions{})
cancel()
if err != nil {
switch err.(type) {
case cerrors.ErrorResourceDoesNotExist:
if dpPubKey != "" {
// If the node doesn't exist but non-empty public-key need to be set.
log.Panic("v3 node resource must exist for Wireguard.")
} else {
// No node with empty dataplane update implies node resource
// doesn't need to be processed further.
log.Debug("v3 node resource doesn't need any update")
return nil
}
}
// return error here so we can retry in some time.
log.WithError(err).Info("Failed to read node resource")
return err
}
// Check if the public-key needs to be updated.
storedPublicKey := node.Status.WireguardPublicKey
if storedPublicKey != dpPubKey {
updateCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
node.Status.WireguardPublicKey = dpPubKey
_, err := fc.datastorev3.Nodes().Update(updateCtx, node, options.SetOptions{})
cancel()
if err != nil {
// check if failure is recoverable
switch err.(type) {
case cerrors.ErrorResourceUpdateConflict:
log.Debug("Update conflict, retrying update")
continue
}
// retry in some time.
log.WithError(err).Info("Failed updating node resource")
return err
}
log.Debugf("Updated Wireguard public-key from %s to %s", storedPublicKey, dpPubKey)
}
break
}
return nil
}
func (fc *DataplaneConnector) handleWireguardStatUpdateFromDataplane() {
var current *proto.WireguardStatusUpdate
var ticker *jitter.Ticker
var retryC <-chan time.Time
for {
// Block until we either get an update or it's time to retry a failed update.
select {
case current = <-fc.wireguardStatUpdateFromDataplane:
log.Debugf("Wireguard status update from dataplane driver: %s", current.PublicKey)
case <-retryC:
log.Debug("retrying failed Wireguard status update")
}
if ticker != nil {
ticker.Stop()
}
// Try and reconcile the current wireguard status data.
err := fc.reconcileWireguardStatUpdate(current.PublicKey)
if err == nil {
current = nil
retryC = nil
ticker = nil
} else {
// retry reconciling between 2-4 seconds.
ticker = jitter.NewTicker(2*time.Second, 2*time.Second)
retryC = ticker.C
}
}
}
var handledConfigChanges = set.From("CalicoVersion", "ClusterGUID", "ClusterType")
func (fc *DataplaneConnector) sendMessagesToDataplaneDriver() {
defer func() {
fc.shutDownProcess("Failed to send messages to dataplane")
}()
var config map[string]string
for {
msg := <-fc.ToDataplane
switch msg := msg.(type) {
case *proto.InSync:
log.Info("Datastore now in sync.")
if !fc.datastoreInSync {
log.Info("Datastore in sync for first time, sending message to status reporter.")
fc.datastoreInSync = true
fc.InSync <- true
}
case *proto.ConfigUpdate:
if config != nil {
log.WithFields(log.Fields{
"old": config,
"new": msg.Config,
}).Info("Config updated, checking whether we need to restart")
restartNeeded := false
for kNew, vNew := range msg.Config {
logCxt := log.WithFields(log.Fields{"key": kNew, "new": vNew})
if vOld, prs := config[kNew]; !prs {
logCxt = logCxt.WithField("updateType", "add")
} else if vNew != vOld {
logCxt = logCxt.WithFields(log.Fields{"old": vOld, "updateType": "update"})
} else {
continue
}
if handledConfigChanges.Contains(kNew) {
logCxt.Info("Config change can be handled without restart")
continue
}
logCxt.Warning("Config change requires restart")
restartNeeded = true
}
for kOld, vOld := range config {
logCxt := log.WithFields(log.Fields{"key": kOld, "old": vOld, "updateType": "delete"})
if _, prs := msg.Config[kOld]; prs {
// Key was present in the message so we've handled above.
continue
}
if handledConfigChanges.Contains(kOld) {
logCxt.Info("Config change can be handled without restart")
continue
}
logCxt.Warning("Config change requires restart")
restartNeeded = true
}
if restartNeeded {
fc.shutDownProcess("config changed")
}
}
// Take a copy of the config to compare against next time.
config = make(map[string]string)
for k, v := range msg.Config {
config[k] = v
}
if fc.configUpdChan != nil {
// Send the config over to the usage reporter.
fc.configUpdChan <- config
}
case *calc.DatastoreNotReady:
log.Warn("Datastore became unready, need to restart.")
fc.shutDownProcess("datastore became unready")
}
if err := fc.dataplane.SendMessage(msg); err != nil {
fc.shutDownProcess("Failed to write to dataplane driver")
}
}
}
func (fc *DataplaneConnector) shutDownProcess(reason string) {
// Send a failure report to the managed shutdown thread then give it
// a few seconds to do the shutdown.
fc.failureReportChan <- reason
time.Sleep(5 * time.Second)
// The graceful shutdown failed, terminate the process.
log.Panic("Managed shutdown failed. Panicking.")
}
func (fc *DataplaneConnector) Start() {
// Start a background thread to write to the dataplane driver.
go fc.sendMessagesToDataplaneDriver()
// Start background thread to read messages from dataplane driver.
go fc.readMessagesFromDataplane()
// Start a background thread to handle Wireguard update to Node.
go fc.handleWireguardStatUpdateFromDataplane()
}
var ErrServiceNotReady = errors.New("Kubernetes service missing IP or port.")
func discoverTyphaAddr(configParams *config.Config, getKubernetesService func(namespace, name string) (*v1.Service, error)) (string, error) {
if configParams.TyphaAddr != "" {
// Explicit address; trumps other sources of config.
return configParams.TyphaAddr, nil
}
if configParams.TyphaK8sServiceName == "" {
// No explicit address, and no service name, not using Typha.
return "", nil
}
// If we get here, we need to look up the Typha service using the k8s API.
// TODO Typha: support Typha lookup without using rest.InClusterConfig().
svc, err := getKubernetesService(configParams.TyphaK8sNamespace, configParams.TyphaK8sServiceName)
if err != nil {
log.WithError(err).Error("Unable to get Typha service from Kubernetes.")
return "", err
}
host := svc.Spec.ClusterIP
log.WithField("clusterIP", host).Info("Found Typha ClusterIP.")
if host == "" {
log.WithError(err).Error("Typha service had no ClusterIP.")
return "", ErrServiceNotReady
}
for _, p := range svc.Spec.Ports {
if p.Name == "calico-typha" {
log.WithField("port", p).Info("Found Typha service port.")
typhaAddr := net.JoinHostPort(host, fmt.Sprintf("%v", p.Port))
return typhaAddr, nil
}
}
log.Error("Didn't find Typha service port.")
return "", ErrServiceNotReady
}
| 1 | 17,869 | This was an out-of-date dupe of the check on line 335 | projectcalico-felix | go |
@@ -44,7 +44,6 @@ window.PluginsView = countlyView.extend({
this.dtable = $('#plugins-table').dataTable($.extend({}, $.fn.dataTable.defaults, {
"aaData": pluginsData,
- "bPaginate": false,
"aoColumns": [
{ "mData": function (row, type) { if (row.enabled) { return jQuery.i18n.map[row.code + ".plugin-title"] || jQuery.i18n.map[row.code + ".title"] || row.title; } else return row.title }, "sType": "string", "sTitle": jQuery.i18n.map["plugins.name"] },
{ | 1 | window.PluginsView = countlyView.extend({
initialize: function () {
this.filter = (store.get("countly_pluginsfilter")) ? store.get("countly_pluginsfilter") : "plugins-all";
},
beforeRender: function () {
if (this.template)
return $.when(countlyPlugins.initialize()).then(function () { });
else {
var self = this;
return $.when($.get(countlyGlobal["path"] + '/plugins/templates/plugins.html', function (src) {
self.template = Handlebars.compile(src);
}), countlyPlugins.initialize()).then(function () { });
}
},
renderCommon: function (isRefresh) {
var pluginsData = countlyPlugins.getData();
this.templateData = {
"page-title": jQuery.i18n.map["plugins.title"]
};
var self = this;
if (!isRefresh) {
$(this.el).html(this.template(this.templateData));
$("#" + this.filter).addClass("selected").addClass("active");
$.fn.dataTableExt.afnFiltering.push(function (oSettings, aData, iDataIndex) {
if (!$(oSettings.nTable).hasClass("plugins-filter")) {
return true;
}
if (self.filter == "plugins-enabled") {
return aData[1]
}
if (self.filter == "plugins-disabled") {
return !aData[1]
}
return true;
});
this.dtable = $('#plugins-table').dataTable($.extend({}, $.fn.dataTable.defaults, {
"aaData": pluginsData,
"bPaginate": false,
"aoColumns": [
{ "mData": function (row, type) { if (row.enabled) { return jQuery.i18n.map[row.code + ".plugin-title"] || jQuery.i18n.map[row.code + ".title"] || row.title; } else return row.title }, "sType": "string", "sTitle": jQuery.i18n.map["plugins.name"] },
{
"mData": function (row, type) {
if (type == "display") {
var disabled = (row.prepackaged) ? 'disabled' : '';
var input = '<div class="on-off-switch ' + disabled + '">';
if (row.enabled) {
input += '<input type="checkbox" class="on-off-switch-checkbox" id="plugin-' + row.code + '" checked ' + disabled + '>';
} else {
input += '<input type="checkbox" class="on-off-switch-checkbox" id="plugin-' + row.code + '" ' + disabled + '>';
}
input += '<label class="on-off-switch-label" for="plugin-' + row.code + '"></label>';
input += '<span class="text">' + jQuery.i18n.map["plugins.enable"] + '</span>';
return input;
} else {
return row.enabled;
}
},
"sType": "string", "sTitle": jQuery.i18n.map["plugins.state"], "sClass": "shrink"
},
{ "mData": function (row, type) { if (row.enabled) { return jQuery.i18n.map[row.code + ".plugin-description"] || jQuery.i18n.map[row.code + ".description"] || row.description; } else return row.description; }, "sType": "string", "sTitle": jQuery.i18n.map["plugins.description"], "bSortable": false, "sClass": "light" },
{ "mData": function (row, type) { return row.version; }, "sType": "string", "sTitle": jQuery.i18n.map["plugins.version"], "sClass": "center", "bSortable": false },
{ "mData": function (row, type) { if (row.homepage != "") return '<a class="plugin-link" href="' + row.homepage + '" target="_blank"><i class="ion-android-open"></i></a>'; else return ""; }, "sType": "string", "sTitle": jQuery.i18n.map["plugins.homepage"], "sClass": "shrink center", "bSortable": false }
]
}));
this.dtable.stickyTableHeaders();
this.dtable.fnSort([[0, 'asc']]);
/*
Make header sticky if scroll is more than the height of header
This is done in order to make Apply Changes button visible
*/
var navigationTop = $("#sticky-plugin-header").offset().top;
var tableHeaderTop = $("#plugins-table").find("thead").offset().top;
$(window).on("scroll", function (e) {
var topBarHeight = $("#top-bar").outerHeight();
var $fixedHeader = $("#sticky-plugin-header");
if ($(this).scrollTop() > navigationTop - topBarHeight) {
var width = $("#content-container").width();
$fixedHeader.addClass("fixed");
$fixedHeader.css({ width: width });
if (topBarHeight) {
$fixedHeader.css({ top: topBarHeight });
} else {
$fixedHeader.css({ top: 0 });
}
} else {
$fixedHeader.removeClass("fixed");
$fixedHeader.css({ width: "" });
}
if (($(this).scrollTop() + $fixedHeader.outerHeight()) > tableHeaderTop) {
$(".sticky-header").removeClass("hide");
} else {
$(".sticky-header").addClass("hide");
}
});
$(window).on("resize", function (e) {
var $fixedHeader = $("#sticky-plugin-header");
if ($fixedHeader.hasClass("fixed")) {
var width = $("#content-container").width();
$fixedHeader.css({ width: width });
}
});
}
},
refresh: function (Refreshme) {
if (Refreshme) {
var self = this;
return $.when(this.beforeRender()).then(function () {
if (app.activeView != self) {
return false;
}
CountlyHelpers.refreshTable(self.dtable, countlyPlugins.getData());
app.localize();
});
}
},
togglePlugin: function (plugins) {
var self = this;
var overlay = $("#overlay").clone();
$("body").append(overlay);
overlay.show();
var loader = $(this.el).find("#loader");
loader.show();
countlyPlugins.toggle(plugins, function (res) {
var msg = { clearAll: true };
if (res == "Success" || res == "Errors") {
var seconds = 10;
if (res == "Success") {
msg.title = jQuery.i18n.map["plugins.success"];
msg.message = jQuery.i18n.map["plugins.restart"] + " " + seconds + " " + jQuery.i18n.map["plugins.seconds"];
msg.info = jQuery.i18n.map["plugins.finish"];
msg.delay = seconds * 1000;
}
else if (res == "Errors") {
msg.title = jQuery.i18n.map["plugins.errors"];
msg.message = jQuery.i18n.map["plugins.errors-msg"];
msg.info = jQuery.i18n.map["plugins.restart"] + " " + seconds + " " + jQuery.i18n.map["plugins.seconds"];
msg.sticky = true;
msg.type = "error";
}
setTimeout(function () {
window.location.reload(true);
}, seconds * 1000);
}
else {
overlay.hide();
loader.hide();
msg.title = jQuery.i18n.map["plugins.error"];
msg.message = res;
msg.info = jQuery.i18n.map["plugins.retry"];
msg.sticky = true;
msg.type = "error";
}
CountlyHelpers.notify(msg);
});
},
filterPlugins: function (filter) {
this.filter = filter;
store.set("countly_pluginsfilter", filter);
$("#" + this.filter).addClass("selected").addClass("active");
this.dtable.fnDraw();
}
});
window.ConfigurationsView = countlyView.extend({
userConfig: false,
initialize: function () {
this.predefinedInputs = {};
this.predefinedLabels = {
};
this.configsData = {};
this.cache = {};
this.changes = {};
//register some common system config inputs
this.registerInput("apps.category", function (value) {
return null;
var categories = app.manageAppsView.getAppCategories();
var select = '<div class="cly-select" id="apps.category">' +
'<div class="select-inner">' +
'<div class="text-container">';
if (!categories[value])
select += '<div class="text"></div>';
else
select += '<div class="text">' + categories[value] + '</div>';
select += '</div>' +
'<div class="right combo"></div>' +
'</div>' +
'<div class="select-items square">' +
'<div>';
for (var i in categories) {
select += '<div data-value="' + i + '" class="segmentation-option item">' + categories[i] + '</div>';
}
select += '</div>' +
'</div>' +
'</div>';
return select;
});
this.registerInput("apps.country", function (value) {
var zones = app.manageAppsView.getTimeZones();
var select = '<div class="cly-select" id="apps.country">' +
'<div class="select-inner">' +
'<div class="text-container">';
if (!zones[value])
select += '<div class="text"></div>';
else
select += '<div class="text"><div class="flag" style="background-image:url(images/flags/' + value.toLowerCase() + '.png)"></div>' + zones[value].n + '</div>';
select += '</div>' +
'<div class="right combo"></div>' +
'</div>' +
'<div class="select-items square">' +
'<div>';
for (var i in zones) {
select += '<div data-value="' + i + '" class="segmentation-option item"><div class="flag" style="background-image:url(images/flags/' + i.toLowerCase() + '.png)"></div>' + zones[i].n + '</div>';
}
select += '</div>' +
'</div>' +
'</div>';
return select;
});
this.registerInput("frontend.theme", function (value) {
var themes = countlyPlugins.getThemeList();
var select = '<div class="cly-select" id="frontend.theme">' +
'<div class="select-inner">' +
'<div class="text-container">';
if (value && value.length)
select += '<div class="text">' + value + '</div>';
else
select += '<div class="text" data-localize="configs.no-theme">' + jQuery.i18n.map["configs.no-theme"] + '</div>';
select += '</div>' +
'<div class="right combo"></div>' +
'</div>' +
'<div class="select-items square">' +
'<div>';
for (var i = 0; i < themes.length; i++) {
if (themes[i] == "")
select += '<div data-value="" class="segmentation-option item" data-localize="configs.no-theme">' + jQuery.i18n.map["configs.no-theme"] + '</div>';
else
select += '<div data-value="' + themes[i] + '" class="segmentation-option item">' + themes[i] + '</div>';
}
select += '</div>' +
'</div>' +
'</div>';
return select;
});
//register some common system config inputs
this.registerInput("logs.default", function (value) {
var categories = ['debug', 'info', 'warn', 'error'];
var select = '<div class="cly-select" id="logs.default">' +
'<div class="select-inner">' +
'<div class="text-container">';
if (value && value.length)
select += '<div class="text" data-localize="configs.logs.' + value + '">' + jQuery.i18n.map["configs.logs." + value] + '</div>';
else
select += '<div class="text" data-localzie="configs.logs.warn">' + Query.i18n.map["configs.logs.warn"] + '</div>';
select += '</div>' +
'<div class="right combo"></div>' +
'</div>' +
'<div class="select-items square">' +
'<div>';
for (var i = 0; i < categories.length; i++) {
select += '<div data-value="' + categories[i] + '" class="segmentation-option item" data-localize="configs.logs.' + categories[i] + '">' + jQuery.i18n.map["configs.logs." + categories[i]] + '</div>';
}
select += '</div>' +
'</div>' +
'</div>';
return select;
});
this.registerInput("security.dashboard_additional_headers", function (value) {
return '<textarea rows="5" style="width:100%" id="security.dashboard_additional_headers">' + (value || "") + '</textarea>';
});
this.registerInput("security.api_additional_headers", function (value) {
return '<textarea rows="5" style="width:100%" id="security.api_additional_headers">' + (value || "") + '</textarea>';
});
this.registerInput("apps.timezone", function (value) {
return null;
});
},
beforeRender: function () {
if (this.template)
if (this.userConfig)
return $.when(countlyPlugins.initializeUserConfigs()).then(function () { });
else
return $.when(countlyPlugins.initializeConfigs()).then(function () { });
else {
var self = this;
if (this.userConfig)
return $.when($.get(countlyGlobal["path"] + '/plugins/templates/configurations.html', function (src) {
self.template = Handlebars.compile(src);
}), countlyPlugins.initializeUserConfigs()).then(function () { });
else
return $.when($.get(countlyGlobal["path"] + '/plugins/templates/configurations.html', function (src) {
self.template = Handlebars.compile(src);
}), countlyPlugins.initializeConfigs()).then(function () { });
}
},
renderCommon: function (isRefresh) {
console.log("common");
if (this.reset)
$("#new-install-overlay").show();
if (this.userConfig)
this.configsData = countlyPlugins.getUserConfigsData();
else
this.configsData = countlyPlugins.getConfigsData();
this.searchKeys = this.getSearchKeys(this.configsData);
this.navTitles = this.setNavTitles(this.configsData);
this.selectedNav = this.navTitles.coreTitles[0];
var configsHTML;
var title = jQuery.i18n.map["plugins.configs"];
if (this.userConfig)
title = jQuery.i18n.map["plugins.user-configs"];
if (this.namespace && this.configsData[this.namespace]) {
configsHTML = this.generateConfigsTable(this.configsData[this.namespace], "." + this.namespace);
title = this.getInputLabel(this.namespace, this.namespace) + " " + title;
}
else
configsHTML = this.generateConfigsTable(this.configsData);
this.templateData = {
"page-title": title,
"configs": configsHTML,
"namespace": this.namespace,
"user": this.userConfig,
"reset": this.reset,
"navTitles": this.navTitles,
"selectedNav": this.selectedNav
};
var self = this;
if (this.success) {
CountlyHelpers.notify({
title: jQuery.i18n.map["configs.changed"],
message: jQuery.i18n.map["configs.saved"]
});
this.success = false;
if (typeof history !== "undefined" && typeof history.replaceState !== "undefined") {
if (this.userConfig)
history.replaceState(undefined, undefined, "#/manage/user-settings");
else
history.replaceState(undefined, undefined, "#/manage/configurations");
}
}
if (!isRefresh) {
$(this.el).html(this.template(this.templateData));
$('#nav-item-' + this.selectedNav.key).addClass('selected');
this.changes = {};
this.cache = JSON.parse(JSON.stringify(this.configsData));
$(".configs #username").val(countlyGlobal["member"].username);
$(".configs #api-key").val(countlyGlobal["member"].api_key);
$("#configs-back").click(function () {
window.history.back();
});
$('.on-off-switch input').on("change", function () {
var isChecked = $(this).is(":checked"),
attrID = $(this).attr("id");
self.updateConfig(attrID, isChecked);
});
$(".configs input").keyup(function () {
var id = $(this).attr("id");
var value = $(this).val();
if ($(this).attr("type") == "number")
value = parseFloat(value);
self.updateConfig(id, value);
});
$(".configs textarea").keyup(function () {
var id = $(this).attr("id");
var value = $(this).val();
self.updateConfig(id, value);
});
$(".configs .segmentation-option").on("click", function () {
var id = $(this).closest(".cly-select").attr("id");
var value = $(this).data("value");
self.updateConfig(id, value);
});
$(".configs #username").off("keyup").on("keyup", _.throttle(function () {
if (!($(this).val().length) || $("#menu-username").text() == $(this).val()) {
$(".username-check").remove();
return false;
}
$(this).next(".required").remove();
var existSpan = $("<span class='username-check red-text' data-localize='management-users.username.exists'>").html(jQuery.i18n.map["management-users.username.exists"]),
notExistSpan = $("<span class='username-check green-text'>").html("✔"),
data = {};
data.username = $(this).val();
data._csrf = countlyGlobal['csrf_token'];
var self = $(this);
$.ajax({
type: "POST",
url: countlyGlobal["path"] + "/users/check/username",
data: data,
success: function (result) {
$(".username-check").remove();
if (result) {
self.after(notExistSpan.clone());
} else {
self.after(existSpan.clone());
}
}
});
}, 300));
$(".configs #new_pwd").off("keyup").on("keyup", _.throttle(function () {
$(".password-check").remove();
var error = CountlyHelpers.validatePassword($(this).val());
if (error) {
var invalidSpan = $("<div class='password-check red-text'>").html(error);
$(this).after(invalidSpan.clone());
return false;
}
}, 300));
$(".configs #re_new_pwd").off("keyup").on("keyup", _.throttle(function () {
$(".password-check").remove();
var error = CountlyHelpers.validatePassword($(this).val());
if (error) {
var invalidSpan = $("<div class='password-check red-text'>").html(error);
$(this).after(invalidSpan.clone());
return false;
}
}, 300));
$(".configs #usersettings_regenerate").click(function () {
$(".configs #api-key").val(CountlyHelpers.generatePassword(32, true)).trigger("keyup");
});
$('.config-container').off('click').on('click', function(){
var key = $(this).attr('id').replace('nav-item-', '');
self.selectedNav = self.navTitles.coreTitles.find(function(x) { return x.key === key}) || self.navTitles.pluginTitles.find(function(x) { return x.key === key});
self.templateData.selectedNav = self.selectedNav;
$('.config-container').removeClass('selected');
$('#nav-item-' + self.selectedNav.key).addClass('selected');
$('.config-table-row').hide();
$('.config-table-row-header').hide();
$('#config-title').html(self.selectedNav.label);
$('#config-table-row-' + self.selectedNav.key).show();
$('#config-table-row-header-' + self.selectedNav.key).show();
$('.config-table-details-row').show();
$('#config-table-container').removeClass('title-rows-enable');
$('#config-table-container').addClass('title-rows-hidden');
$('#empty-search-result').hide();
$('#search-box').val("");
})
$(".configs .account-settings .input input").keyup(function () {
$("#configs-apply-changes").removeClass("settings-changes");
$(".configs .account-settings .input input").each(function () {
var id = $(this).attr("id");
switch (id) {
case "username":
if (this.value != $("#menu-username").text())
$("#configs-apply-changes").addClass("settings-changes");
break;
case "api-key":
if (this.value != $("#user-api-key").val())
$("#configs-apply-changes").addClass("settings-changes");
break;
default:
if (this.value != "")
$("#configs-apply-changes").addClass("settings-changes");
break;
}
if ($("#configs-apply-changes").hasClass("settings-changes"))
$("#configs-apply-changes").show();
else if (!$("#configs-apply-changes").hasClass("configs-changes"))
$("#configs-apply-changes").hide();
});
});
$("#configs-apply-changes").click(function () {
if (self.userConfig) {
$(".username-check.green-text").remove();
if ($(".red-text").length) {
CountlyHelpers.notify({
title: jQuery.i18n.map["user-settings.please-correct-input"],
message: jQuery.i18n.map["configs.not-saved"],
type: "error"
});
return false;
}
var username = $(".configs #username").val(),
old_pwd = $(".configs #old_pwd").val(),
new_pwd = $(".configs #new_pwd").val(),
re_new_pwd = $(".configs #re_new_pwd").val(),
api_key = $(".configs #api-key").val();
var ignoreError = false;
if ((new_pwd.length && re_new_pwd.length) || api_key.length || username.length) {
ignoreError = true;
}
if ((new_pwd.length || re_new_pwd.length) && !old_pwd.length) {
CountlyHelpers.notify({
title: jQuery.i18n.map["configs.not-saved"],
message: jQuery.i18n.map["user-settings.old-password-match"],
type: "error"
});
return true;
}
if (new_pwd != re_new_pwd) {
CountlyHelpers.notify({
title: jQuery.i18n.map["configs.not-saved"],
message: jQuery.i18n.map["user-settings.password-match"],
type: "error"
});
return true;
}
if (new_pwd.length && new_pwd == old_pwd) {
CountlyHelpers.notify({
title: jQuery.i18n.map["configs.not-saved"],
message: jQuery.i18n.map["user-settings.password-not-old"],
type: "error"
});
return true;
}
if (api_key.length != 32) {
CountlyHelpers.notify({
title: jQuery.i18n.map["configs.not-saved"],
message: jQuery.i18n.map["user-settings.api-key-length"],
type: "error"
});
return true;
}
$.ajax({
type: "POST",
url: countlyGlobal["path"] + "/user/settings",
data: {
"username": username,
"old_pwd": old_pwd,
"new_pwd": new_pwd,
"api_key": api_key,
_csrf: countlyGlobal['csrf_token']
},
success: function (result) {
var saveResult = $(".configs #settings-save-result");
if (result == "username-exists") {
CountlyHelpers.notify({
title: jQuery.i18n.map["configs.not-saved"],
message: jQuery.i18n.map["management-users.username.exists"],
type: "error"
});
return true;
} else if (!result) {
CountlyHelpers.notify({
title: jQuery.i18n.map["configs.not-saved"],
message: jQuery.i18n.map["user-settings.alert"],
type: "error"
});
return true;
} else {
if (!isNaN(parseInt(result))) {
$("#new-install-overlay").fadeOut();
countlyGlobal["member"].password_changed = parseInt(result);
}
else if (typeof result === "string") {
CountlyHelpers.notify({
title: jQuery.i18n.map["configs.not-saved"],
message: jQuery.i18n.map[result],
type: "error"
});
return true;
}
$("#user-api-key").val(api_key);
$(".configs #old_pwd").val("");
$(".configs #new_pwd").val("");
$(".configs #re_new_pwd").val("");
$("#menu-username").text(username);
$("#user-api-key").val(api_key);
countlyGlobal["member"].username = username;
countlyGlobal["member"].api_key = api_key;
}
if (Object.keys(self.changes).length) {
countlyPlugins.updateUserConfigs(self.changes, function (err, services) {
if (err && !ignoreError) {
CountlyHelpers.notify({
title: jQuery.i18n.map["configs.not-saved"],
message: jQuery.i18n.map["configs.not-changed"],
type: "error"
});
}
else {
CountlyHelpers.notify({
title: jQuery.i18n.map["configs.changed"],
message: jQuery.i18n.map["configs.saved"]
});
self.configsData = JSON.parse(JSON.stringify(self.cache));
$("#configs-apply-changes").hide();
self.changes = {};
}
});
}
else {
CountlyHelpers.notify({
title: jQuery.i18n.map["configs.changed"],
message: jQuery.i18n.map["configs.saved"]
});
$("#configs-apply-changes").hide();
}
}
});
}
else {
countlyPlugins.updateConfigs(self.changes, function (err, services) {
if (err) {
CountlyHelpers.notify({
title: jQuery.i18n.map["configs.not-saved"],
message: jQuery.i18n.map["configs.not-changed"],
type: "error"
});
}
else {
self.configsData = JSON.parse(JSON.stringify(self.cache));
$("#configs-apply-changes").hide();
self.changes = {};
location.hash = "#/manage/configurations/success";
window.location.reload(true);
}
});
}
});
$('#search-box').off('input').on('input', function(){
var searchKey = $(this).val().toLowerCase();
if(searchKey.length === 0){
$('#nav-item-' + self.selectedNav.key).trigger('click');
return;
}
var searchResult = self.searchKeys.filter(function(item){
return item.searchKeys.indexOf(searchKey) >= 0
});
var configGroups = [];
searchResult.forEach(function(result){
var group = {
key : result.key,
rows : result.subItems.filter(function(field){ return field.searchKeys.indexOf(searchKey) >= 0})
}
configGroups.push(group);
});
$('.config-container').removeClass('selected');
$('#config-title').html('RESULTS FOR: "' + searchKey + '"');
$('#config-table-container').removeClass('title-rows-hidden');
$('#config-table-container').addClass('title-rows-enable');
self.showSearchResult(configGroups);
if(configGroups.length === 0){
$('#empty-search-result').show();
}else{
$('#empty-search-result').hide();
}
});
/*
Make header sticky if scroll is more than the height of header
This is done in order to make Apply Changes button visible
*/
var navigationTop = $("#sticky-config-header").offset().top;
// $(window).on("scroll", function(e) {
// var topBarHeight = $("#top-bar").outerHeight();
// var $fixedHeader = $("#sticky-config-header");
// if ($(this).scrollTop() > navigationTop - topBarHeight) {
// var width = $("#content-container").width();
// $fixedHeader.addClass("fixed");
// $fixedHeader.css({width: width});
// if (topBarHeight) {
// $fixedHeader.css({top: topBarHeight});
// } else {
// $fixedHeader.css({top: 0});
// }
// } else {
// $fixedHeader.removeClass("fixed");
// $fixedHeader.css({width: ""});
// }
// });
$(window).on("resize", function (e) {
var $fixedHeader = $("#sticky-config-header");
if ($fixedHeader.hasClass("fixed")) {
var width = $("#content-container").width();
$fixedHeader.css({ width: width });
}
});
}
},
updateConfig: function (id, value) {
var configs = id.split(".");
//update cache
var data = this.cache;
for (var i = 0; i < configs.length; i++) {
if (typeof data[configs[i]] == "undefined") {
break;
}
else if (i == configs.length - 1) {
data[configs[i]] = value;
}
else {
data = data[configs[i]];
}
}
//add to changes
var data = this.changes;
for (var i = 0; i < configs.length; i++) {
if (i == configs.length - 1) {
data[configs[i]] = value;
}
else if (typeof data[configs[i]] == "undefined") {
data[configs[i]] = {};
}
data = data[configs[i]];
}
$("#configs-apply-changes").removeClass("configs-changes");
if (JSON.stringify(this.configsData) != JSON.stringify(this.cache)) {
$("#configs-apply-changes").addClass("configs-changes");
}
else {
this.changes = {};
}
if ($("#configs-apply-changes").hasClass("configs-changes"))
$("#configs-apply-changes").show();
else if (!$("#configs-apply-changes").hasClass("settings-changes"))
$("#configs-apply-changes").hide();
},
getSearchKeys: function(data){
var result = Object.keys(data).reduce(function(prev, key){
var dataItem = data[key];
var searchItem = {}
var searcKeyItems = Object.keys(dataItem).reduce(function(subPrev, subKey){
var isCore = countlyGlobal.plugins.indexOf(key) === -1;
var titleText = jQuery.i18n.map["configs." + key + "-" + subKey] || jQuery.i18n.map[key + "." + subKey] || jQuery.i18n.map[key + "." + subKey.replace(/\_/g, '-')] || jQuery.i18n.map["userdata." + subKey] || subKey;
var helpText = jQuery.i18n.map["configs.help." + key + "-" + subKey] || "";
var searchItems = titleText + "," + helpText + "," + subKey + ",";
subPrev.subItems.push({
key : subKey,
searchKeys : searchItems
});
subPrev.wholeList += searchItems;
return subPrev;
}, { wholeList : "", subItems : []});
searchItem.searchKeys = searcKeyItems.wholeList;
searchItem.subItems = searcKeyItems.subItems;
delete searchItem.subItems.wholeList;
searchItem.key = key;
prev.push(searchItem);
return prev;
},[]);
console.log("result", result);
return result;
},
generateConfigsTable: function (configsData, id) {
id = id || "";
var first = true;
if (id != "") {
first = false;
}
var configsHTML = "";
if (!first)
configsHTML += "<table class='d-table help-zone-vb' cellpadding='0' cellspacing='0'>";
for (var i in configsData) {
if (typeof configsData[i] == "object") {
if (configsData[i] != null) {
var label = this.getInputLabel((id + "." + i).substring(1), i);
if (label) {
var display = i === this.selectedNav.key ? "block" : "none";
var category = "CORE";
var relatedNav = this.navTitles.coreTitles.find(function(x){ return x.key === i});
if(!relatedNav){
category = "PLUGINS";
relatedNav = this.navTitles.pluginTitles.find(function(x){ return x.key === i});
}
// configsHTML += "<tr id='config-table-row-" + i + "' style='display:" + display + "' class='config-table-row'><td>" + label + "</td><td>" + this.generateConfigsTable(configsData[i], id + "." + i) + "</td></tr>";
configsHTML += "<tr id='config-table-row-header-" + i + "' style='display:" + display + "' class='config-table-row-header'><td style='display:block'>" + category + " > " + relatedNav.label + "</td></tr>"
configsHTML += "<tr id='config-table-row-" + i + "' style='display:" + display + "' class='config-table-row'><td>" + this.generateConfigsTable(configsData[i], id + "." + i) + "</td></tr>";
}
}
else {
var input = this.getInputByType((id + "." + i).substring(1), "");
var label = this.getInputLabel((id + "." + i).substring(1), i);
if (input && label)
configsHTML += "<tr id='config-row-" + i + "-" + id.replace(".","") + "' class='config-table-details-row'><td style='padding:15px 20px'>" + label + "</td><td style='padding:15px 20px'>" + input + "</td></tr>";
}
}
else {
var input = this.getInputByType((id + "." + i).substring(1), configsData[i]);
var label = this.getInputLabel((id + "." + i).substring(1), i);
console.log("label",label)
if (input && label)
configsHTML += "<tr id='config-row-" + i + "-" + id.replace(".","") + "' class='config-table-details-row'><td style='padding:15px 20px'>" + label + "</td><td style='padding:15px 20px'>" + input + "</td></tr>";
}
}
if (!first)
configsHTML += "</table>";
return configsHTML;
},
getInputLabel: function (id, value) {
var ns = id.split(".")[0];
if (ns != "frontend" && ns != "api" && ns != "apps" && ns != "logs" && ns != "security" && countlyGlobal["plugins"].indexOf(ns) == -1) {
return null;
}
var ret = "";
if (jQuery.i18n.map["configs.help." + id])
ret = "<span class='config-help' data-localize='configs.help." + id + "'>" + jQuery.i18n.map["configs.help." + id] + "</span>";
else if (jQuery.i18n.map["configs.help." + id.replace(".", "-")])
ret = "<span class='config-help' data-localize='configs.help." + id.replace(".", "-") + "'>" + jQuery.i18n.map["configs.help." + id.replace(".", "-")] + "</span>";
if (typeof this.predefinedLabels[id] != "undefined")
return "<div data-localize='" + this.predefinedLabels[id] + "'>" + jQuery.i18n.map[this.predefinedLabels[id]] + "</div>" + ret;
else if (jQuery.i18n.map["configs." + id])
return "<div data-localize='configs." + id + "'>" + jQuery.i18n.map["configs." + id] + "</div>" + ret;
else if (jQuery.i18n.map["configs." + id.replace(".", "-")])
return "<div data-localize='configs." + id.replace(".", "-") + "'>" + jQuery.i18n.map["configs." + id.replace(".", "-")] + "</div>" + ret;
else if (jQuery.i18n.map[id])
return "<div data-localize='" + id + "'>" + jQuery.i18n.map[id] + "</div>" + ret;
else if (jQuery.i18n.map[id.replace(".", "-")])
return "<div data-localize='" + id.replace(".", "-") + "'>" + jQuery.i18n.map[id.replace(".", "-")] + "</div>" + ret;
else
return "<div>" + value + "</div>" + ret;
},
getInputByType: function (id, value) {
if (this.predefinedInputs[id]) {
return this.predefinedInputs[id](value);
}
else if (typeof value == "boolean") {
var input = '<div class="on-off-switch">';
if (value) {
input += '<input type="checkbox" name="on-off-switch" class="on-off-switch-checkbox" id="' + id + '" checked>';
} else {
input += '<input type="checkbox" name="on-off-switch" class="on-off-switch-checkbox" id="' + id + '">';
}
input += '<label class="on-off-switch-label" for="' + id + '"></label>';
input += '<span class="text">' + jQuery.i18n.map["plugins.enable"] + '</span>';
return input;
}
else if (typeof value == "number") {
return "<input type='number' id='" + id + "' value='" + value + "' max='99999999999999' oninput='this.value=this.value.substring(0,14);'/>";
}
else
return "<input type='text' id='" + id + "' value='" + value + "'/>";
},
getLabel: function (id) {
if (countlyGlobal["plugins"].indexOf(id) == -1)
return jQuery.i18n.map["configs." + id];
var ret = "";
if (jQuery.i18n.map["configs.help." + id])
ret = jQuery.i18n.map["configs.help." + id];
else if (jQuery.i18n.map["configs.help." + id.replace(".", "-")])
ret = jQuery.i18n.map["configs.help." + id.replace(".", "-")];
if (typeof this.predefinedLabels[id] != "undefined")
return jQuery.i18n.map[this.predefinedLabels[id]] + ret;
else if (jQuery.i18n.map["configs." + id])
return jQuery.i18n.map["configs." + id] + ret;
else if (jQuery.i18n.map["configs." + id.replace(".", "-")])
return jQuery.i18n.map["configs." + id.replace(".", "-")] + ret;
else if (jQuery.i18n.map[id])
return jQuery.i18n.map[id] + ret;
else if (jQuery.i18n.map[id.replace(".", "-")])
return jQuery.i18n.map[id.replace(".", "-")] + ret;
else
return id + ret;
},
setNavTitles: function (configdata) {
var plugins = countlyGlobal.plugins;
var pluginTitles = [], coreTitles = [];
var self = this;
Object.keys(configdata).forEach(function (key) {
if (plugins.indexOf(key) >= 0)
pluginTitles.push({ key: key, label: self.getLabel(key) });
else
coreTitles.push({ key: key, label: self.getLabel(key) });
});
coreTitles = coreTitles.sort(function (a, b) { return a > b; });
pluginTitles = pluginTitles.sort(function (a, b) { return a > b; });
return {
coreTitles: coreTitles,
pluginTitles: pluginTitles
}
},
showSearchResult: function(results){
$('.config-table-row-header').hide();
$('.config-table-row').hide();
$('.config-table-details-row').hide();
results.forEach(function(result){
$('#config-table-row-header-' + result.key).show();
$('#config-table-row-' + result.key).show();
result.rows.forEach(function(row){
$('#config-row-' + row.key + '-' + result.key).show();
})
})
},
registerInput: function (id, callback) {
this.predefinedInputs[id] = callback;
},
registerLabel: function (id, html) {
this.predefinedLabels[id] = html;
},
refresh: function () {
}
});
//register views
app.pluginsView = new PluginsView();
app.configurationsView = new ConfigurationsView();
if (countlyGlobal["member"].global_admin) {
app.route('/manage/plugins', 'plugins', function () {
this.renderWhenReady(this.pluginsView);
});
app.route('/manage/configurations', 'configurations', function () {
this.configurationsView.namespace = null;
this.configurationsView.reset = false;
this.configurationsView.userConfig = false;
this.configurationsView.success = false;
this.renderWhenReady(this.configurationsView);
});
app.route('/manage/configurations/:namespace', 'configurations_namespace', function (namespace) {
if (namespace == "reset") {
this.configurationsView.namespace = null;
this.configurationsView.reset = true;
this.configurationsView.userConfig = false;
this.configurationsView.success = false;
this.renderWhenReady(this.configurationsView);
}
else if (namespace == "success") {
this.configurationsView.namespace = null;
this.configurationsView.reset = false;
this.configurationsView.userConfig = false;
this.configurationsView.success = true;
this.renderWhenReady(this.configurationsView);
}
else {
this.configurationsView.namespace = namespace;
this.configurationsView.reset = false;
this.configurationsView.userConfig = false;
this.configurationsView.success = false;
this.renderWhenReady(this.configurationsView);
}
});
}
app.route('/manage/user-settings', 'user-settings', function () {
this.configurationsView.namespace = null;
this.configurationsView.reset = false;
this.configurationsView.userConfig = true;
this.configurationsView.success = false;
this.renderWhenReady(this.configurationsView);
});
app.route('/manage/user-settings/:namespace', 'user-settings_namespace', function (namespace) {
if (namespace == "reset") {
this.configurationsView.reset = true;
this.configurationsView.success = false;
this.configurationsView.namespace = null;
}
else {
this.configurationsView.reset = false;
this.configurationsView.success = false;
this.configurationsView.namespace = namespace;
}
this.configurationsView.userConfig = true;
this.renderWhenReady(this.configurationsView);
});
app.addPageScript("/manage/plugins", function () {
$("#plugins-selector").find(">.button").click(function () {
if ($(this).hasClass("selected")) {
return true;
}
$(".plugins-selector").removeClass("selected").removeClass("active");
var filter = $(this).attr("id");
app.activeView.filterPlugins(filter);
});
var plugins = _.clone(countlyGlobal["plugins"]);
$("#plugins-table").on("change", ".on-off-switch input", function () {
var $checkBox = $(this),
plugin = $checkBox.attr("id").replace(/^plugin-/, '');
if ($checkBox.is(":checked")) {
plugins.push(plugin);
plugins = _.uniq(plugins);
} else {
plugins = _.without(plugins, plugin);
}
if (_.difference(countlyGlobal["plugins"], plugins).length == 0 &&
_.difference(plugins, countlyGlobal["plugins"]).length == 0) {
$(".btn-plugin-enabler").hide();
} else {
$(".btn-plugin-enabler").show();
}
});
$(document).on("click", ".btn-plugin-enabler", function () {
var plugins = {};
$("#plugins-table").find(".on-off-switch input").each(function () {
var plugin = this.id.toString().replace(/^plugin-/, ''),
state = ($(this).is(":checked")) ? true : false;
plugins[plugin] = state;
});
var text = jQuery.i18n.map["plugins.confirm"];
var msg = { title: jQuery.i18n.map["plugins.processing"], message: jQuery.i18n.map["plugins.wait"], info: jQuery.i18n.map["plugins.hold-on"], sticky: true };
CountlyHelpers.confirm(text, "red", function (result) {
if (!result) {
return true;
}
CountlyHelpers.notify(msg);
app.activeView.togglePlugin(plugins);
});
});
});
$(document).ready(function () {
if (countlyGlobal["member"] && countlyGlobal["member"]["global_admin"]) {
var menu = '<a href="#/manage/plugins" class="item">' +
'<div class="logo-icon fa fa-puzzle-piece"></div>' +
'<div class="text" data-localize="plugins.title"></div>' +
'</a>';
if ($('#management-submenu .help-toggle').length)
$('#management-submenu .help-toggle').before(menu);
var menu = '<a href="#/manage/configurations" class="item">' +
'<div class="logo-icon fa fa-wrench"></div>' +
'<div class="text" data-localize="plugins.configs"></div>' +
'</a>';
if ($('#management-submenu .help-toggle').length)
$('#management-submenu .help-toggle').before(menu);
}
}); | 1 | 12,900 | Let's put this back | Countly-countly-server | js |
@@ -122,9 +122,9 @@ bool Mailbox::sendItem(Item* item) const
}
} else {
Player tmpPlayer(nullptr);
- if (!IOLoginData::loadPlayerByName(&tmpPlayer, receiver)) {
+ //if (!IOLoginData::loadPlayerByName(&tmpPlayer, receiver)) {
return false;
- }
+ //}
if (g_game.internalMoveItem(item->getParent(), tmpPlayer.getInbox(), INDEX_WHEREEVER,
item, item->getItemCount(), nullptr, FLAG_NOLIMIT) == RET_NOERROR) { | 1 | /**
* The Forgotten Server - a free and open-source MMORPG server emulator
* Copyright (C) 2014 Mark Samman <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "otpch.h"
#include "mailbox.h"
#include "game.h"
#include "player.h"
#include "iologindata.h"
#include "town.h"
extern Game g_game;
Mailbox::Mailbox(uint16_t _type) : Item(_type)
{
//
}
Mailbox::~Mailbox()
{
//
}
ReturnValue Mailbox::__queryAdd(int32_t, const Thing* thing, uint32_t, uint32_t, Creature*) const
{
const Item* item = thing->getItem();
if (item && Mailbox::canSend(item)) {
return RET_NOERROR;
}
return RET_NOTPOSSIBLE;
}
ReturnValue Mailbox::__queryMaxCount(int32_t, const Thing*, uint32_t count, uint32_t& maxQueryCount, uint32_t) const
{
maxQueryCount = std::max<uint32_t>(1, count);
return RET_NOERROR;
}
ReturnValue Mailbox::__queryRemove(const Thing*, uint32_t, uint32_t) const
{
return RET_NOTPOSSIBLE;
}
Cylinder* Mailbox::__queryDestination(int32_t&, const Thing*, Item**, uint32_t&)
{
return this;
}
void Mailbox::__addThing(Thing* thing)
{
return __addThing(0, thing);
}
void Mailbox::__addThing(int32_t, Thing* thing)
{
Item* item = thing->getItem();
if (item && Mailbox::canSend(item)) {
sendItem(item);
}
}
void Mailbox::__updateThing(Thing*, uint16_t, uint32_t)
{
//
}
void Mailbox::__replaceThing(uint32_t, Thing*)
{
//
}
void Mailbox::__removeThing(Thing*, uint32_t)
{
//
}
void Mailbox::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, cylinderlink_t)
{
getParent()->postAddNotification(thing, oldParent, index, LINK_PARENT);
}
void Mailbox::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, bool isCompleteRemoval, cylinderlink_t)
{
getParent()->postRemoveNotification(thing, newParent, index, isCompleteRemoval, LINK_PARENT);
}
bool Mailbox::sendItem(Item* item) const
{
std::string receiver;
if (!getReceiver(item, receiver)) {
return false;
}
/**No need to continue if its still empty**/
if (receiver.empty()) {
return false;
}
Player* player = g_game.getPlayerByName(receiver);
if (player) {
if (g_game.internalMoveItem(item->getParent(), player->getInbox(), INDEX_WHEREEVER,
item, item->getItemCount(), nullptr, FLAG_NOLIMIT) == RET_NOERROR) {
g_game.transformItem(item, item->getID() + 1);
player->onReceiveMail();
return true;
}
} else {
Player tmpPlayer(nullptr);
if (!IOLoginData::loadPlayerByName(&tmpPlayer, receiver)) {
return false;
}
if (g_game.internalMoveItem(item->getParent(), tmpPlayer.getInbox(), INDEX_WHEREEVER,
item, item->getItemCount(), nullptr, FLAG_NOLIMIT) == RET_NOERROR) {
g_game.transformItem(item, item->getID() + 1);
IOLoginData::savePlayer(&tmpPlayer);
return true;
}
}
return false;
}
bool Mailbox::getReceiver(Item* item, std::string& name) const
{
const Container* container = item->getContainer();
if (container) {
for (Item* containerItem : container->getItemList()) {
if (containerItem->getID() == ITEM_LABEL && getReceiver(containerItem, name)) {
return true;
}
}
return false;
}
const std::string& text = item->getText();
if (text.empty()) {
return false;
}
name = getFirstLine(text);
trimString(name);
return true;
}
bool Mailbox::canSend(const Item* item)
{
return item->getID() == ITEM_PARCEL || item->getID() == ITEM_LETTER;
}
| 1 | 10,130 | Things like these should have been addressed before submitting a pull request. | otland-forgottenserver | cpp |
@@ -77,7 +77,7 @@ public class ITZipkinMetrics {
// ensure we don't track prometheus, UI requests in prometheus
assertThat(scrape())
- .doesNotContain("prometheus")
+ .doesNotContain("prometheus_notifications")
.doesNotContain("uri=\"/zipkin")
.doesNotContain("uri=\"/\"");
} | 1 | /*
* Copyright 2015-2019 The OpenZipkin Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package zipkin2.server.internal.prometheus;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.linecorp.armeria.server.Server;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import zipkin.server.ZipkinServer;
import zipkin2.Span;
import zipkin2.codec.SpanBytesEncoder;
import zipkin2.storage.InMemoryStorage;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static zipkin2.TestObjects.LOTS_OF_SPANS;
import static zipkin2.server.internal.ITZipkinServer.url;
@SpringBootTest(
classes = ZipkinServer.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE, // RANDOM_PORT requires spring-web
properties = {
"server.port=0",
"spring.config.name=zipkin-server"
}
)
@RunWith(SpringRunner.class)
public class ITZipkinMetrics {
@Autowired InMemoryStorage storage;
@Autowired PrometheusMeterRegistry registry;
@Autowired Server server;
OkHttpClient client = new OkHttpClient.Builder().followRedirects(true).build();
@Before public void init() {
storage.clear();
}
@Test public void metricsIsOK() throws Exception {
assertThat(get("/metrics").isSuccessful())
.isTrue();
// ensure we don't track metrics in prometheus
assertThat(scrape())
.doesNotContain("metrics");
}
@Test public void prometheusIsOK() throws Exception {
assertThat(get("/prometheus").isSuccessful())
.isTrue();
// ensure we don't track prometheus, UI requests in prometheus
assertThat(scrape())
.doesNotContain("prometheus")
.doesNotContain("uri=\"/zipkin")
.doesNotContain("uri=\"/\"");
}
@Test public void apiTemplate_prometheus() throws Exception {
List<Span> spans = asList(LOTS_OF_SPANS[0]);
byte[] body = SpanBytesEncoder.JSON_V2.encodeList(spans);
assertThat(post("/api/v2/spans", body).isSuccessful())
.isTrue();
assertThat(get("/api/v2/trace/" + LOTS_OF_SPANS[0].traceId()).isSuccessful())
.isTrue();
assertThat(get("/api/v2/traceMany?traceIds=abcde," + LOTS_OF_SPANS[0].traceId()).isSuccessful())
.isTrue();
assertThat(scrape())
.contains("uri=\"/api/v2/traceMany\"") // sanity check
.contains("uri=\"/api/v2/trace/{traceId}\"")
.doesNotContain(LOTS_OF_SPANS[0].traceId());
}
@Test public void forwardedRoute_prometheus() throws Exception {
assertThat(get("/zipkin/api/v2/services").isSuccessful())
.isTrue();
assertThat(scrape())
.contains("uri=\"/api/v2/services\"")
.doesNotContain("uri=\"/zipkin/api/v2/services\"");
}
@Test public void jvmMetrics_prometheus() throws Exception {
assertThat(scrape())
.contains("jvm_memory_max_bytes")
.contains("jvm_memory_used_bytes")
.contains("jvm_memory_committed_bytes")
.contains("jvm_buffer_count_buffers")
.contains("jvm_buffer_memory_used_bytes")
.contains("jvm_buffer_total_capacity_bytes")
.contains("jvm_classes_loaded_classes")
.contains("jvm_classes_unloaded_classes_total")
.contains("jvm_threads_live_threads")
.contains("jvm_threads_states_threads")
.contains("jvm_threads_peak_threads")
.contains("jvm_threads_daemon_threads");
// gc metrics are not tested as are not present during test running
}
String scrape() throws InterruptedException {
Thread.sleep(100);
return registry.scrape();
}
/**
* Makes sure the prometheus filter doesn't count twice
*/
@Test public void writeSpans_updatesPrometheusMetrics() throws Exception {
List<Span> spans = asList(LOTS_OF_SPANS[0], LOTS_OF_SPANS[1], LOTS_OF_SPANS[2]);
byte[] body = SpanBytesEncoder.JSON_V2.encodeList(spans);
post("/api/v2/spans", body);
post("/api/v2/spans", body);
Thread.sleep(100); // sometimes travis flakes getting the "http.server.requests" timer
double messagesCount = registry.counter("zipkin_collector.spans", "transport", "http").count();
// Get the http count from the registry and it should match the summation previous count
// and count of calls below
long httpCount = registry
.find("http.server.requests")
.tag("uri", "/api/v2/spans")
.timer()
.count();
// ensure unscoped counter does not exist
assertThat(scrape())
.doesNotContain("zipkin_collector_spans_total " + messagesCount)
.contains("zipkin_collector_spans_total{transport=\"http\",} " + messagesCount)
.contains(
"http_server_requests_seconds_count{method=\"POST\",status=\"202\",uri=\"/api/v2/spans\",} "
+ httpCount);
}
@Test public void writesSpans_readMetricsFormat() throws Exception {
byte[] span = {'z', 'i', 'p', 'k', 'i', 'n'};
List<Span> spans = asList(LOTS_OF_SPANS[0], LOTS_OF_SPANS[1], LOTS_OF_SPANS[2]);
byte[] body = SpanBytesEncoder.JSON_V2.encodeList(spans);
post("/api/v2/spans", body);
post("/api/v2/spans", body);
post("/api/v2/spans", span);
Thread.sleep(1500);
String metrics = getAsString("/metrics");
assertThat(readJson(metrics)).containsOnlyKeys(
"gauge.zipkin_collector.message_spans.http"
, "gauge.zipkin_collector.message_bytes.http"
, "counter.zipkin_collector.messages.http"
, "counter.zipkin_collector.bytes.http"
, "counter.zipkin_collector.spans.http"
, "counter.zipkin_collector.messages_dropped.http"
, "counter.zipkin_collector.spans_dropped.http"
);
}
private String getAsString(String path) throws IOException {
Response response = get(path);
assertThat(response.isSuccessful())
.withFailMessage(response.toString())
.isTrue();
return response.body().string();
}
private Response get(String path) throws IOException {
return client.newCall(new Request.Builder().url(url(server, path)).build()).execute();
}
private Response post(String path, byte[] body) throws IOException {
return client.newCall(new Request.Builder()
.url(url(server, path))
.post(RequestBody.create(body))
.build()).execute();
}
static Map<String, Integer> readJson(String json) throws Exception {
Map<String, Integer> result = new LinkedHashMap<>();
JsonParser parser = new JsonFactory().createParser(json);
assertThat(parser.nextToken()).isEqualTo(JsonToken.START_OBJECT);
String nextField;
while ((nextField = parser.nextFieldName()) != null) {
result.put(nextField, parser.nextIntValue(0));
}
return result;
}
}
| 1 | 16,960 | This one as well. Any better suggestion please? | openzipkin-zipkin | java |
@@ -267,6 +267,11 @@ func (s *Server) internalSendLoop(wg *sync.WaitGroup) {
c.pa.reply = []byte(pm.rply)
c.mu.Unlock()
+ if c.trace {
+ c.traceInOp(fmt.Sprintf(
+ "PUB %s %s %d", c.pa.subject, c.pa.reply, c.pa.size), nil)
+ }
+
// Add in NL
b = append(b, _CRLF_...)
c.processInboundClientMsg(b) | 1 | // Copyright 2018-2019 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bytes"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"math/rand"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nats-io/nats-server/v2/server/pse"
)
const (
connectEventSubj = "$SYS.ACCOUNT.%s.CONNECT"
disconnectEventSubj = "$SYS.ACCOUNT.%s.DISCONNECT"
accConnsReqSubj = "$SYS.REQ.ACCOUNT.%s.CONNS"
accUpdateEventSubj = "$SYS.ACCOUNT.%s.CLAIMS.UPDATE"
connsRespSubj = "$SYS._INBOX_.%s"
accConnsEventSubj = "$SYS.SERVER.ACCOUNT.%s.CONNS"
shutdownEventSubj = "$SYS.SERVER.%s.SHUTDOWN"
authErrorEventSubj = "$SYS.SERVER.%s.CLIENT.AUTH.ERR"
serverStatsSubj = "$SYS.SERVER.%s.STATSZ"
serverStatsReqSubj = "$SYS.REQ.SERVER.%s.STATSZ"
serverStatsPingReqSubj = "$SYS.REQ.SERVER.PING"
leafNodeConnectEventSubj = "$SYS.ACCOUNT.%s.LEAFNODE.CONNECT"
remoteLatencyEventSubj = "$SYS.LATENCY.M2.%s"
inboxRespSubj = "$SYS._INBOX.%s.%s"
// FIXME(dlc) - Should account scope, even with wc for now, but later on
// we can then shard as needed.
accNumSubsReqSubj = "$SYS.REQ.ACCOUNT.NSUBS"
// These are for exported debug services. These are local to this server only.
accSubsSubj = "$SYS.DEBUG.SUBSCRIBERS"
shutdownEventTokens = 4
serverSubjectIndex = 2
accUpdateTokens = 5
accUpdateAccIndex = 2
)
// FIXME(dlc) - make configurable.
var eventsHBInterval = 30 * time.Second
// Used to send and receive messages from inside the server.
type internal struct {
account *Account
client *client
seq uint64
sid uint64
servers map[string]*serverUpdate
sweeper *time.Timer
stmr *time.Timer
subs map[string]msgHandler
replies map[string]msgHandler
sendq chan *pubMsg
wg sync.WaitGroup
orphMax time.Duration
chkOrph time.Duration
statsz time.Duration
shash string
inboxPre string
}
// ServerStatsMsg is sent periodically with stats updates.
type ServerStatsMsg struct {
Server ServerInfo `json:"server"`
Stats ServerStats `json:"statsz"`
}
// ConnectEventMsg is sent when a new connection is made that is part of an account.
type ConnectEventMsg struct {
Server ServerInfo `json:"server"`
Client ClientInfo `json:"client"`
}
// DisconnectEventMsg is sent when a new connection previously defined from a
// ConnectEventMsg is closed.
type DisconnectEventMsg struct {
Server ServerInfo `json:"server"`
Client ClientInfo `json:"client"`
Sent DataStats `json:"sent"`
Received DataStats `json:"received"`
Reason string `json:"reason"`
}
// AccountNumConns is an event that will be sent from a server that is tracking
// a given account when the number of connections changes. It will also HB
// updates in the absence of any changes.
type AccountNumConns struct {
Server ServerInfo `json:"server"`
Account string `json:"acc"`
Conns int `json:"conns"`
LeafNodes int `json:"leafnodes"`
TotalConns int `json:"total_conns"`
}
// accNumConnsReq is sent when we are starting to track an account for the first
// time. We will request others send info to us about their local state.
type accNumConnsReq struct {
Server ServerInfo `json:"server"`
Account string `json:"acc"`
}
// ServerInfo identifies remote servers.
type ServerInfo struct {
Name string `json:"name"`
Host string `json:"host"`
ID string `json:"id"`
Cluster string `json:"cluster,omitempty"`
Version string `json:"ver"`
Seq uint64 `json:"seq"`
Time time.Time `json:"time"`
}
// ClientInfo is detailed information about the client forming a connection.
type ClientInfo struct {
Start time.Time `json:"start,omitempty"`
Host string `json:"host,omitempty"`
ID uint64 `json:"id"`
Account string `json:"acc"`
User string `json:"user,omitempty"`
Name string `json:"name,omitempty"`
Lang string `json:"lang,omitempty"`
Version string `json:"ver,omitempty"`
RTT string `json:"rtt,omitempty"`
Stop *time.Time `json:"stop,omitempty"`
}
// ServerStats hold various statistics that we will periodically send out.
type ServerStats struct {
Start time.Time `json:"start"`
Mem int64 `json:"mem"`
Cores int `json:"cores"`
CPU float64 `json:"cpu"`
Connections int `json:"connections"`
TotalConnections uint64 `json:"total_connections"`
ActiveAccounts int `json:"active_accounts"`
NumSubs uint32 `json:"subscriptions"`
Sent DataStats `json:"sent"`
Received DataStats `json:"received"`
SlowConsumers int64 `json:"slow_consumers"`
Routes []*RouteStat `json:"routes,omitempty"`
Gateways []*GatewayStat `json:"gateways,omitempty"`
}
// RouteStat holds route statistics.
type RouteStat struct {
ID uint64 `json:"rid"`
Name string `json:"name,omitempty"`
Sent DataStats `json:"sent"`
Received DataStats `json:"received"`
Pending int `json:"pending"`
}
// GatewayStat holds gateway statistics.
type GatewayStat struct {
ID uint64 `json:"gwid"`
Name string `json:"name"`
Sent DataStats `json:"sent"`
Received DataStats `json:"received"`
NumInbound int `json:"inbound_connections"`
}
// DataStats reports how may msg and bytes. Applicable for both sent and received.
type DataStats struct {
Msgs int64 `json:"msgs"`
Bytes int64 `json:"bytes"`
}
// Used for internally queueing up messages that the server wants to send.
type pubMsg struct {
acc *Account
sub string
rply string
si *ServerInfo
msg interface{}
last bool
}
// Used to track server updates.
type serverUpdate struct {
seq uint64
ltime time.Time
}
// internalSendLoop will be responsible for serializing all messages that
// a server wants to send.
func (s *Server) internalSendLoop(wg *sync.WaitGroup) {
defer wg.Done()
s.mu.Lock()
if s.sys == nil || s.sys.sendq == nil {
s.mu.Unlock()
return
}
c := s.sys.client
sysacc := s.sys.account
sendq := s.sys.sendq
id := s.info.ID
host := s.info.Host
servername := s.info.Name
seqp := &s.sys.seq
var cluster string
if s.gateway.enabled {
cluster = s.getGatewayName()
}
s.mu.Unlock()
// Warn when internal send queue is backed up past 75%
warnThresh := 3 * internalSendQLen / 4
warnFreq := time.Second
last := time.Now().Add(-warnFreq)
for s.eventsRunning() {
// Setup information for next message
if len(sendq) > warnThresh && time.Since(last) >= warnFreq {
s.Warnf("Internal system send queue > 75%%")
last = time.Now()
}
select {
case pm := <-sendq:
if pm.si != nil {
pm.si.Name = servername
pm.si.Host = host
pm.si.Cluster = cluster
pm.si.ID = id
pm.si.Seq = atomic.AddUint64(seqp, 1)
pm.si.Version = VERSION
pm.si.Time = time.Now()
}
var b []byte
if pm.msg != nil {
b, _ = json.MarshalIndent(pm.msg, _EMPTY_, " ")
}
c.mu.Lock()
// We can have an override for account here.
if pm.acc != nil {
c.acc = pm.acc
} else {
c.acc = sysacc
}
// Prep internal structures needed to send message.
c.pa.subject = []byte(pm.sub)
c.pa.size = len(b)
c.pa.szb = []byte(strconv.FormatInt(int64(len(b)), 10))
c.pa.reply = []byte(pm.rply)
c.mu.Unlock()
// Add in NL
b = append(b, _CRLF_...)
c.processInboundClientMsg(b)
// See if we are doing graceful shutdown.
if !pm.last {
c.flushClients(0) // Never spend time in place.
} else {
// For the Shutdown event, we need to send in place otherwise
// there is a chance that the process will exit before the
// writeLoop has a chance to send it.
c.flushClients(time.Second)
return
}
case <-s.quitCh:
return
}
}
}
// Will send a shutdown message.
func (s *Server) sendShutdownEvent() {
s.mu.Lock()
if s.sys == nil || s.sys.sendq == nil {
s.mu.Unlock()
return
}
subj := fmt.Sprintf(shutdownEventSubj, s.info.ID)
sendq := s.sys.sendq
// Stop any more messages from queueing up.
s.sys.sendq = nil
// Unhook all msgHandlers. Normal client cleanup will deal with subs, etc.
s.sys.subs = nil
s.sys.replies = nil
s.mu.Unlock()
// Send to the internal queue and mark as last.
sendq <- &pubMsg{nil, subj, _EMPTY_, nil, nil, true}
}
// Used to send an internal message to an arbitrary account.
func (s *Server) sendInternalAccountMsg(a *Account, subject string, msg interface{}) error {
s.mu.Lock()
if s.sys == nil || s.sys.sendq == nil {
s.mu.Unlock()
return ErrNoSysAccount
}
sendq := s.sys.sendq
// Don't hold lock while placing on the channel.
s.mu.Unlock()
sendq <- &pubMsg{a, subject, "", nil, msg, false}
return nil
}
// This will queue up a message to be sent.
// Lock should not be held.
func (s *Server) sendInternalMsgLocked(sub, rply string, si *ServerInfo, msg interface{}) {
s.mu.Lock()
s.sendInternalMsg(sub, rply, si, msg)
s.mu.Unlock()
}
// This will queue up a message to be sent.
// Assumes lock is held on entry.
func (s *Server) sendInternalMsg(sub, rply string, si *ServerInfo, msg interface{}) {
if s.sys == nil || s.sys.sendq == nil {
return
}
sendq := s.sys.sendq
// Don't hold lock while placing on the channel.
s.mu.Unlock()
sendq <- &pubMsg{nil, sub, rply, si, msg, false}
s.mu.Lock()
}
// Locked version of checking if events system running. Also checks server.
func (s *Server) eventsRunning() bool {
s.mu.Lock()
er := s.running && s.eventsEnabled()
s.mu.Unlock()
return er
}
// EventsEnabled will report if the server has internal events enabled via
// a defined system account.
func (s *Server) EventsEnabled() bool {
s.mu.Lock()
ee := s.eventsEnabled()
s.mu.Unlock()
return ee
}
// eventsEnabled will report if events are enabled.
// Lock should be held.
func (s *Server) eventsEnabled() bool {
return s.sys != nil && s.sys.client != nil && s.sys.account != nil
}
// TrackedRemoteServers returns how many remote servers we are tracking
// from a system events perspective.
func (s *Server) TrackedRemoteServers() int {
s.mu.Lock()
if !s.running || !s.eventsEnabled() {
return -1
}
ns := len(s.sys.servers)
s.mu.Unlock()
return ns
}
// Check for orphan servers who may have gone away without notification.
// This should be wrapChk() to setup common locking.
func (s *Server) checkRemoteServers() {
now := time.Now()
for sid, su := range s.sys.servers {
if now.Sub(su.ltime) > s.sys.orphMax {
s.Debugf("Detected orphan remote server: %q", sid)
// Simulate it going away.
s.processRemoteServerShutdown(sid)
delete(s.sys.servers, sid)
}
}
if s.sys.sweeper != nil {
s.sys.sweeper.Reset(s.sys.chkOrph)
}
}
// Grab RSS and PCPU
func updateServerUsage(v *ServerStats) {
var rss, vss int64
var pcpu float64
pse.ProcUsage(&pcpu, &rss, &vss)
v.Mem = rss
v.CPU = pcpu
v.Cores = numCores
}
// Generate a route stat for our statz update.
func routeStat(r *client) *RouteStat {
if r == nil {
return nil
}
r.mu.Lock()
rs := &RouteStat{
ID: r.cid,
Sent: DataStats{
Msgs: atomic.LoadInt64(&r.outMsgs),
Bytes: atomic.LoadInt64(&r.outBytes),
},
Received: DataStats{
Msgs: atomic.LoadInt64(&r.inMsgs),
Bytes: atomic.LoadInt64(&r.inBytes),
},
Pending: int(r.out.pb),
}
if r.route != nil {
rs.Name = r.route.remoteName
}
r.mu.Unlock()
return rs
}
// Actual send method for statz updates.
// Lock should be held.
func (s *Server) sendStatsz(subj string) {
m := ServerStatsMsg{}
updateServerUsage(&m.Stats)
m.Stats.Start = s.start
m.Stats.Connections = len(s.clients)
m.Stats.TotalConnections = s.totalClients
m.Stats.ActiveAccounts = int(atomic.LoadInt32(&s.activeAccounts))
m.Stats.Received.Msgs = atomic.LoadInt64(&s.inMsgs)
m.Stats.Received.Bytes = atomic.LoadInt64(&s.inBytes)
m.Stats.Sent.Msgs = atomic.LoadInt64(&s.outMsgs)
m.Stats.Sent.Bytes = atomic.LoadInt64(&s.outBytes)
m.Stats.SlowConsumers = atomic.LoadInt64(&s.slowConsumers)
m.Stats.NumSubs = s.numSubscriptions()
for _, r := range s.routes {
m.Stats.Routes = append(m.Stats.Routes, routeStat(r))
}
if s.gateway.enabled {
gw := s.gateway
gw.RLock()
for name, c := range gw.out {
gs := &GatewayStat{Name: name}
c.mu.Lock()
gs.ID = c.cid
gs.Sent = DataStats{
Msgs: atomic.LoadInt64(&c.outMsgs),
Bytes: atomic.LoadInt64(&c.outBytes),
}
c.mu.Unlock()
// Gather matching inbound connections
gs.Received = DataStats{}
for _, c := range gw.in {
c.mu.Lock()
if c.gw.name == name {
gs.Received.Msgs += atomic.LoadInt64(&c.inMsgs)
gs.Received.Bytes += atomic.LoadInt64(&c.inBytes)
gs.NumInbound++
}
c.mu.Unlock()
}
m.Stats.Gateways = append(m.Stats.Gateways, gs)
}
gw.RUnlock()
}
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
}
// Send out our statz update.
// This should be wrapChk() to setup common locking.
func (s *Server) heartbeatStatsz() {
if s.sys.stmr != nil {
s.sys.stmr.Reset(s.sys.statsz)
}
s.sendStatsz(fmt.Sprintf(serverStatsSubj, s.info.ID))
}
// This should be wrapChk() to setup common locking.
func (s *Server) startStatszTimer() {
s.sys.stmr = time.AfterFunc(s.sys.statsz, s.wrapChk(s.heartbeatStatsz))
}
// Start a ticker that will fire periodically and check for orphaned servers.
// This should be wrapChk() to setup common locking.
func (s *Server) startRemoteServerSweepTimer() {
s.sys.sweeper = time.AfterFunc(s.sys.chkOrph, s.wrapChk(s.checkRemoteServers))
}
// Length of our system hash used for server targeted messages.
const sysHashLen = 6
// This will setup our system wide tracking subs.
// For now we will setup one wildcard subscription to
// monitor all accounts for changes in number of connections.
// We can make this on a per account tracking basis if needed.
// Tradeoff is subscription and interest graph events vs connect and
// disconnect events, etc.
func (s *Server) initEventTracking() {
if !s.eventsEnabled() {
return
}
// Create a system hash which we use for other servers to target us specifically.
sha := sha256.New()
sha.Write([]byte(s.info.ID))
s.sys.shash = base64.RawURLEncoding.EncodeToString(sha.Sum(nil))[:sysHashLen]
// This will be for all inbox responses.
subject := fmt.Sprintf(inboxRespSubj, s.sys.shash, "*")
if _, err := s.sysSubscribe(subject, s.inboxReply); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
s.sys.inboxPre = subject
// This is for remote updates for connection accounting.
subject = fmt.Sprintf(accConnsEventSubj, "*")
if _, err := s.sysSubscribe(subject, s.remoteConnsUpdate); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// This will be for responses for account info that we send out.
subject = fmt.Sprintf(connsRespSubj, s.info.ID)
if _, err := s.sysSubscribe(subject, s.remoteConnsUpdate); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for broad requests to respond with account info.
subject = fmt.Sprintf(accConnsReqSubj, "*")
if _, err := s.sysSubscribe(subject, s.connsRequest); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for broad requests to respond with number of subscriptions for a given subject.
if _, err := s.sysSubscribe(accNumSubsReqSubj, s.nsubsRequest); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for all server shutdowns.
subject = fmt.Sprintf(shutdownEventSubj, "*")
if _, err := s.sysSubscribe(subject, s.remoteServerShutdown); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for account claims updates.
subject = fmt.Sprintf(accUpdateEventSubj, "*")
if _, err := s.sysSubscribe(subject, s.accountClaimUpdate); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for requests for our statsz.
subject = fmt.Sprintf(serverStatsReqSubj, s.info.ID)
if _, err := s.sysSubscribe(subject, s.statszReq); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for ping messages that will be sent to all servers for statsz.
if _, err := s.sysSubscribe(serverStatsPingReqSubj, s.statszReq); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for updates when leaf nodes connect for a given account. This will
// force any gateway connections to move to `modeInterestOnly`
subject = fmt.Sprintf(leafNodeConnectEventSubj, "*")
if _, err := s.sysSubscribe(subject, s.leafNodeConnected); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// For tracking remote latency measurements.
subject = fmt.Sprintf(remoteLatencyEventSubj, s.sys.shash)
if _, err := s.sysSubscribe(subject, s.remoteLatencyUpdate); err != nil {
s.Errorf("Error setting up internal latency tracking: %v", err)
}
// These are for system account exports for debugging from client applications.
sacc := s.sys.account
// This is for simple debugging of number of subscribers that exist in the system.
if _, err := s.sysSubscribeInternal(accSubsSubj, s.debugSubscribers); err != nil {
s.Errorf("Error setting up internal debug service for subscribers: %v", err)
}
if err := sacc.AddServiceExport(accSubsSubj, nil); err != nil {
s.Errorf("Error adding system service export for %q: %v", accSubsSubj, err)
}
}
// accountClaimUpdate will receive claim updates for accounts.
func (s *Server) accountClaimUpdate(sub *subscription, _ *client, subject, reply string, msg []byte) {
if !s.EventsEnabled() {
return
}
toks := strings.Split(subject, tsep)
if len(toks) < accUpdateTokens {
s.Debugf("Received account claims update on bad subject %q", subject)
return
}
if v, ok := s.accounts.Load(toks[accUpdateAccIndex]); ok {
s.updateAccountWithClaimJWT(v.(*Account), string(msg))
}
}
// processRemoteServerShutdown will update any affected accounts.
// Will update the remote count for clients.
// Lock assume held.
func (s *Server) processRemoteServerShutdown(sid string) {
s.accounts.Range(func(k, v interface{}) bool {
v.(*Account).removeRemoteServer(sid)
return true
})
}
// remoteServerShutdownEvent is called when we get an event from another server shutting down.
func (s *Server) remoteServerShutdown(sub *subscription, _ *client, subject, reply string, msg []byte) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() {
return
}
toks := strings.Split(subject, tsep)
if len(toks) < shutdownEventTokens {
s.Debugf("Received remote server shutdown on bad subject %q", subject)
return
}
sid := toks[serverSubjectIndex]
su := s.sys.servers[sid]
if su != nil {
s.processRemoteServerShutdown(sid)
}
}
// updateRemoteServer is called when we have an update from a remote server.
// This allows us to track remote servers, respond to shutdown messages properly,
// make sure that messages are ordered, and allow us to prune dead servers.
// Lock should be held upon entry.
func (s *Server) updateRemoteServer(ms *ServerInfo) {
su := s.sys.servers[ms.ID]
if su == nil {
s.sys.servers[ms.ID] = &serverUpdate{ms.Seq, time.Now()}
} else {
// Should always be going up.
if ms.Seq <= su.seq {
s.Errorf("Received out of order remote server update from: %q", ms.ID)
return
}
su.seq = ms.Seq
su.ltime = time.Now()
}
}
// shutdownEventing will clean up all eventing state.
func (s *Server) shutdownEventing() {
if !s.eventsRunning() {
return
}
s.mu.Lock()
clearTimer(&s.sys.sweeper)
clearTimer(&s.sys.stmr)
s.mu.Unlock()
// We will queue up a shutdown event and wait for the
// internal send loop to exit.
s.sendShutdownEvent()
s.sys.wg.Wait()
s.mu.Lock()
defer s.mu.Unlock()
// Whip through all accounts.
s.accounts.Range(func(k, v interface{}) bool {
v.(*Account).clearEventing()
return true
})
// Turn everything off here.
s.sys = nil
}
// Request for our local connection count.
func (s *Server) connsRequest(sub *subscription, _ *client, subject, reply string, msg []byte) {
if !s.eventsRunning() {
return
}
m := accNumConnsReq{}
if err := json.Unmarshal(msg, &m); err != nil {
s.sys.client.Errorf("Error unmarshalling account connections request message: %v", err)
return
}
// Here we really only want to lookup the account if its local. We do not want to fetch this
// account if we have no interest in it.
var acc *Account
if v, ok := s.accounts.Load(m.Account); ok {
acc = v.(*Account)
}
if acc == nil {
return
}
// We know this is a local connection.
if nlc := acc.NumLocalConnections(); nlc > 0 {
s.mu.Lock()
s.sendAccConnsUpdate(acc, reply)
s.mu.Unlock()
}
}
// leafNodeConnected is an event we will receive when a leaf node for a given account
// connects.
func (s *Server) leafNodeConnected(sub *subscription, _ *client, subject, reply string, msg []byte) {
m := accNumConnsReq{}
if err := json.Unmarshal(msg, &m); err != nil {
s.sys.client.Errorf("Error unmarshalling account connections request message: %v", err)
return
}
s.mu.Lock()
na := m.Account == "" || !s.eventsEnabled() || !s.gateway.enabled
s.mu.Unlock()
if na {
return
}
if acc, _ := s.lookupAccount(m.Account); acc != nil {
s.switchAccountToInterestMode(acc.Name)
}
}
// statszReq is a request for us to respond with current statz.
func (s *Server) statszReq(sub *subscription, _ *client, subject, reply string, msg []byte) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() || reply == _EMPTY_ {
return
}
s.sendStatsz(reply)
}
// remoteConnsUpdate gets called when we receive a remote update from another server.
func (s *Server) remoteConnsUpdate(sub *subscription, _ *client, subject, reply string, msg []byte) {
if !s.eventsRunning() {
return
}
m := AccountNumConns{}
if err := json.Unmarshal(msg, &m); err != nil {
s.sys.client.Errorf("Error unmarshalling account connection event message: %v", err)
return
}
// See if we have the account registered, if not drop it.
// Make sure this does not force us to load this account here.
var acc *Account
if v, ok := s.accounts.Load(m.Account); ok {
acc = v.(*Account)
}
// Silently ignore these if we do not have local interest in the account.
if acc == nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
// check again here if we have been shutdown.
if !s.running || !s.eventsEnabled() {
return
}
// Double check that this is not us, should never happen, so error if it does.
if m.Server.ID == s.info.ID {
s.sys.client.Errorf("Processing our own account connection event message: ignored")
return
}
// If we are here we have interest in tracking this account. Update our accounting.
acc.updateRemoteServer(&m)
s.updateRemoteServer(&m.Server)
}
// Setup tracking for this account. This allows us to track global account activity.
// Lock should be held on entry.
func (s *Server) enableAccountTracking(a *Account) {
if a == nil || !s.eventsEnabled() {
return
}
// TODO(ik): Generate payload although message may not be sent.
// May need to ensure we do so only if there is a known interest.
// This can get complicated with gateways.
subj := fmt.Sprintf(accConnsReqSubj, a.Name)
reply := fmt.Sprintf(connsRespSubj, s.info.ID)
m := accNumConnsReq{Account: a.Name}
s.sendInternalMsg(subj, reply, &m.Server, &m)
}
// Event on leaf node connect.
// Lock should NOT be held on entry.
func (s *Server) sendLeafNodeConnect(a *Account) {
s.mu.Lock()
// If we are not in operator mode, or do not have any gateways defined, this should also be a no-op.
if a == nil || !s.eventsEnabled() || !s.gateway.enabled {
s.mu.Unlock()
return
}
subj := fmt.Sprintf(leafNodeConnectEventSubj, a.Name)
m := accNumConnsReq{Account: a.Name}
s.sendInternalMsg(subj, "", &m.Server, &m)
s.mu.Unlock()
s.switchAccountToInterestMode(a.Name)
}
// sendAccConnsUpdate is called to send out our information on the
// account's local connections.
// Lock should be held on entry.
func (s *Server) sendAccConnsUpdate(a *Account, subj string) {
if !s.eventsEnabled() || a == nil || a == s.gacc {
return
}
a.mu.RLock()
// Build event with account name and number of local clients and leafnodes.
m := AccountNumConns{
Account: a.Name,
Conns: a.numLocalConnections(),
LeafNodes: a.numLocalLeafNodes(),
TotalConns: a.numLocalConnections() + a.numLocalLeafNodes(),
}
a.mu.RUnlock()
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
// Set timer to fire again unless we are at zero.
a.mu.Lock()
if a.numLocalConnections() == 0 {
clearTimer(&a.ctmr)
} else {
// Check to see if we have an HB running and update.
if a.ctmr == nil {
a.ctmr = time.AfterFunc(eventsHBInterval, func() { s.accConnsUpdate(a) })
} else {
a.ctmr.Reset(eventsHBInterval)
}
}
a.mu.Unlock()
}
// accConnsUpdate is called whenever there is a change to the account's
// number of active connections, or during a heartbeat.
func (s *Server) accConnsUpdate(a *Account) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() || a == nil {
return
}
subj := fmt.Sprintf(accConnsEventSubj, a.Name)
s.sendAccConnsUpdate(a, subj)
}
// accountConnectEvent will send an account client connect event if there is interest.
// This is a billing event.
func (s *Server) accountConnectEvent(c *client) {
s.mu.Lock()
gacc := s.gacc
if !s.eventsEnabled() {
s.mu.Unlock()
return
}
s.mu.Unlock()
c.mu.Lock()
// Ignore global account activity
if c.acc == nil || c.acc == gacc {
c.mu.Unlock()
return
}
m := ConnectEventMsg{
Client: ClientInfo{
Start: c.start,
Host: c.host,
ID: c.cid,
Account: accForClient(c),
User: nameForClient(c),
Name: c.opts.Name,
Lang: c.opts.Lang,
Version: c.opts.Version,
},
}
c.mu.Unlock()
subj := fmt.Sprintf(connectEventSubj, c.acc.Name)
s.sendInternalMsgLocked(subj, _EMPTY_, &m.Server, &m)
}
// accountDisconnectEvent will send an account client disconnect event if there is interest.
// This is a billing event.
func (s *Server) accountDisconnectEvent(c *client, now time.Time, reason string) {
s.mu.Lock()
gacc := s.gacc
if !s.eventsEnabled() {
s.mu.Unlock()
return
}
s.mu.Unlock()
c.mu.Lock()
// Ignore global account activity
if c.acc == nil || c.acc == gacc {
c.mu.Unlock()
return
}
m := DisconnectEventMsg{
Client: ClientInfo{
Start: c.start,
Stop: &now,
Host: c.host,
ID: c.cid,
Account: accForClient(c),
User: nameForClient(c),
Name: c.opts.Name,
Lang: c.opts.Lang,
Version: c.opts.Version,
RTT: c.getRTT(),
},
Sent: DataStats{
Msgs: atomic.LoadInt64(&c.inMsgs),
Bytes: atomic.LoadInt64(&c.inBytes),
},
Received: DataStats{
Msgs: c.outMsgs,
Bytes: c.outBytes,
},
Reason: reason,
}
c.mu.Unlock()
subj := fmt.Sprintf(disconnectEventSubj, c.acc.Name)
s.sendInternalMsgLocked(subj, _EMPTY_, &m.Server, &m)
}
func (s *Server) sendAuthErrorEvent(c *client) {
s.mu.Lock()
if !s.eventsEnabled() {
s.mu.Unlock()
return
}
s.mu.Unlock()
now := time.Now()
c.mu.Lock()
m := DisconnectEventMsg{
Client: ClientInfo{
Start: c.start,
Stop: &now,
Host: c.host,
ID: c.cid,
Account: accForClient(c),
User: nameForClient(c),
Name: c.opts.Name,
Lang: c.opts.Lang,
Version: c.opts.Version,
RTT: c.getRTT(),
},
Sent: DataStats{
Msgs: c.inMsgs,
Bytes: c.inBytes,
},
Received: DataStats{
Msgs: c.outMsgs,
Bytes: c.outBytes,
},
Reason: AuthenticationViolation.String(),
}
c.mu.Unlock()
s.mu.Lock()
subj := fmt.Sprintf(authErrorEventSubj, s.info.ID)
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
s.mu.Unlock()
}
// Internal message callback. If the msg is needed past the callback it is
// required to be copied.
type msgHandler func(sub *subscription, client *client, subject, reply string, msg []byte)
func (s *Server) deliverInternalMsg(sub *subscription, c *client, subject, reply, msg []byte) {
s.mu.Lock()
if !s.eventsEnabled() || s.sys.subs == nil {
s.mu.Unlock()
return
}
cb := s.sys.subs[string(sub.sid)]
s.mu.Unlock()
if cb != nil {
cb(sub, c, string(subject), string(reply), msg)
}
}
// Create an internal subscription. No support for queue groups atm.
func (s *Server) sysSubscribe(subject string, cb msgHandler) (*subscription, error) {
return s.systemSubscribe(subject, false, cb)
}
// Create an internal subscription but do not forward interest.
func (s *Server) sysSubscribeInternal(subject string, cb msgHandler) (*subscription, error) {
return s.systemSubscribe(subject, true, cb)
}
func (s *Server) systemSubscribe(subject string, internalOnly bool, cb msgHandler) (*subscription, error) {
if !s.eventsEnabled() {
return nil, ErrNoSysAccount
}
if cb == nil {
return nil, fmt.Errorf("undefined message handler")
}
s.mu.Lock()
sid := strconv.FormatInt(int64(s.sys.sid), 10)
s.sys.subs[sid] = cb
s.sys.sid++
c := s.sys.client
s.mu.Unlock()
// Now create the subscription
return c.processSub([]byte(subject+" "+sid), internalOnly)
}
func (s *Server) sysUnsubscribe(sub *subscription) {
if sub == nil || !s.eventsEnabled() {
return
}
s.mu.Lock()
acc := s.sys.account
c := s.sys.client
delete(s.sys.subs, string(sub.sid))
s.mu.Unlock()
c.unsubscribe(acc, sub, true, true)
}
// This will generate the tracking subject for remote latency from the response subject.
func remoteLatencySubjectForResponse(subject []byte) string {
if !isTrackedReply(subject) {
return ""
}
toks := bytes.Split(subject, []byte(tsep))
// FIXME(dlc) - Sprintf may become a performance concern at some point.
return fmt.Sprintf(remoteLatencyEventSubj, toks[len(toks)-2])
}
// remoteLatencyUpdate is used to track remote latency measurements for tracking on exported services.
func (s *Server) remoteLatencyUpdate(sub *subscription, _ *client, subject, _ string, msg []byte) {
if !s.eventsRunning() {
return
}
rl := remoteLatency{}
if err := json.Unmarshal(msg, &rl); err != nil {
s.Errorf("Error unmarshalling remot elatency measurement: %v", err)
return
}
// Now we need to look up the responseServiceImport associated with this measurement.
acc, err := s.LookupAccount(rl.Account)
if err != nil {
s.Warnf("Could not lookup account %q for latency measurement", rl.Account)
return
}
// Now get the request id / reply. We need to see if we have a GW prefix and if so strip that off.
reply := rl.ReqId
if gwPrefix, old := isGWRoutedSubjectAndIsOldPrefix([]byte(reply)); gwPrefix {
reply = string(getSubjectFromGWRoutedReply([]byte(reply), old))
}
acc.mu.RLock()
si := acc.imports.services[reply]
if si == nil {
acc.mu.RUnlock()
return
}
m1 := si.m1
m2 := rl.M2
lsub := si.latency.subject
acc.mu.RUnlock()
// So we have not processed the response tracking measurement yet.
if m1 == nil {
si.acc.mu.Lock()
// Double check since could have slipped in.
m1 = si.m1
if m1 == nil {
// Store our value there for them to pick up.
si.m1 = &m2
}
si.acc.mu.Unlock()
if m1 == nil {
return
}
}
// Calculate the correct latency given M1 and M2.
// M2 ServiceLatency is correct, so use that.
// M1 TotalLatency is correct, so use that.
// Will use those to back into NATS latency.
m1.merge(&m2)
// Make sure we remove the entry here.
acc.removeServiceImport(si.from)
// Send the metrics
s.sendInternalAccountMsg(acc, lsub, &m1)
}
// This is used for all inbox replies so that we do not send supercluster wide interest
// updates for every request. Same trick used in modern NATS clients.
func (s *Server) inboxReply(sub *subscription, c *client, subject, reply string, msg []byte) {
s.mu.Lock()
if !s.eventsEnabled() || s.sys.replies == nil {
s.mu.Unlock()
return
}
cb, ok := s.sys.replies[subject]
s.mu.Unlock()
if ok && cb != nil {
cb(sub, c, subject, reply, msg)
}
}
// Copied from go client.
// We could use serviceReply here instead to save some code.
// I prefer these semantics for the moment, when tracing you know
// what this is.
const (
InboxPrefix = "$SYS._INBOX."
inboxPrefixLen = len(InboxPrefix)
respInboxPrefixLen = inboxPrefixLen + sysHashLen + 1
replySuffixLen = 8 // Gives us 62^8
)
// Creates an internal inbox used for replies that will be processed by the global wc handler.
func (s *Server) newRespInbox() string {
var b [respInboxPrefixLen + replySuffixLen]byte
pres := b[:respInboxPrefixLen]
copy(pres, s.sys.inboxPre)
rn := rand.Int63()
for i, l := respInboxPrefixLen, rn; i < len(b); i++ {
b[i] = digits[l%base]
l /= base
}
return string(b[:])
}
// accNumSubsReq is sent when we need to gather remote info on subs.
type accNumSubsReq struct {
Account string `json:"acc"`
Subject string `json:"subject"`
Queue []byte `json:"queue,omitempty"`
}
// helper function to total information from results to count subs.
func totalSubs(rr *SublistResult, qg []byte) (nsubs int32) {
if rr == nil {
return
}
checkSub := func(sub *subscription) {
// TODO(dlc) - This could be smarter.
if qg != nil && !bytes.Equal(qg, sub.queue) {
return
}
if sub.client.kind == CLIENT || sub.client.isUnsolicitedLeafNode() {
nsubs++
}
}
if qg == nil {
for _, sub := range rr.psubs {
checkSub(sub)
}
}
for _, qsub := range rr.qsubs {
for _, sub := range qsub {
checkSub(sub)
}
}
return
}
// Allows users of large systems to debug active subscribers for a given subject.
// Payload should be the subject of interest.
func (s *Server) debugSubscribers(sub *subscription, c *client, subject, reply string, msg []byte) {
// Even though this is an internal only subscription, meaning interest was not forwarded, we could
// get one here from a GW in optimistic mode. Ignore for now.
// FIXME(dlc) - Should we send no interest here back to the GW?
if c.kind != CLIENT {
return
}
var nsubs int32
// We could have a single subject or we could have a subject and a wildcard separated by whitespace.
args := strings.Split(strings.TrimSpace(string(msg)), " ")
if len(args) == 0 {
s.sendInternalAccountMsg(c.acc, reply, 0)
return
}
tsubj := args[0]
var qgroup []byte
if len(args) > 1 {
qgroup = []byte(args[1])
}
if subjectIsLiteral(tsubj) {
// We will look up subscribers locally first then determine if we need to solicit other servers.
rr := c.acc.sl.Match(tsubj)
nsubs = totalSubs(rr, qgroup)
} else {
// We have a wildcard, so this is a bit slower path.
var _subs [32]*subscription
subs := _subs[:0]
c.acc.sl.All(&subs)
for _, sub := range subs {
if subjectIsSubsetMatch(string(sub.subject), tsubj) {
if qgroup != nil && !bytes.Equal(qgroup, sub.queue) {
continue
}
if sub.client.kind == CLIENT || sub.client.isUnsolicitedLeafNode() {
nsubs++
}
}
}
}
// We should have an idea of how many responses to expect from remote servers.
var expected = c.acc.expectedRemoteResponses()
// If we are only local, go ahead and return.
if expected == 0 {
s.sendInternalAccountMsg(c.acc, reply, nsubs)
return
}
// We need to solicit from others.
// To track status.
responses := int32(0)
done := make(chan (bool))
s.mu.Lock()
// Create direct reply inbox that we multiplex under the WC replies.
replySubj := s.newRespInbox()
// Store our handler.
s.sys.replies[replySubj] = func(sub *subscription, _ *client, subject, _ string, msg []byte) {
if n, err := strconv.Atoi(string(msg)); err == nil {
atomic.AddInt32(&nsubs, int32(n))
}
if atomic.AddInt32(&responses, 1) >= expected {
select {
case done <- true:
default:
}
}
}
// Send the request to the other servers.
request := &accNumSubsReq{
Account: c.acc.Name,
Subject: tsubj,
Queue: qgroup,
}
s.sendInternalMsg(accNumSubsReqSubj, replySubj, nil, request)
s.mu.Unlock()
// FIXME(dlc) - We should rate limit here instead of blind Go routine.
go func() {
select {
case <-done:
case <-time.After(500 * time.Millisecond):
}
// Cleanup the WC entry.
s.mu.Lock()
delete(s.sys.replies, replySubj)
s.mu.Unlock()
// Send the response.
s.sendInternalAccountMsg(c.acc, reply, atomic.LoadInt32(&nsubs))
}()
}
// Request for our local subscription count. This will come from a remote origin server
// that received the initial request.
func (s *Server) nsubsRequest(sub *subscription, _ *client, subject, reply string, msg []byte) {
if !s.eventsRunning() {
return
}
m := accNumSubsReq{}
if err := json.Unmarshal(msg, &m); err != nil {
s.sys.client.Errorf("Error unmarshalling account nsubs request message: %v", err)
return
}
// Grab account.
acc, _ := s.lookupAccount(m.Account)
if acc == nil || acc.numLocalAndLeafConnections() == 0 {
return
}
// We will look up subscribers locally first then determine if we need to solicit other servers.
var nsubs int32
if subjectIsLiteral(m.Subject) {
rr := acc.sl.Match(m.Subject)
nsubs = totalSubs(rr, m.Queue)
} else {
// We have a wildcard, so this is a bit slower path.
var _subs [32]*subscription
subs := _subs[:0]
acc.sl.All(&subs)
for _, sub := range subs {
if (sub.client.kind == CLIENT || sub.client.isUnsolicitedLeafNode()) && subjectIsSubsetMatch(string(sub.subject), m.Subject) {
if m.Queue != nil && !bytes.Equal(m.Queue, sub.queue) {
continue
}
nsubs++
}
}
}
s.sendInternalMsgLocked(reply, _EMPTY_, nil, nsubs)
}
// Helper to grab name for a client.
func nameForClient(c *client) string {
if c.user != nil {
return c.user.Nkey
}
return "N/A"
}
// Helper to grab account name for a client.
func accForClient(c *client) string {
if c.acc != nil {
return c.acc.Name
}
return "N/A"
}
// Helper to clear timers.
func clearTimer(tp **time.Timer) {
if t := *tp; t != nil {
t.Stop()
*tp = nil
}
}
// Helper function to wrap functions with common test
// to lock server and return if events not enabled.
func (s *Server) wrapChk(f func()) func() {
return func() {
s.mu.Lock()
if !s.eventsEnabled() {
s.mu.Unlock()
return
}
f()
s.mu.Unlock()
}
}
| 1 | 10,036 | wonder if we should collect c.trace, c.pa.subject, etc.. while under the lock to prevent data races.. or simply move the tracing under the lock. | nats-io-nats-server | go |
@@ -182,7 +182,7 @@ PJ_XY pj_fwd(PJ_LP lp, PJ *P) {
last_errno = proj_errno_reset(P);
- if (!P->skip_fwd_prepare)
+ if (!P->skip_fwd_prepare && 0 != strcmp(P->short_name, "s2"))
coo = fwd_prepare (P, coo);
if (HUGE_VAL==coo.v[0] || HUGE_VAL==coo.v[1])
return proj_coord_error ().xy; | 1 | /******************************************************************************
* Project: PROJ.4
* Purpose: Forward operation invocation
* Author: Thomas Knudsen, [email protected], 2018-01-02
* Based on material from Gerald Evenden (original pj_fwd)
* and Piyush Agram (original pj_fwd3d)
*
******************************************************************************
* Copyright (c) 2000, Frank Warmerdam
* Copyright (c) 2018, Thomas Knudsen / SDFE
*
* 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 <errno.h>
#include <math.h>
#include "proj_internal.h"
#include <math.h>
#define INPUT_UNITS P->left
#define OUTPUT_UNITS P->right
static PJ_COORD fwd_prepare (PJ *P, PJ_COORD coo) {
if (HUGE_VAL==coo.v[0] || HUGE_VAL==coo.v[1] || HUGE_VAL==coo.v[2])
return proj_coord_error ();
/* The helmert datum shift will choke unless it gets a sensible 4D coordinate */
if (HUGE_VAL==coo.v[2] && P->helmert) coo.v[2] = 0.0;
if (HUGE_VAL==coo.v[3] && P->helmert) coo.v[3] = 0.0;
/* Check validity of angular input coordinates */
if (INPUT_UNITS==PJ_IO_UNITS_RADIANS) {
double t;
/* check for latitude or longitude over-range */
t = (coo.lp.phi < 0 ? -coo.lp.phi : coo.lp.phi) - M_HALFPI;
if (t > PJ_EPS_LAT)
{
proj_log_error(P, _("Invalid latitude"));
proj_errno_set (P, PROJ_ERR_COORD_TRANSFM_INVALID_COORD);
return proj_coord_error ();
}
if (coo.lp.lam > 10 || coo.lp.lam < -10)
{
proj_log_error(P, _("Invalid longitude"));
proj_errno_set (P, PROJ_ERR_COORD_TRANSFM_INVALID_COORD);
return proj_coord_error ();
}
/* Clamp latitude to -90..90 degree range */
if (coo.lp.phi > M_HALFPI)
coo.lp.phi = M_HALFPI;
if (coo.lp.phi < -M_HALFPI)
coo.lp.phi = -M_HALFPI;
/* If input latitude is geocentrical, convert to geographical */
if (P->geoc)
coo = pj_geocentric_latitude (P, PJ_INV, coo);
/* Ensure longitude is in the -pi:pi range */
if (0==P->over)
coo.lp.lam = adjlon(coo.lp.lam);
if (P->hgridshift)
coo = proj_trans (P->hgridshift, PJ_INV, coo);
else if (P->helmert || (P->cart_wgs84 != nullptr && P->cart != nullptr)) {
coo = proj_trans (P->cart_wgs84, PJ_FWD, coo); /* Go cartesian in WGS84 frame */
if( P->helmert )
coo = proj_trans (P->helmert, PJ_INV, coo); /* Step into local frame */
coo = proj_trans (P->cart, PJ_INV, coo); /* Go back to angular using local ellps */
}
if (coo.lp.lam==HUGE_VAL)
return coo;
if (P->vgridshift)
coo = proj_trans (P->vgridshift, PJ_FWD, coo); /* Go orthometric from geometric */
/* Distance from central meridian, taking system zero meridian into account */
coo.lp.lam = (coo.lp.lam - P->from_greenwich) - P->lam0;
/* Ensure longitude is in the -pi:pi range */
if (0==P->over)
coo.lp.lam = adjlon(coo.lp.lam);
return coo;
}
/* We do not support gridshifts on cartesian input */
if (INPUT_UNITS==PJ_IO_UNITS_CARTESIAN && P->helmert)
return proj_trans (P->helmert, PJ_INV, coo);
return coo;
}
static PJ_COORD fwd_finalize (PJ *P, PJ_COORD coo) {
switch (OUTPUT_UNITS) {
/* Handle false eastings/northings and non-metric linear units */
case PJ_IO_UNITS_CARTESIAN:
if (P->is_geocent) {
coo = proj_trans (P->cart, PJ_FWD, coo);
}
coo.xyz.x *= P->fr_meter;
coo.xyz.y *= P->fr_meter;
coo.xyz.z *= P->fr_meter;
break;
/* Classic proj.4 functions return plane coordinates in units of the semimajor axis */
case PJ_IO_UNITS_CLASSIC:
coo.xy.x *= P->a;
coo.xy.y *= P->a;
/* Falls through */ /* (<-- GCC warning silencer) */
/* to continue processing in common with PJ_IO_UNITS_PROJECTED */
case PJ_IO_UNITS_PROJECTED:
coo.xyz.x = P->fr_meter * (coo.xyz.x + P->x0);
coo.xyz.y = P->fr_meter * (coo.xyz.y + P->y0);
coo.xyz.z = P->vfr_meter * (coo.xyz.z + P->z0);
break;
case PJ_IO_UNITS_WHATEVER:
break;
case PJ_IO_UNITS_DEGREES:
break;
case PJ_IO_UNITS_RADIANS:
coo.lpz.z = P->vfr_meter * (coo.lpz.z + P->z0);
if( P->is_long_wrap_set ) {
if( coo.lpz.lam != HUGE_VAL ) {
coo.lpz.lam = P->long_wrap_center +
adjlon(coo.lpz.lam - P->long_wrap_center);
}
}
break;
}
if (P->axisswap)
coo = proj_trans (P->axisswap, PJ_FWD, coo);
return coo;
}
static PJ_COORD error_or_coord(PJ *P, PJ_COORD coord, int last_errno) {
if (proj_errno(P))
return proj_coord_error();
proj_errno_restore(P, last_errno);
return coord;
}
PJ_XY pj_fwd(PJ_LP lp, PJ *P) {
int last_errno;
PJ_COORD coo = {{0,0,0,0}};
coo.lp = lp;
last_errno = proj_errno_reset(P);
if (!P->skip_fwd_prepare)
coo = fwd_prepare (P, coo);
if (HUGE_VAL==coo.v[0] || HUGE_VAL==coo.v[1])
return proj_coord_error ().xy;
/* Do the transformation, using the lowest dimensional transformer available */
if (P->fwd)
coo.xy = P->fwd(coo.lp, P);
else if (P->fwd3d)
coo.xyz = P->fwd3d (coo.lpz, P);
else if (P->fwd4d)
coo = P->fwd4d (coo, P);
else {
proj_errno_set (P, PROJ_ERR_OTHER_NO_INVERSE_OP);
return proj_coord_error ().xy;
}
if (HUGE_VAL==coo.v[0])
return proj_coord_error ().xy;
if (!P->skip_fwd_finalize)
coo = fwd_finalize (P, coo);
return error_or_coord(P, coo, last_errno).xy;
}
PJ_XYZ pj_fwd3d(PJ_LPZ lpz, PJ *P) {
int last_errno;
PJ_COORD coo = {{0,0,0,0}};
coo.lpz = lpz;
last_errno = proj_errno_reset(P);
if (!P->skip_fwd_prepare)
coo = fwd_prepare (P, coo);
if (HUGE_VAL==coo.v[0])
return proj_coord_error ().xyz;
/* Do the transformation, using the lowest dimensional transformer feasible */
if (P->fwd3d)
coo.xyz = P->fwd3d(coo.lpz, P);
else if (P->fwd4d)
coo = P->fwd4d (coo, P);
else if (P->fwd)
coo.xy = P->fwd (coo.lp, P);
else {
proj_errno_set (P, PROJ_ERR_OTHER_NO_INVERSE_OP);
return proj_coord_error ().xyz;
}
if (HUGE_VAL==coo.v[0])
return proj_coord_error ().xyz;
if (!P->skip_fwd_finalize)
coo = fwd_finalize (P, coo);
return error_or_coord(P, coo, last_errno).xyz;
}
PJ_COORD pj_fwd4d (PJ_COORD coo, PJ *P) {
int last_errno = proj_errno_reset(P);
if (!P->skip_fwd_prepare)
coo = fwd_prepare (P, coo);
if (HUGE_VAL==coo.v[0])
return proj_coord_error ();
/* Call the highest dimensional converter available */
if (P->fwd4d)
coo = P->fwd4d (coo, P);
else if (P->fwd3d)
coo.xyz = P->fwd3d (coo.lpz, P);
else if (P->fwd)
coo.xy = P->fwd (coo.lp, P);
else {
proj_errno_set (P, PROJ_ERR_OTHER_NO_INVERSE_OP);
return proj_coord_error ();
}
if (HUGE_VAL==coo.v[0])
return proj_coord_error ();
if (!P->skip_fwd_finalize)
coo = fwd_finalize (P, coo);
return error_or_coord(P, coo, last_errno);
}
| 1 | 12,608 | Why is this hack needed ? Ideally, we shouldn't need that. | OSGeo-PROJ | cpp |
@@ -0,0 +1,19 @@
+package plugin
+
+type Status struct {
+ DriverName string
+ MeshDriverName string `json:"MeshDriverName,omitempty"`
+ Version int
+}
+
+func NewStatus(address, meshAddress string, isPluginV2 bool) *Status {
+ status := &Status{
+ DriverName: pluginNameFromAddress(address),
+ MeshDriverName: pluginNameFromAddress(meshAddress),
+ Version: 1,
+ }
+ if isPluginV2 {
+ status.Version = 2
+ }
+ return status
+} | 1 | 1 | 14,845 | Minor/Nitpick: replace `1` with a constant, esp. as used in `prog/weaver/http.go` in `{{if eq .Plugin.Version 1}}` | weaveworks-weave | go |
|
@@ -13,5 +13,5 @@ namespace Datadog.Trace.Configuration
{
return Environment.GetEnvironmentVariable(key);
}
- }
+ }
} | 1 | using System;
namespace Datadog.Trace.Configuration
{
/// <summary>
/// Represents a configuration source that
/// retrieves values from environment variables.
/// </summary>
public class EnvironmentConfigurationSource : StringConfigurationSource
{
/// <inheritdoc />
public override string GetString(string key)
{
return Environment.GetEnvironmentVariable(key);
}
}
}
| 1 | 15,882 | nit: Looks like the whitespace got thrown off, can you fix this? | DataDog-dd-trace-dotnet | .cs |
@@ -5593,7 +5593,13 @@ namespace pwiz.Skyline.Properties {
return ResourceManager.GetString("CommandLine_ImportAnnotations_Error__Failed_while_reading_annotations_", resourceCulture);
}
}
-
+
+ public static string CommandLine_ImportPeakBoundaries_Error__Failed_while_importing_boundaries_ {
+ get {
+ return ResourceManager.GetString("CommandLine_ImportPeakBoundaries_Error__Failed_while_importing_boundaries_", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to Error: The replicate {0} already exists in the given document and the --import-append option is not specified. The replicate will not be added to the document..
/// </summary> | 1 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace pwiz.Skyline.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("pwiz.Skyline.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Failed to find a valid Analyst installation.
/// </summary>
public static string AbiMethodExporter_EnsureAnalyst_Failed_to_find_a_valid_Analyst_installation {
get {
return ResourceManager.GetString("AbiMethodExporter_EnsureAnalyst_Failed_to_find_a_valid_Analyst_installation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Waiting for Analyst to start....
/// </summary>
public static string AbiMethodExporter_EnsureAnalyst_Waiting_for_Analyst_to_start {
get {
return ResourceManager.GetString("AbiMethodExporter_EnsureAnalyst_Waiting_for_Analyst_to_start", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Working....
/// </summary>
public static string AbiMethodExporter_EnsureAnalyst_Working {
get {
return ResourceManager.GetString("AbiMethodExporter_EnsureAnalyst_Working", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention Time.
/// </summary>
public static string AbstractChromGraphItem_CustomizeXAxis_Retention_Time {
get {
return ResourceManager.GetString("AbstractChromGraphItem_CustomizeXAxis_Retention_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Intensity.
/// </summary>
public static string AbstractChromGraphItem_CustomizeYAxis_Intensity {
get {
return ResourceManager.GetString("AbstractChromGraphItem_CustomizeYAxis_Intensity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation scheme is set to multiplexing but file does not appear to contain multiplexed acquisition data..
/// </summary>
public static string AbstractDemultiplexer_AnalyzeFile_Isolation_scheme_is_set_to_multiplexing_but_file_does_not_appear_to_contain_multiplexed_acquisition_data_ {
get {
return ResourceManager.GetString("AbstractDemultiplexer_AnalyzeFile_Isolation_scheme_is_set_to_multiplexing_but_fil" +
"e_does_not_appear_to_contain_multiplexed_acquisition_data_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot save to {0}..
/// </summary>
public static string AbstractDiaExporter_Export_Cannot_save_to__0__ {
get {
return ResourceManager.GetString("AbstractDiaExporter_Export_Cannot_save_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting Isolation List.
/// </summary>
public static string AbstractDiaExporter_WriteMultiplexedWindows_Exporting_Isolation_List {
get {
return ResourceManager.GetString("AbstractDiaExporter_WriteMultiplexedWindows_Exporting_Isolation_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting Isolation List ({0} cycles out of {0}).
/// </summary>
public static string AbstractDiaExporter_WriteMultiplexedWindows_Exporting_Isolation_List__0__cycles_out_of__0__ {
get {
return ResourceManager.GetString("AbstractDiaExporter_WriteMultiplexedWindows_Exporting_Isolation_List__0__cycles_o" +
"ut_of__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting Isolation List ({0} cycles out of {1}).
/// </summary>
public static string AbstractDiaExporter_WriteMultiplexedWindows_Exporting_Isolation_List__0__cycles_out_of__1__ {
get {
return ResourceManager.GetString("AbstractDiaExporter_WriteMultiplexedWindows_Exporting_Isolation_List__0__cycles_o" +
"ut_of__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scan in imported file appears to be missing an isolation window center..
/// </summary>
public static string AbstractIsoWindowMapper_Add_Scan_in_imported_file_appears_to_be_missing_an_isolation_window_center_ {
get {
return ResourceManager.GetString("AbstractIsoWindowMapper_Add_Scan_in_imported_file_appears_to_be_missing_an_isolat" +
"ion_window_center_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The isolation width for a scan in the imported file could not be determined..
/// </summary>
public static string AbstractIsoWindowMapper_Add_The_isolation_width_for_a_scan_in_the_imported_file_could_not_be_determined_ {
get {
return ResourceManager.GetString("AbstractIsoWindowMapper_Add_The_isolation_width_for_a_scan_in_the_imported_file_c" +
"ould_not_be_determined_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Tried to get a window mask for {0}, a spectrum with previously unobserved isolation windows. Demultiplexing requires a repeating cycle of isolation windows..
/// </summary>
public static string AbstractIsoWindowMapper_GetWindowMask_Tried_to_get_a_window_mask_for__0___a_spectrum_with_previously_unobserved_isolation_windows__Demultiplexing_requires_a_repeating_cycle_of_isolation_windows_ {
get {
return ResourceManager.GetString("AbstractIsoWindowMapper_GetWindowMask_Tried_to_get_a_window_mask_for__0___a_spect" +
"rum_with_previously_unobserved_isolation_windows__Demultiplexing_requires_a_repe" +
"ating_cycle_of_isolation_windows_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The number of required transitions {0} exceeds the maximum {1}.
/// </summary>
public static string AbstractMassListExporter_Export_The_number_of_required_transitions__0__exceeds_the_maximum__1__ {
get {
return ResourceManager.GetString("AbstractMassListExporter_Export_The_number_of_required_transitions__0__exceeds_th" +
"e_maximum__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check max concurrent {0} count..
/// </summary>
public static string AbstractMassListExporter_ExportScheduledBuckets_Check_max_concurrent__0__count {
get {
return ResourceManager.GetString("AbstractMassListExporter_ExportScheduledBuckets_Check_max_concurrent__0__count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check max concurrent {0} count and optimization step count..
/// </summary>
public static string AbstractMassListExporter_ExportScheduledBuckets_Check_max_concurrent__0__count_and_optimization_step_count {
get {
return ResourceManager.GetString("AbstractMassListExporter_ExportScheduledBuckets_Check_max_concurrent__0__count_an" +
"d_optimization_step_count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to schedule the following peptides with the current settings:.
/// </summary>
public static string AbstractMassListExporter_ExportScheduledBuckets_Failed_to_schedule_the_following_peptides_with_the_current_settings {
get {
return ResourceManager.GetString("AbstractMassListExporter_ExportScheduledBuckets_Failed_to_schedule_the_following_" +
"peptides_with_the_current_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Maximum transitions per file required.
/// </summary>
public static string AbstractMassListExporter_ExportScheduledBuckets_Maximum_transitions_per_file_required {
get {
return ResourceManager.GetString("AbstractMassListExporter_ExportScheduledBuckets_Maximum_transitions_per_file_requ" +
"ired", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to precursors.
/// </summary>
public static string AbstractMassListExporter_ExportScheduledBuckets_precursors {
get {
return ResourceManager.GetString("AbstractMassListExporter_ExportScheduledBuckets_precursors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The required peptide {0} cannot be scheduled.
/// </summary>
public static string AbstractMassListExporter_ExportScheduledBuckets_The_required_peptide__0__cannot_be_scheduled {
get {
return ResourceManager.GetString("AbstractMassListExporter_ExportScheduledBuckets_The_required_peptide__0__cannot_b" +
"e_scheduled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to transitions.
/// </summary>
public static string AbstractMassListExporter_ExportScheduledBuckets_transitions {
get {
return ResourceManager.GetString("AbstractMassListExporter_ExportScheduledBuckets_transitions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following modifications could not be interpreted..
/// </summary>
public static string AbstractModificationMatcher_UninterpretedMods_The_following_modifications_could_not_be_interpreted {
get {
return ResourceManager.GetString("AbstractModificationMatcher_UninterpretedMods_The_following_modifications_could_n" +
"ot_be_interpreted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} = {1}.
/// </summary>
public static string AbstractModificationMatcherFoundMatches__0__equals__1__ {
get {
return ResourceManager.GetString("AbstractModificationMatcherFoundMatches__0__equals__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to m/z.
/// </summary>
public static string AbstractMSGraphItem_CustomizeXAxis_MZ {
get {
return ResourceManager.GetString("AbstractMSGraphItem_CustomizeXAxis_MZ", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Intensity.
/// </summary>
public static string AbstractMSGraphItem_CustomizeYAxis_Intensity {
get {
return ResourceManager.GetString("AbstractMSGraphItem_CustomizeYAxis_Intensity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occured while uploading to Panorama, would you like to go to Panorama?.
/// </summary>
public static string AbstractPanoramaPublishClient_UploadSharedZipFile_An_error_occured_while_uploading_to_Panorama__would_you_like_to_go_to_Panorama_ {
get {
return ResourceManager.GetString("AbstractPanoramaPublishClient_UploadSharedZipFile_An_error_occured_while_uploadin" +
"g_to_Panorama__would_you_like_to_go_to_Panorama_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document import was cancelled on the server. Would you like to go to Panorama?.
/// </summary>
public static string AbstractPanoramaPublishClient_UploadSharedZipFile_Document_import_was_cancelled_on_the_server__Would_you_like_to_go_to_Panorama_ {
get {
return ResourceManager.GetString("AbstractPanoramaPublishClient_UploadSharedZipFile_Document_import_was_cancelled_o" +
"n_the_server__Would_you_like_to_go_to_Panorama_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Upload succeeded, would you like to view the file in Panorama?.
/// </summary>
public static string AbstractPanoramaPublishClient_UploadSharedZipFile_Upload_succeeded__would_you_like_to_view_the_file_in_Panorama_ {
get {
return ResourceManager.GetString("AbstractPanoramaPublishClient_UploadSharedZipFile_Upload_succeeded__would_you_lik" +
"e_to_view_the_file_in_Panorama_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to score = {0:F06}.
/// </summary>
public static string AbstractSpectrumGraphItem_AddAnnotations_ {
get {
return ResourceManager.GetString("AbstractSpectrumGraphItem_AddAnnotations_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to rank {0}.
/// </summary>
public static string AbstractSpectrumGraphItem_GetLabel_rank__0__ {
get {
return ResourceManager.GetString("AbstractSpectrumGraphItem_GetLabel_rank__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Files extracted to: {0}.
/// </summary>
public static string ActionTutorial_client_DownloadFileCompleted_File_saved_at___0_ {
get {
return ResourceManager.GetString("ActionTutorial_client_DownloadFileCompleted_File_saved_at___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error {0}.
/// </summary>
public static string ActionTutorial_DownloadTutorials_Error__0_ {
get {
return ResourceManager.GetString("ActionTutorial_DownloadTutorials_Error__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while trying to display the document '{0}'.
///There might be something wrong with default web browser on this computer..
/// </summary>
public static string ActionTutorial_ExtractTutorial_An_error_occurred_while_trying_to_display_the_document___0____ {
get {
return ResourceManager.GetString("ActionTutorial_ExtractTutorial_An_error_occurred_while_trying_to_display_the_docu" +
"ment___0____", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading to: {0}{1}Tutorial will open in browser when download is complete..
/// </summary>
public static string ActionTutorial_LongWaitDlgAction_Downloading_to___0__1_Tutorial_will_open_in_browser_when_download_is_complete_ {
get {
return ResourceManager.GetString("ActionTutorial_LongWaitDlgAction_Downloading_to___0__1_Tutorial_will_open_in_brow" +
"ser_when_download_is_complete_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading Tutorial ZIP File.
/// </summary>
public static string ActionTutorial_LongWaitDlgAction_Downloading_Tutorial_Zip_File {
get {
return ResourceManager.GetString("ActionTutorial_LongWaitDlgAction_Downloading_Tutorial_Zip_File", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Extracting Tutorial ZIP File.
/// </summary>
public static string ActionTutorial_LongWaitDlgAction_Extracting_Tutorial_Zip_File_in_the_same_directory_ {
get {
return ResourceManager.GetString("ActionTutorial_LongWaitDlgAction_Extracting_Tutorial_Zip_File_in_the_same_directo" +
"ry_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap add_pro32 {
get {
object obj = ResourceManager.GetObject("add_pro32", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Please choose the iRT calculator you would like to add..
/// </summary>
public static string AddIrtCalculatorDlg_OkDialog_Please_choose_the_iRT_calculator_you_would_like_to_add {
get {
return ResourceManager.GetString("AddIrtCalculatorDlg_OkDialog_Please_choose_the_iRT_calculator_you_would_like_to_a" +
"dd", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please specify a path to an existing iRT database..
/// </summary>
public static string AddIrtCalculatorDlg_OkDialog_Please_specify_a_path_to_an_existing_iRT_database {
get {
return ResourceManager.GetString("AddIrtCalculatorDlg_OkDialog_Please_specify_a_path_to_an_existing_iRT_database", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} is not an iRT database..
/// </summary>
public static string AddIrtCalculatorDlg_OkDialog_The_file__0__is_not_an_iRT_database {
get {
return ResourceManager.GetString("AddIrtCalculatorDlg_OkDialog_The_file__0__is_not_an_iRT_database", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not exist..
/// </summary>
public static string AddIrtCalculatorDlgOkDialogThe_file__0__does_not_exist {
get {
return ResourceManager.GetString("AddIrtCalculatorDlgOkDialogThe_file__0__does_not_exist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 new peptide will be added to the {0}..
/// </summary>
public static string AddIrtPeptidesDlg_AddIrtPeptidesDlg_1_new_peptide_will_be_added_to_the__0__ {
get {
return ResourceManager.GetString("AddIrtPeptidesDlg_AddIrtPeptidesDlg_1_new_peptide_will_be_added_to_the__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 run was not converted due to insufficient correlation..
/// </summary>
public static string AddIrtPeptidesDlg_AddIrtPeptidesDlg_1_run_was_not_converted_due_to_insufficient_correlation {
get {
return ResourceManager.GetString("AddIrtPeptidesDlg_AddIrtPeptidesDlg_1_run_was_not_converted_due_to_insufficient_c" +
"orrelation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 run was successfully converted..
/// </summary>
public static string AddIrtPeptidesDlg_AddIrtPeptidesDlg_1_run_was_successfully_converted {
get {
return ResourceManager.GetString("AddIrtPeptidesDlg_AddIrtPeptidesDlg_1_run_was_successfully_converted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed.
/// </summary>
public static string AddIrtPeptidesDlg_AddIrtPeptidesDlg_Failed {
get {
return ResourceManager.GetString("AddIrtPeptidesDlg_AddIrtPeptidesDlg_Failed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT database.
/// </summary>
public static string AddIrtPeptidesDlg_AddIrtPeptidesDlg_iRT_database {
get {
return ResourceManager.GetString("AddIrtPeptidesDlg_AddIrtPeptidesDlg_iRT_database", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No new peptides will be added to the {0}..
/// </summary>
public static string AddIrtPeptidesDlg_AddIrtPeptidesDlg_No_new_peptides_will_be_added_to_the__0__ {
get {
return ResourceManager.GetString("AddIrtPeptidesDlg_AddIrtPeptidesDlg_No_new_peptides_will_be_added_to_the__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Regression.
/// </summary>
public static string AddIrtPeptidesDlg_AddIrtPeptidesDlg_Regression {
get {
return ResourceManager.GetString("AddIrtPeptidesDlg_AddIrtPeptidesDlg_Regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Regression Attempted.
/// </summary>
public static string AddIrtPeptidesDlg_AddIrtPeptidesDlg_Regression_Attempted {
get {
return ResourceManager.GetString("AddIrtPeptidesDlg_AddIrtPeptidesDlg_Regression_Attempted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Regression Refined.
/// </summary>
public static string AddIrtPeptidesDlg_AddIrtPeptidesDlg_Regression_Refined {
get {
return ResourceManager.GetString("AddIrtPeptidesDlg_AddIrtPeptidesDlg_Regression_Refined", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to spectral library.
/// </summary>
public static string AddIrtPeptidesDlg_AddIrtPeptidesDlg_spectral_library {
get {
return ResourceManager.GetString("AddIrtPeptidesDlg_AddIrtPeptidesDlg_spectral_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Success.
/// </summary>
public static string AddIrtPeptidesDlg_AddIrtPeptidesDlg_Success {
get {
return ResourceManager.GetString("AddIrtPeptidesDlg_AddIrtPeptidesDlg_Success", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT.
/// </summary>
public static string AddIrtPeptidesDlg_dataGridView_CellContentClick_iRT {
get {
return ResourceManager.GetString("AddIrtPeptidesDlg_dataGridView_CellContentClick_iRT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Spectral Libraries.
/// </summary>
public static string AddIrtSpectralLibrary_btnBrowseFile_Click_Spectral_Libraries {
get {
return ResourceManager.GetString("AddIrtSpectralLibrary_btnBrowseFile_Click_Spectral_Libraries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only BiblioSpec and Chromatogram libraries contain enough retention time information to support this operation..
/// </summary>
public static string AddIrtSpectralLibrary_OkDialog_Only_BiblioSpec_and_Chromatogram_libraries_contain_enough_retention_time_information_to_support_this_operation {
get {
return ResourceManager.GetString("AddIrtSpectralLibrary_OkDialog_Only_BiblioSpec_and_Chromatogram_libraries_contain" +
"_enough_retention_time_information_to_support_this_operation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please choose a non-redundant library..
/// </summary>
public static string AddIrtSpectralLibrary_OkDialog_Please_choose_a_non_redundant_library {
get {
return ResourceManager.GetString("AddIrtSpectralLibrary_OkDialog_Please_choose_a_non_redundant_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please choose the library you would like to add..
/// </summary>
public static string AddIrtSpectralLibrary_OkDialog_Please_choose_the_library_you_would_like_to_add {
get {
return ResourceManager.GetString("AddIrtSpectralLibrary_OkDialog_Please_choose_the_library_you_would_like_to_add", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please specify a path to an existing spectral library..
/// </summary>
public static string AddIrtSpectralLibrary_OkDialog_Please_specify_a_path_to_an_existing_spectral_library {
get {
return ResourceManager.GetString("AddIrtSpectralLibrary_OkDialog_Please_specify_a_path_to_an_existing_spectral_libr" +
"ary", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} appears to be a redundant library..
/// </summary>
public static string AddIrtSpectralLibrary_OkDialog_The_file__0__appears_to_be_a_redundant_library {
get {
return ResourceManager.GetString("AddIrtSpectralLibrary_OkDialog_The_file__0__appears_to_be_a_redundant_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not exist..
/// </summary>
public static string AddIrtSpectralLibrary_OkDialog_The_file__0__does_not_exist {
get {
return ResourceManager.GetString("AddIrtSpectralLibrary_OkDialog_The_file__0__does_not_exist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} is not a BiblioSpec or Chromatogram library..
/// </summary>
public static string AddIrtSpectralLibrary_OkDialog_The_file__0__is_not_a_BiblioSpec_or_Chromatogram_library {
get {
return ResourceManager.GetString("AddIrtSpectralLibrary_OkDialog_The_file__0__is_not_a_BiblioSpec_or_Chromatogram_l" +
"ibrary", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measured.
/// </summary>
public static string AddIrtsResultsDlg_dataGridView_CellContentClick_Measured {
get {
return ResourceManager.GetString("AddIrtsResultsDlg_dataGridView_CellContentClick_Measured", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The current document contains {0} peptides not in this standard with measured retention times. It is suggested that you use a small number of peptides that can be easily measured in a single injection for an iRT standard. Choose a number of peptides below to have Skyline select automatically from the current document..
/// </summary>
public static string AddIrtStandardsDlg_AddIrtStandardsDlg_MessagePeptidesExcluded {
get {
return ResourceManager.GetString("AddIrtStandardsDlg_AddIrtStandardsDlg_MessagePeptidesExcluded", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please choose the optimization library you would like to add..
/// </summary>
public static string AddOptimizationDlg_OkDialog_Please_choose_the_optimization_library_you_would_like_to_add_ {
get {
return ResourceManager.GetString("AddOptimizationDlg_OkDialog_Please_choose_the_optimization_library_you_would_like" +
"_to_add_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please specify a path to an existing optimization library..
/// </summary>
public static string AddOptimizationDlg_OkDialog_Please_specify_a_path_to_an_existing_optimization_library_ {
get {
return ResourceManager.GetString("AddOptimizationDlg_OkDialog_Please_specify_a_path_to_an_existing_optimization_lib" +
"rary_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not exist..
/// </summary>
public static string AddOptimizationDlg_OkDialog_The_file__0__does_not_exist_ {
get {
return ResourceManager.GetString("AddOptimizationDlg_OkDialog_The_file__0__does_not_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} is not an optimization library..
/// </summary>
public static string AddOptimizationDlg_OkDialog_The_file__0__is_not_an_optimization_library_ {
get {
return ResourceManager.GetString("AddOptimizationDlg_OkDialog_The_file__0__is_not_an_optimization_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 new optimization will be added to the library..
/// </summary>
public static string AddOptimizationsDlg_AddOptimizationsDlg__1_new_optimization_will_be_added_to_the_library_ {
get {
return ResourceManager.GetString("AddOptimizationsDlg_AddOptimizationsDlg__1_new_optimization_will_be_added_to_the_" +
"library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No new optimizations will be added to the library..
/// </summary>
public static string AddOptimizationsDlg_AddOptimizationsDlg_No_new_optimizations_will_be_added_to_the_library_ {
get {
return ResourceManager.GetString("AddOptimizationsDlg_AddOptimizationsDlg_No_new_optimizations_will_be_added_to_the" +
"_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following files are not valid library input files:.
/// </summary>
public static string AddPathsDlg_OkDialog_The_following_files_are_not_valid_library_input_files_ {
get {
return ResourceManager.GetString("AddPathsDlg_OkDialog_The_following_files_are_not_valid_library_input_files_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following files could not be found:.
/// </summary>
public static string AddPathsDlg_OkDialog_The_following_files_could_not_be_found_ {
get {
return ResourceManager.GetString("AddPathsDlg_OkDialog_The_following_files_could_not_be_found_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Comparing Imported Files.
/// </summary>
public static string AddPeakCompareDlg_OkDialog_Comparing_Imported_Files {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_Comparing_Imported_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Comparing Models.
/// </summary>
public static string AddPeakCompareDlg_OkDialog_Comparing_Models {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_Comparing_Models", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Comparison name cannot be empty..
/// </summary>
public static string AddPeakCompareDlg_OkDialog_Comparison_name_cannot_be_empty_ {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_Comparison_name_cannot_be_empty_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document has no eligible chromatograms for analysis. Valid chromatograms must not be decoys or iRT standards..
/// </summary>
public static string AddPeakCompareDlg_OkDialog_Document_has_no_eligible_chromatograms_for_analysis___Valid_chromatograms_must_not_be_decoys_or_iRT_standards_ {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_Document_has_no_eligible_chromatograms_for_analysis___" +
"Valid_chromatograms_must_not_be_decoys_or_iRT_standards_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error applying imported peak boundaries: {0}.
/// </summary>
public static string AddPeakCompareDlg_OkDialog_Error_applying_imported_peak_boundaries___0_ {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_Error_applying_imported_peak_boundaries___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error comparing model peak boundaries: {0}.
/// </summary>
public static string AddPeakCompareDlg_OkDialog_Error_comparing_model_peak_boundaries___0_ {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_Error_comparing_model_peak_boundaries___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File path cannot be empty..
/// </summary>
public static string AddPeakCompareDlg_OkDialog_File_path_cannot_be_empty_ {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_File_path_cannot_be_empty_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File path field must contain a path to a valid file..
/// </summary>
public static string AddPeakCompareDlg_OkDialog_File_path_field_must_contain_a_path_to_a_valid_file_ {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_File_path_field_must_contain_a_path_to_a_valid_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Model must be trained before it can be used for peak boundary comparison..
/// </summary>
public static string AddPeakCompareDlg_OkDialog_Model_must_be_trained_before_it_can_be_used_for_peak_boundary_comparison_ {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_Model_must_be_trained_before_it_can_be_used_for_peak_b" +
"oundary_comparison_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The current file or model has no q values or scores to analyze. Either q values or scores are necessary to compare peak picking tools..
/// </summary>
public static string AddPeakCompareDlg_OkDialog_The_current_file_or_model_has_no_q_values_or_scores_to_analyze___Either_q_values_or_scores_are_necessary_to_compare_peak_picking_tools_ {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_The_current_file_or_model_has_no_q_values_or_scores_to" +
"_analyze___Either_q_values_or_scores_are_necessary_to_compare_peak_picking_tools" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The imported file does not contain any peak boundaries for {0} transition group / file pairs. These chromatograms will be treated as if no boundary was selected..
/// </summary>
public static string AddPeakCompareDlg_OkDialog_The_imported_file_does_not_contain_any_peak_boundaries_for__0__transition_group___file_pairs___These_chromatograms_will_be_treated_as_if_no_boundary_was_selected_ {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_The_imported_file_does_not_contain_any_peak_boundaries" +
"_for__0__transition_group___file_pairs___These_chromatograms_will_be_treated_as_" +
"if_no_boundary_was_selected_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The selected file or model does not assign peak boundaries to any chromatograms in the document. Please select a different model or file..
/// </summary>
public static string AddPeakCompareDlg_OkDialog_The_selected_file_or_model_does_not_assign_peak_boundaries_to_any_chromatograms_in_the_document___Please_select_a_different_model_or_file_ {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_The_selected_file_or_model_does_not_assign_peak_bounda" +
"ries_to_any_chromatograms_in_the_document___Please_select_a_different_model_or_f" +
"ile_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The selected model is already included in the list of comparisons. Please choose another model..
/// </summary>
public static string AddPeakCompareDlg_OkDialog_The_selected_model_is_already_included_in_the_list_of_comparisons__Please_choose_another_model_ {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_The_selected_model_is_already_included_in_the_list_of_" +
"comparisons__Please_choose_another_model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is already an imported file with the current name. Please choose another name.
/// </summary>
public static string AddPeakCompareDlg_OkDialog_There_is_already_an_imported_file_with_the_current_name___Please_choose_another_name {
get {
return ResourceManager.GetString("AddPeakCompareDlg_OkDialog_There_is_already_an_imported_file_with_the_current_nam" +
"e___Please_choose_another_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A retention time predictor with that name already exists. Please choose a new name..
/// </summary>
public static string AddRetentionTimePredictorDlg_OkDialog_A_retention_time_predictor_with_that_name_already_exists__Please_choose_a_new_name_ {
get {
return ResourceManager.GetString("AddRetentionTimePredictorDlg_OkDialog_A_retention_time_predictor_with_that_name_a" +
"lready_exists__Please_choose_a_new_name_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adduct "{0}" calls for labeling more {1} atoms than are found in the molecule {2}.
/// </summary>
public static string Adduct_ApplyToMolecule_Adduct___0___calls_for_labeling_more__1__atoms_than_are_found_in_the_molecule__2_ {
get {
return ResourceManager.GetString("Adduct_ApplyToMolecule_Adduct___0___calls_for_labeling_more__1__atoms_than_are_fo" +
"und_in_the_molecule__2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adduct "{0}" calls for removing more {1} atoms than are found in the molecule {2}.
/// </summary>
public static string Adduct_ApplyToMolecule_Adduct___0___calls_for_removing_more__1__atoms_than_are_found_in_the_molecule__2_ {
get {
return ResourceManager.GetString("Adduct_ApplyToMolecule_Adduct___0___calls_for_removing_more__1__atoms_than_are_fo" +
"und_in_the_molecule__2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not parse isotopic label description "{0}" in adduct description "{1}".
///Isotopic labels in adduct descriptions should be in the form of isotope counts (e.g. "2Cl37" or "2Cl374N15"),
///or a mass shift (e.g. "1.234" or "(-1.234)").
///Recognized isotopes include: {2}.
/// </summary>
public static string Adduct_ParseDescription_isotope_error {
get {
return ResourceManager.GetString("Adduct_ParseDescription_isotope_error", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A tool requires Program:{0} Version:{1} and it is not specified with the --tool-program-macro and --tool-program-path commands. Tool Installation Canceled..
/// </summary>
public static string AddZipToolHelper_FindProgramPath_A_tool_requires_Program__0__Version__1__and_it_is_not_specified_with_the___tool_program_macro_and___tool_program_path_commands__Tool_Installation_Canceled_ {
get {
return ResourceManager.GetString("AddZipToolHelper_FindProgramPath_A_tool_requires_Program__0__Version__1__and_it_i" +
"s_not_specified_with_the___tool_program_macro_and___tool_program_path_commands__" +
"Tool_Installation_Canceled_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Package installation not handled in SkylineRunner. If you have already handled package installation use the --tool-ignore-required-packages flag.
/// </summary>
public static string AddZipToolHelper_InstallProgram_Error__Package_installation_not_handled_in_SkylineRunner___If_you_have_already_handled_package_installation_use_the___tool_ignore_required_packages_flag {
get {
return ResourceManager.GetString("AddZipToolHelper_InstallProgram_Error__Package_installation_not_handled_in_Skylin" +
"eRunner___If_you_have_already_handled_package_installation_use_the___tool_ignore" +
"_required_packages_flag", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to and a conflicting tool.
/// </summary>
public static string AddZipToolHelper_ShouldOverwrite__and_a_conflicting_tool {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwrite__and_a_conflicting_tool", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to in the file {0}.
/// </summary>
public static string AddZipToolHelper_ShouldOverwrite__in_the_file__0_ {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwrite__in_the_file__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Conflicting report: {0}.
/// </summary>
public static string AddZipToolHelper_ShouldOverwrite_Conflicting_report___0_ {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwrite_Conflicting_report___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Conflicting reports: {0}.
/// </summary>
public static string AddZipToolHelper_ShouldOverwrite_Conflicting_reports___0_ {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwrite_Conflicting_reports___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Conflicting tool: {0}.
/// </summary>
public static string AddZipToolHelper_ShouldOverwrite_Conflicting_tool___0_ {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwrite_Conflicting_tool___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: There are {0} conflicting reports.
/// </summary>
public static string AddZipToolHelper_ShouldOverwrite_Error__There_are__0__conflicting_reports {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwrite_Error__There_are__0__conflicting_reports", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: There is a conflicting report.
/// </summary>
public static string AddZipToolHelper_ShouldOverwrite_Error__There_is_a_conflicting_report {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwrite_Error__There_is_a_conflicting_report", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: There is a conflicting tool.
/// </summary>
public static string AddZipToolHelper_ShouldOverwrite_Error__There_is_a_conflicting_tool {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwrite_Error__There_is_a_conflicting_tool", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overwriting report: {0}.
/// </summary>
public static string AddZipToolHelper_ShouldOverwrite_Overwriting_report___0_ {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwrite_Overwriting_report___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overwriting reports: {0}.
/// </summary>
public static string AddZipToolHelper_ShouldOverwrite_Overwriting_reports___0_ {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwrite_Overwriting_reports___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overwriting tool: {0}.
/// </summary>
public static string AddZipToolHelper_ShouldOverwrite_Overwriting_tool___0_ {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwrite_Overwriting_tool___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please specify 'overwrite' or 'parallel' with the --tool-zip-conflict-resolution command..
/// </summary>
public static string AddZipToolHelper_ShouldOverwrite_Please_specify__overwrite__or__parallel__with_the___tool_zip_conflict_resolution_command_ {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwrite_Please_specify__overwrite__or__parallel__with_th" +
"e___tool_zip_conflict_resolution_command_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There are annotations with conflicting names. Please use the --tool-zip-overwrite-annotations command..
/// </summary>
public static string AddZipToolHelper_ShouldOverwriteAnnotations_There_are_annotations_with_conflicting_names__Please_use_the___tool_zip_overwrite_annotations_command_ {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwriteAnnotations_There_are_annotations_with_conflictin" +
"g_names__Please_use_the___tool_zip_overwrite_annotations_command_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There are conflicting annotations. Keeping existing..
/// </summary>
public static string AddZipToolHelper_ShouldOverwriteAnnotations_There_are_conflicting_annotations__Keeping_existing_ {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwriteAnnotations_There_are_conflicting_annotations__Ke" +
"eping_existing_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There are conflicting annotations. Overwriting..
/// </summary>
public static string AddZipToolHelper_ShouldOverwriteAnnotations_There_are_conflicting_annotations__Overwriting_ {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwriteAnnotations_There_are_conflicting_annotations__Ov" +
"erwriting_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: the annotation {0} is being overwritten.
/// </summary>
public static string AddZipToolHelper_ShouldOverwriteAnnotations_Warning__the_annotation__0__is_being_overwritten {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwriteAnnotations_Warning__the_annotation__0__is_being_" +
"overwritten", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: the annotation {0} may not be what your tool requires..
/// </summary>
public static string AddZipToolHelper_ShouldOverwriteAnnotations_Warning__the_annotation__0__may_not_be_what_your_tool_requires_ {
get {
return ResourceManager.GetString("AddZipToolHelper_ShouldOverwriteAnnotations_Warning__the_annotation__0__may_not_b" +
"e_what_your_tool_requires_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid byte buffer for checksum..
/// </summary>
public static string AdlerChecksum_MakeForBuff_Invalid_byte_buffer_for_checksum {
get {
return ResourceManager.GetString("AdlerChecksum_MakeForBuff_Invalid_byte_buffer_for_checksum", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure attempting to calculate a checksum for the file {0}.
/// </summary>
public static string AdlerChecksum_MakeForFile_Failure_attempting_to_calculate_a_checksum_for_the_file__0__ {
get {
return ResourceManager.GetString("AdlerChecksum_MakeForFile_Failure_attempting_to_calculate_a_checksum_for_the_file" +
"__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid string "{0}" for checksum.
/// </summary>
public static string AdlerChecksum_MakeForString_Invalid_string___0___for_checksum {
get {
return ResourceManager.GetString("AdlerChecksum_MakeForString_Invalid_string___0___for_checksum", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown.
/// </summary>
public static string AdlerChecksum_ToString_Unknown {
get {
return ResourceManager.GetString("AdlerChecksum_ToString_Unknown", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} CV.
/// </summary>
public static string AggregateOp_AxisTitleCv {
get {
return ResourceManager.GetString("AggregateOp_AxisTitleCv", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} CV (%).
/// </summary>
public static string AggregateOp_AxisTitleCvPercent {
get {
return ResourceManager.GetString("AggregateOp_AxisTitleCvPercent", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Abort.
/// </summary>
public static string AlertDlg_GetDefaultButtonText__Abort {
get {
return ResourceManager.GetString("AlertDlg_GetDefaultButtonText__Abort", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Ignore.
/// </summary>
public static string AlertDlg_GetDefaultButtonText__Ignore {
get {
return ResourceManager.GetString("AlertDlg_GetDefaultButtonText__Ignore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &No.
/// </summary>
public static string AlertDlg_GetDefaultButtonText__No {
get {
return ResourceManager.GetString("AlertDlg_GetDefaultButtonText__No", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Retry.
/// </summary>
public static string AlertDlg_GetDefaultButtonText__Retry {
get {
return ResourceManager.GetString("AlertDlg_GetDefaultButtonText__Retry", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Yes.
/// </summary>
public static string AlertDlg_GetDefaultButtonText__Yes {
get {
return ResourceManager.GetString("AlertDlg_GetDefaultButtonText__Yes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cancel.
/// </summary>
public static string AlertDlg_GetDefaultButtonText_Cancel {
get {
return ResourceManager.GetString("AlertDlg_GetDefaultButtonText_Cancel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to OK.
/// </summary>
public static string AlertDlg_GetDefaultButtonText_OK {
get {
return ResourceManager.GetString("AlertDlg_GetDefaultButtonText_OK", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Message truncated. Press Ctrl+C to copy entire message to the clipboard..
/// </summary>
public static string AlertDlg_TruncateMessage_Message_truncated__Press_Ctrl_C_to_copy_entire_message_to_the_clipboard_ {
get {
return ResourceManager.GetString("AlertDlg_TruncateMessage_Message_truncated__Press_Ctrl_C_to_copy_entire_message_t" +
"o_the_clipboard_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}:{1}.
/// </summary>
public static string AlignedFile_AlignLibraryRetentionTimes__0__1__ {
get {
return ResourceManager.GetString("AlignedFile_AlignLibraryRetentionTimes__0__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Aligned Time.
/// </summary>
public static string AlignmentForm_UpdateGraph_Aligned_Time {
get {
return ResourceManager.GetString("AlignmentForm_UpdateGraph_Aligned_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Alignment of {0} to {1}.
/// </summary>
public static string AlignmentForm_UpdateGraph_Alignment_of__0__to__1_ {
get {
return ResourceManager.GetString("AlignmentForm_UpdateGraph_Alignment_of__0__to__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Outliers.
/// </summary>
public static string AlignmentForm_UpdateGraph_Outliers {
get {
return ResourceManager.GetString("AlignmentForm_UpdateGraph_Outliers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides.
/// </summary>
public static string AlignmentForm_UpdateGraph_Peptides {
get {
return ResourceManager.GetString("AlignmentForm_UpdateGraph_Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides Refined.
/// </summary>
public static string AlignmentForm_UpdateGraph_Peptides_Refined {
get {
return ResourceManager.GetString("AlignmentForm_UpdateGraph_Peptides_Refined", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Regression line.
/// </summary>
public static string AlignmentForm_UpdateGraph_Regression_line {
get {
return ResourceManager.GetString("AlignmentForm_UpdateGraph_Regression_line", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Time from {0}.
/// </summary>
public static string AlignmentForm_UpdateGraph_Time_from__0__ {
get {
return ResourceManager.GetString("AlignmentForm_UpdateGraph_Time_from__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Time from Regression.
/// </summary>
public static string AlignmentForm_UpdateGraph_Time_from_Regression {
get {
return ResourceManager.GetString("AlignmentForm_UpdateGraph_Time_from_Regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Waiting for retention time alignment.
/// </summary>
public static string AlignmentForm_UpdateGraph_Waiting_for_retention_time_alignment {
get {
return ResourceManager.GetString("AlignmentForm_UpdateGraph_Waiting_for_retention_time_alignment", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cancel import.
/// </summary>
public static string AllChromatogramsGraph_btnCancel_Click_Cancel_import {
get {
return ResourceManager.GetString("AllChromatogramsGraph_btnCancel_Click_Cancel_import", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cancel file.
/// </summary>
public static string AllChromatogramsGraph_btnCancelFile_Click_Cancel_file {
get {
return ResourceManager.GetString("AllChromatogramsGraph_btnCancelFile_Click_Cancel_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cancel file import.
/// </summary>
public static string AllChromatogramsGraph_Cancel_Cancel_file_import {
get {
return ResourceManager.GetString("AllChromatogramsGraph_Cancel_Cancel_file_import", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Close.
/// </summary>
public static string AllChromatogramsGraph_Finish_Close {
get {
return ResourceManager.GetString("AllChromatogramsGraph_Finish_Close", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove failed file.
/// </summary>
public static string AllChromatogramsGraph_RemoveFailedFile_Remove_failed_file {
get {
return ResourceManager.GetString("AllChromatogramsGraph_RemoveFailedFile_Remove_failed_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retry import results.
/// </summary>
public static string AllChromatogramsGraph_Retry_Retry_import_results {
get {
return ResourceManager.GetString("AllChromatogramsGraph_Retry_Retry_import_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} of {1} files.
/// </summary>
public static string AllChromatogramsGraph_UpdateStatus__0__of__1__files {
get {
return ResourceManager.GetString("AllChromatogramsGraph_UpdateStatus__0__of__1__files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Hide.
/// </summary>
public static string AllChromatogramsGraph_UpdateStatus_Hide {
get {
return ResourceManager.GetString("AllChromatogramsGraph_UpdateStatus_Hide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Joining chromatograms....
/// </summary>
public static string AllChromatogramsGraph_UpdateStatus_Joining_chromatograms___ {
get {
return ResourceManager.GetString("AllChromatogramsGraph_UpdateStatus_Joining_chromatograms___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap AllIonsStatusButton {
get {
object obj = ResourceManager.GetObject("AllIonsStatusButton", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Invalid amino acid '{0}' found in the value '{1}'..
/// </summary>
public static string AminoAcid_ValidateAAList_Invalid_amino_acid__0__found_in_the_value__1__ {
get {
return ResourceManager.GetString("AminoAcid_ValidateAAList_Invalid_amino_acid__0__found_in_the_value__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The amino acid '{0}' is repeated in the value '{1}'..
/// </summary>
public static string AminoAcid_ValidateAAList_The_amino_acid__0__is_repeated_in_the_value__1__ {
get {
return ResourceManager.GetString("AminoAcid_ValidateAAList_The_amino_acid__0__is_repeated_in_the_value__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap AnnotatedSpectum {
get {
object obj = ResourceManager.GetObject("AnnotatedSpectum", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Annotation: .
/// </summary>
public static string Annotation_DisambiguationPrefix_Annotation__ {
get {
return ResourceManager.GetString("Annotation_DisambiguationPrefix_Annotation__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides.
/// </summary>
public static string AnnotationDef_AnnotationTarget_Peptides {
get {
return ResourceManager.GetString("AnnotationDef_AnnotationTarget_Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor Results.
/// </summary>
public static string AnnotationDef_AnnotationTarget_PrecursorResults {
get {
return ResourceManager.GetString("AnnotationDef_AnnotationTarget_PrecursorResults", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursors.
/// </summary>
public static string AnnotationDef_AnnotationTarget_Precursors {
get {
return ResourceManager.GetString("AnnotationDef_AnnotationTarget_Precursors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Proteins.
/// </summary>
public static string AnnotationDef_AnnotationTarget_Proteins {
get {
return ResourceManager.GetString("AnnotationDef_AnnotationTarget_Proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicates.
/// </summary>
public static string AnnotationDef_AnnotationTarget_Replicates {
get {
return ResourceManager.GetString("AnnotationDef_AnnotationTarget_Replicates", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition Results.
/// </summary>
public static string AnnotationDef_AnnotationTarget_TransitionResults {
get {
return ResourceManager.GetString("AnnotationDef_AnnotationTarget_TransitionResults", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transitions.
/// </summary>
public static string AnnotationDef_AnnotationTarget_Transitions {
get {
return ResourceManager.GetString("AnnotationDef_AnnotationTarget_Transitions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid value.
/// </summary>
public static string AnnotationDef_ValidationErrorMessage_Invalid_value {
get {
return ResourceManager.GetString("AnnotationDef_ValidationErrorMessage_Invalid_value", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Value must be a number.
/// </summary>
public static string AnnotationDef_ValidationErrorMessage_Value_must_be_a_number {
get {
return ResourceManager.GetString("AnnotationDef_ValidationErrorMessage_Value_must_be_a_number", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Annotations:.
/// </summary>
public static string AnnotationDefList_Label_Annotations {
get {
return ResourceManager.GetString("AnnotationDefList_Label_Annotations", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Define Annotations.
/// </summary>
public static string AnnotationDefList_Title_Define_Annotations {
get {
return ResourceManager.GetString("AnnotationDefList_Title_Define_Annotations", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to False.
/// </summary>
public static string AnnotationHelper_GetReplicateIndicices_False {
get {
return ResourceManager.GetString("AnnotationHelper_GetReplicateIndicices_False", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to True.
/// </summary>
public static string AnnotationHelper_GetReplicateIndicices_True {
get {
return ResourceManager.GetString("AnnotationHelper_GetReplicateIndicices_True", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Annotation conflict for '{0}' found attempting to merge annotations..
/// </summary>
public static string Annotations_Merge_Annotation_conflict_for__0__found_attempting_to_merge_annotations {
get {
return ResourceManager.GetString("Annotations_Merge_Annotation_conflict_for__0__found_attempting_to_merge_annotatio" +
"ns", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Not enough data.
/// </summary>
public static string AreaCVHistogram2DGraphPane_Draw_Not_enough_data {
get {
return ResourceManager.GetString("AreaCVHistogram2DGraphPane_Draw_Not_enough_data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculating ....
/// </summary>
public static string AreaCVHistogram2DGraphPane_UpdateGraph_Calculating____ {
get {
return ResourceManager.GetString("AreaCVHistogram2DGraphPane_UpdateGraph_Calculating____", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CV.
/// </summary>
public static string AreaCVHistogram2DGraphPane_UpdateGraph_CV {
get {
return ResourceManager.GetString("AreaCVHistogram2DGraphPane_UpdateGraph_CV", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Log10 Mean Area.
/// </summary>
public static string AreaCvHistogram2DGraphPane_UpdateGraph_Log10_Mean_Area {
get {
return ResourceManager.GetString("AreaCvHistogram2DGraphPane_UpdateGraph_Log10_Mean_Area", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Median: {0}.
/// </summary>
public static string AreaCVHistogram2DGraphPane_UpdateGraph_Median___0_ {
get {
return ResourceManager.GetString("AreaCVHistogram2DGraphPane_UpdateGraph_Median___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculating ....
/// </summary>
public static string AreaCVHistogramGraphPane_AddLabels_Calculating____ {
get {
return ResourceManager.GetString("AreaCVHistogramGraphPane_AddLabels_Calculating____", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Median: {0}.
/// </summary>
public static string AreaCVHistogramGraphPane_AddLabels_Median___0_ {
get {
return ResourceManager.GetString("AreaCVHistogramGraphPane_AddLabels_Median___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Not enough data.
/// </summary>
public static string AreaCVHistogramGraphPane_AddLabels_Not_enough_data {
get {
return ResourceManager.GetString("AreaCVHistogramGraphPane_AddLabels_Not_enough_data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Below {0}: {1}.
/// </summary>
public static string AreaCVHistogramGraphPane_UpdateGraph_Below__0____1_ {
get {
return ResourceManager.GetString("AreaCVHistogramGraphPane_UpdateGraph_Below__0____1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CV.
/// </summary>
public static string AreaCVHistogramGraphPane_UpdateGraph_CV {
get {
return ResourceManager.GetString("AreaCVHistogramGraphPane_UpdateGraph_CV", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Frequency.
/// </summary>
public static string AreaCVHistogramGraphPane_UpdateGraph_Frequency {
get {
return ResourceManager.GetString("AreaCVHistogramGraphPane_UpdateGraph_Frequency", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Global standards.
/// </summary>
public static string AreaCVToolbar_UpdateUI_Global_standards {
get {
return ResourceManager.GetString("AreaCVToolbar_UpdateUI_Global_standards", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid CV cutoff entered.
/// </summary>
public static string AreaCvToolbarProperties_btnOk_Click_Invalid_CV_cutoff_entered {
get {
return ResourceManager.GetString("AreaCvToolbarProperties_btnOk_Click_Invalid_CV_cutoff_entered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid maximum CV entered.
/// </summary>
public static string AreaCVToolbarProperties_btnOk_Click_Invalid_maximum_CV_entered {
get {
return ResourceManager.GetString("AreaCVToolbarProperties_btnOk_Click_Invalid_maximum_CV_entered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid maximum frequency entered.
/// </summary>
public static string AreaCvToolbarProperties_btnOk_Click_Invalid_maximum_frequency_entered {
get {
return ResourceManager.GetString("AreaCvToolbarProperties_btnOk_Click_Invalid_maximum_frequency_entered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid maximum log10 area entered.
/// </summary>
public static string AreaCVToolbarProperties_btnOk_Click_Invalid_maximum_log_10_area_entered {
get {
return ResourceManager.GetString("AreaCVToolbarProperties_btnOk_Click_Invalid_maximum_log_10_area_entered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid minimum log10 area entered.
/// </summary>
public static string AreaCVToolbarProperties_btnOk_Click_Invalid_minimum_log_10_area_entered {
get {
return ResourceManager.GetString("AreaCVToolbarProperties_btnOk_Click_Invalid_minimum_log_10_area_entered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid Q value entered.
/// </summary>
public static string AreaCvToolbarProperties_btnOk_Click_Invalid_Q_value_entered {
get {
return ResourceManager.GetString("AreaCvToolbarProperties_btnOk_Click_Invalid_Q_value_entered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The maximum log10 area has to be greater than the minimum log10 area.
/// </summary>
public static string AreaCVToolbarProperties_btnOk_Click_The_maximum_log10_area_has_to_be_greater_than_the_minimum_log10_area {
get {
return ResourceManager.GetString("AreaCVToolbarProperties_btnOk_Click_The_maximum_log10_area_has_to_be_greater_than" +
"_the_minimum_log10_area", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak Area.
/// </summary>
public static string AreaPeptideGraphPane_UpdateAxes_Peak_Area {
get {
return ResourceManager.GetString("AreaPeptideGraphPane_UpdateAxes_Peak_Area", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Expected.
/// </summary>
public static string AreaReplicateGraphPane_InitFromData_Expected {
get {
return ResourceManager.GetString("AreaReplicateGraphPane_InitFromData_Expected", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library.
/// </summary>
public static string AreaReplicateGraphPane_InitFromData_Library {
get {
return ResourceManager.GetString("AreaReplicateGraphPane_InitFromData_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No results available.
/// </summary>
public static string AreaReplicateGraphPane_UpdateGraph_No_results_available {
get {
return ResourceManager.GetString("AreaReplicateGraphPane_UpdateGraph_No_results_available", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak Area.
/// </summary>
public static string AreaReplicateGraphPane_UpdateGraph_Peak_Area {
get {
return ResourceManager.GetString("AreaReplicateGraphPane_UpdateGraph_Peak_Area", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak Area Normalized.
/// </summary>
public static string AreaReplicateGraphPane_UpdateGraph_Peak_Area_Normalized {
get {
return ResourceManager.GetString("AreaReplicateGraphPane_UpdateGraph_Peak_Area_Normalized", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak Area Percentage.
/// </summary>
public static string AreaReplicateGraphPane_UpdateGraph_Peak_Area_Percentage {
get {
return ResourceManager.GetString("AreaReplicateGraphPane_UpdateGraph_Peak_Area_Percentage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak Area Ratio To {0}.
/// </summary>
public static string AreaReplicateGraphPane_UpdateGraph_Peak_Area_Ratio_To__0_ {
get {
return ResourceManager.GetString("AreaReplicateGraphPane_UpdateGraph_Peak_Area_Ratio_To__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Percent of Regression Peak Area.
/// </summary>
public static string AreaReplicateGraphPane_UpdateGraph_Percent_of_Regression_Peak_Area {
get {
return ResourceManager.GetString("AreaReplicateGraphPane_UpdateGraph_Percent_of_Regression_Peak_Area", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Select a peptide to see the peak area graph.
/// </summary>
public static string AreaReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_peak_area_graph {
get {
return ResourceManager.GetString("AreaReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_peak_area_graph", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Step {0}.
/// </summary>
public static string AreaReplicateGraphPane_UpdateGraph_Step__0_ {
get {
return ResourceManager.GetString("AreaReplicateGraphPane_UpdateGraph_Step__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Associated proteins.
/// </summary>
public static string AssociateProteinsDlg_ApplyChanges_Associated_proteins {
get {
return ResourceManager.GetString("AssociateProteinsDlg_ApplyChanges_Associated_proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No matches were found using the imported fasta file..
/// </summary>
public static string AssociateProteinsDlg_FindProteinMatchesWithFasta_No_matches_were_found_using_the_imported_fasta_file_ {
get {
return ResourceManager.GetString("AssociateProteinsDlg_FindProteinMatchesWithFasta_No_matches_were_found_using_the_" +
"imported_fasta_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No background proteome defined, see the Digestion tab in Peptide Settings for more information..
/// </summary>
public static string AssociateProteinsDlg_UseBackgroundProteome_No_background_proteome_defined {
get {
return ResourceManager.GetString("AssociateProteinsDlg_UseBackgroundProteome_No_background_proteome_defined", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No matches were found using the background proteome..
/// </summary>
public static string AssociateProteinsDlg_UseBackgroundProteome_No_matches_were_found_using_the_background_proteome_ {
get {
return ResourceManager.GetString("AssociateProteinsDlg_UseBackgroundProteome_No_matches_were_found_using_the_backgr" +
"ound_proteome_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There was an error reading from the file..
/// </summary>
public static string AssociateProteinsDlg_UseFastaFile_There_was_an_error_reading_from_the_file_ {
get {
return ResourceManager.GetString("AssociateProteinsDlg_UseFastaFile_There_was_an_error_reading_from_the_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Intensity.
/// </summary>
public static string AsyncChromatogramsGraph_AsyncChromatogramsGraph_Intensity {
get {
return ResourceManager.GetString("AsyncChromatogramsGraph_AsyncChromatogramsGraph_Intensity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention Time.
/// </summary>
public static string AsyncChromatogramsGraph_AsyncChromatogramsGraph_Retention_Time {
get {
return ResourceManager.GetString("AsyncChromatogramsGraph_AsyncChromatogramsGraph_Retention_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}, sample {1}.
/// </summary>
public static string AsyncChromatogramsGraph_Render__0___sample__1_ {
get {
return ResourceManager.GetString("AsyncChromatogramsGraph_Render__0___sample__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Canceled.
/// </summary>
public static string AsyncChromatogramsGraph2_AsyncChromatogramsGraph2_Canceled {
get {
return ResourceManager.GetString("AsyncChromatogramsGraph2_AsyncChromatogramsGraph2_Canceled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Examining background proteome for uniqueness constraints.
/// </summary>
public static string BackgroundProteome_GetUniquenessDict_Examining_background_proteome_for_uniqueness_constraints {
get {
return ResourceManager.GetString("BackgroundProteome_GetUniquenessDict_Examining_background_proteome_for_uniqueness" +
"_constraints", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Background Proteomes:.
/// </summary>
public static string BackgroundProteomeList_Label_Background_Proteomes {
get {
return ResourceManager.GetString("BackgroundProteomeList_Label_Background_Proteomes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Background Proteomes.
/// </summary>
public static string BackgroundProteomeList_Title_Edit_Background_Proteomes {
get {
return ResourceManager.GetString("BackgroundProteomeList_Title_Edit_Background_Proteomes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed updating background proteome {0}..
/// </summary>
public static string BackgroundProteomeManager_LoadBackground_Failed_updating_background_proteome__0__ {
get {
return ResourceManager.GetString("BackgroundProteomeManager_LoadBackground_Failed_updating_background_proteome__0__" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Resolving protein details for {0} proteome.
/// </summary>
public static string BackgroundProteomeManager_LoadBackground_Resolving_protein_details_for__0__proteome {
get {
return ResourceManager.GetString("BackgroundProteomeManager_LoadBackground_Resolving_protein_details_for__0__proteo" +
"me", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to rename temporary file to {0}..
/// </summary>
public static string BackgroundProteomeManager_LoadBackground_Unable_to_rename_temporary_file_to__0__ {
get {
return ResourceManager.GetString("BackgroundProteomeManager_LoadBackground_Unable_to_rename_temporary_file_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to After minimizing, the cache file will be reduced to {0:0%} its current size.
/// </summary>
public static string BackgroundWorker_UpdateStatistics_After_minimizing_the_cache_file_will_be_reduced_to__0__its_current_size {
get {
return ResourceManager.GetString("BackgroundWorker_UpdateStatistics_After_minimizing_the_cache_file_will_be_reduced" +
"_to__0__its_current_size", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Computing space savings ({0}% complete).
/// </summary>
public static string BackgroundWorker_UpdateStatistics_Computing_space_savings__0__complete {
get {
return ResourceManager.GetString("BackgroundWorker_UpdateStatistics_Computing_space_savings__0__complete", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The current size of the cache file is {0:fs}.
/// </summary>
public static string BackgroundWorker_UpdateStatistics_The_current_size_of_the_cache_file_is__0__fs {
get {
return ResourceManager.GetString("BackgroundWorker_UpdateStatistics_The_current_size_of_the_cache_file_is__0__fs", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data truncation in library header. File may be corrupted..
/// </summary>
public static string BiblioSpecLibrary_Load_Data_truncation_in_library_header_File_may_be_corrupted {
get {
return ResourceManager.GetString("BiblioSpecLibrary_Load_Data_truncation_in_library_header_File_may_be_corrupted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data truncation in spectrum header. File may be corrupted..
/// </summary>
public static string BiblioSpecLibrary_Load_Data_truncation_in_spectrum_header_File_may_be_corrupted {
get {
return ResourceManager.GetString("BiblioSpecLibrary_Load_Data_truncation_in_spectrum_header_File_may_be_corrupted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data truncation in spectrum sequence. File may be corrupted..
/// </summary>
public static string BiblioSpecLibrary_Load_Data_truncation_in_spectrum_sequence_File_may_be_corrupted {
get {
return ResourceManager.GetString("BiblioSpecLibrary_Load_Data_truncation_in_spectrum_sequence_File_may_be_corrupted" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed loading library '{0}'..
/// </summary>
public static string BiblioSpecLibrary_Load_Failed_loading_library__0__ {
get {
return ResourceManager.GetString("BiblioSpecLibrary_Load_Failed_loading_library__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid precursor charge found. File may be corrupted..
/// </summary>
public static string BiblioSpecLibrary_Load_Invalid_precursor_charge_found_File_may_be_corrupted {
get {
return ResourceManager.GetString("BiblioSpecLibrary_Load_Invalid_precursor_charge_found_File_may_be_corrupted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading {0} library.
/// </summary>
public static string BiblioSpecLibrary_Load_Loading__0__library {
get {
return ResourceManager.GetString("BiblioSpecLibrary_Load_Loading__0__library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure trying to read peaks.
/// </summary>
public static string BiblioSpecLibrary_ReadSpectrum_Failure_trying_to_read_peaks {
get {
return ResourceManager.GetString("BiblioSpecLibrary_ReadSpectrum_Failure_trying_to_read_peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Legacy BiblioSpec Library.
/// </summary>
public static string BiblioSpecLibrary_SpecFilter_Legacy_BiblioSpec_Library {
get {
return ResourceManager.GetString("BiblioSpecLibrary_SpecFilter_Legacy_BiblioSpec_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The library built successfully. Spectra matching the following peptides had multiple ambiguous peptide matches and were excluded:.
/// </summary>
public static string BiblioSpecLiteBuilder_AmbiguousMatches_The_library_built_successfully__Spectra_matching_the_following_peptides_had_multiple_ambiguous_peptide_matches_and_were_excluded_ {
get {
return ResourceManager.GetString("BiblioSpecLiteBuilder_AmbiguousMatches_The_library_built_successfully__Spectra_ma" +
"tching_the_following_peptides_had_multiple_ambiguous_peptide_matches_and_were_ex" +
"cluded_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Building {0} library.
/// </summary>
public static string BiblioSpecLiteBuilder_BuildLibrary_Building__0__library {
get {
return ResourceManager.GetString("BiblioSpecLiteBuilder_BuildLibrary_Building__0__library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed trying to build the library {0}..
/// </summary>
public static string BiblioSpecLiteBuilder_BuildLibrary_Failed_trying_to_build_the_library__0__ {
get {
return ResourceManager.GetString("BiblioSpecLiteBuilder_BuildLibrary_Failed_trying_to_build_the_library__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed trying to build the redundant library {0}..
/// </summary>
public static string BiblioSpecLiteBuilder_BuildLibrary_Failed_trying_to_build_the_redundant_library__0__ {
get {
return ResourceManager.GetString("BiblioSpecLiteBuilder_BuildLibrary_Failed_trying_to_build_the_redundant_library__" +
"0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Preparing to build library.
/// </summary>
public static string BiblioSpecLiteBuilder_BuildLibrary_Preparing_to_build_library {
get {
return ResourceManager.GetString("BiblioSpecLiteBuilder_BuildLibrary_Preparing_to_build_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Embedded.
/// </summary>
public static string BiblioSpecLiteBuilder_Embedded {
get {
return ResourceManager.GetString("BiblioSpecLiteBuilder_Embedded", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Aligning library retention times.
/// </summary>
public static string BiblioSpecLiteLibrary_CalculateFileRetentionTimeAlignments_Aligning_library_retention_times {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_CalculateFileRetentionTimeAlignments_Aligning_library_reten" +
"tion_times", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed reading library header for {0}..
/// </summary>
public static string BiblioSpecLiteLibrary_CreateCache_Failed_reading_library_header_for__0__ {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_CreateCache_Failed_reading_library_header_for__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No spectra were found in the library {0}.
/// </summary>
public static string BiblioSpecLiteLibrary_CreateCache_No_spectra_were_found_in_the_library__0__ {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_CreateCache_No_spectra_were_found_in_the_library__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to get a valid count of spectra in the library {0}.
/// </summary>
public static string BiblioSpecLiteLibrary_CreateCache_Unable_to_get_a_valid_count_of_spectra_in_the_library__0__ {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_CreateCache_Unable_to_get_a_valid_count_of_spectra_in_the_l" +
"ibrary__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed attempting to filter redundant library {0} to {1}.
/// </summary>
public static string BiblioSpecLiteLibrary_DeleteDataFiles_Failed_attempting_to_filter_redundant_library__0__to__1_ {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_DeleteDataFiles_Failed_attempting_to_filter_redundant_libra" +
"ry__0__to__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removing library runs from document library..
/// </summary>
public static string BiblioSpecLiteLibrary_DeleteDataFiles_Removing_library_runs_from_document_library_ {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_DeleteDataFiles_Removing_library_runs_from_document_library" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Building binary cache for {0} library.
/// </summary>
public static string BiblioSpecLiteLibrary_Load_Building_binary_cache_for__0__library {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_Load_Building_binary_cache_for__0__library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed loading library '{0}'..
/// </summary>
public static string BiblioSpecLiteLibrary_Load_Failed_loading_library__0__ {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_Load_Failed_loading_library__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid precursor charge {0} found. File may be corrupted..
/// </summary>
public static string BiblioSpecLiteLibrary_Load_Invalid_precursor_charge__0__found__File_may_be_corrupted {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_Load_Invalid_precursor_charge__0__found__File_may_be_corrup" +
"ted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Spectrum peaks {0} excede the maximum allowed {1}..
/// </summary>
public static string BiblioSpecLiteLibrary_ReadRedundantSpectrum_Spectrum_peaks__0__excede_the_maximum_allowed__1__ {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_ReadRedundantSpectrum_Spectrum_peaks__0__excede_the_maximum" +
"_allowed__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The redundant library {0} does not exist..
/// </summary>
public static string BiblioSpecLiteLibrary_ReadRedundantSpectrum_The_redundant_library__0__does_not_exist {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_ReadRedundantSpectrum_The_redundant_library__0__does_not_ex" +
"ist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected SQLite failure reading {0}..
/// </summary>
public static string BiblioSpecLiteLibrary_ReadSpectrum_Unexpected_SQLite_failure_reading__0__ {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_ReadSpectrum_Unexpected_SQLite_failure_reading__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to get a valid count of all spectra in the library {0}.
/// </summary>
public static string BiblioSpecLiteLibrary_RetentionTimesPsmCount_Unable_to_get_a_valid_count_of_all_spectra_in_the_library__0__ {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_RetentionTimesPsmCount_Unable_to_get_a_valid_count_of_all_s" +
"pectra_in_the_library__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to BiblioSpec Library.
/// </summary>
public static string BiblioSpecLiteLibrary_SpecFilter_BiblioSpec_Library {
get {
return ResourceManager.GetString("BiblioSpecLiteLibrary_SpecFilter_BiblioSpec_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading {0} library,.
/// </summary>
public static string BiblioSpecLiteLibraryLoadLoading__0__library {
get {
return ResourceManager.GetString("BiblioSpecLiteLibraryLoadLoading__0__library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to BiblioSpec Library.
/// </summary>
public static string BiblioSpecLiteSpec_FILTER_BLIB_BiblioSpec_Library {
get {
return ResourceManager.GetString("BiblioSpecLiteSpec_FILTER_BLIB_BiblioSpec_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed parsing adduct description "{0}".
/// </summary>
public static string BioMassCalc_ApplyAdductToFormula_Failed_parsing_adduct_description___0__ {
get {
return ResourceManager.GetString("BioMassCalc_ApplyAdductToFormula_Failed_parsing_adduct_description___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed parsing adduct description "{0}": declared charge {1} does not agree with calculated charge {2}.
/// </summary>
public static string BioMassCalc_ApplyAdductToFormula_Failed_parsing_adduct_description___0____declared_charge__1__does_not_agree_with_calculated_charge__2_ {
get {
return ResourceManager.GetString("BioMassCalc_ApplyAdductToFormula_Failed_parsing_adduct_description___0____declare" +
"d_charge__1__does_not_agree_with_calculated_charge__2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown symbol "{0}" in adduct description "{1}".
/// </summary>
public static string BioMassCalc_ApplyAdductToFormula_Unknown_symbol___0___in_adduct_description___1__ {
get {
return ResourceManager.GetString("BioMassCalc_ApplyAdductToFormula_Unknown_symbol___0___in_adduct_description___1__" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The expression '{0}' is not a valid chemical formula..
/// </summary>
public static string BioMassCalc_CalculateMass_The_expression__0__is_not_a_valid_chemical_formula {
get {
return ResourceManager.GetString("BioMassCalc_CalculateMass_The_expression__0__is_not_a_valid_chemical_formula", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Supported chemical symbols include: .
/// </summary>
public static string BioMassCalc_FormatArgumentException__Supported_chemical_symbols_include__ {
get {
return ResourceManager.GetString("BioMassCalc_FormatArgumentException__Supported_chemical_symbols_include__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fixing isotope abundance masses requires a monoisotopic mass calculator.
/// </summary>
public static string BioMassCalc_SynchMasses_Fixing_isotope_abundance_masses_requires_a_monoisotopic_mass_calculator {
get {
return ResourceManager.GetString("BioMassCalc_SynchMasses_Fixing_isotope_abundance_masses_requires_a_monoisotopic_m" +
"ass_calculator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Blank {
get {
object obj = ResourceManager.GetObject("Blank", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Error getting database Id for file {0}..
/// </summary>
public static string BlibDb_BuildRefSpectra_Error_getting_database_Id_for_file__0__ {
get {
return ResourceManager.GetString("BlibDb_BuildRefSpectra_Error_getting_database_Id_for_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Multiple reference spectra found for peptide {0} in the library {1}..
/// </summary>
public static string BlibDb_BuildRefSpectra_Multiple_reference_spectra_found_for_peptide__0__in_the_library__1__ {
get {
return ResourceManager.GetString("BlibDb_BuildRefSpectra_Multiple_reference_spectra_found_for_peptide__0__in_the_li" +
"brary__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Creating spectral library for imported transition list.
/// </summary>
public static string BlibDb_CreateLibraryFromSpectra_Creating_spectral_library_for_imported_transition_list {
get {
return ResourceManager.GetString("BlibDb_CreateLibraryFromSpectra_Creating_spectral_library_for_imported_transition" +
"_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Libraries must be fully loaded before they can be minimized..
/// </summary>
public static string BlibDb_MinimizeLibraries_Libraries_must_be_fully_loaded_before_they_can_be_minimzed {
get {
return ResourceManager.GetString("BlibDb_MinimizeLibraries_Libraries_must_be_fully_loaded_before_they_can_be_minimz" +
"ed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Minimizing library {0}.
/// </summary>
public static string BlibDb_MinimizeLibrary_Minimizing_library__0__ {
get {
return ResourceManager.GetString("BlibDb_MinimizeLibrary_Minimizing_library__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Expected sorted data.
/// </summary>
public static string Block_VerifySort_Expected_sorted_data {
get {
return ResourceManager.GetString("Block_VerifySort_Expected_sorted_data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No such chrominfo: {0}.
/// </summary>
public static string BookmarkEnumerator_Current_No_such_chrominfo__0__ {
get {
return ResourceManager.GetString("BookmarkEnumerator_Current_No_such_chrominfo__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No such node: {0}.
/// </summary>
public static string BookmarkEnumerator_Current_No_such_node__0__ {
get {
return ResourceManager.GetString("BookmarkEnumerator_Current_No_such_node__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <NoPeptide>.
/// </summary>
public static string BookmarkEnumerator_GetLocationName_NoPeptide {
get {
return ResourceManager.GetString("BookmarkEnumerator_GetLocationName_NoPeptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <UnknownFile>.
/// </summary>
public static string BookmarkEnumerator_GetLocationName_UnknownFile {
get {
return ResourceManager.GetString("BookmarkEnumerator_GetLocationName_UnknownFile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results.
/// </summary>
public static string BookmarkEnumerator_GetLocationType_Results {
get {
return ResourceManager.GetString("BookmarkEnumerator_GetLocationType_Results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Protein.
/// </summary>
public static string BookmarkEnumerator_GetNodeTypeName_Protein {
get {
return ResourceManager.GetString("BookmarkEnumerator_GetNodeTypeName_Protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown.
/// </summary>
public static string BookmarkEnumerator_GetNodeTypeName_Unknown {
get {
return ResourceManager.GetString("BookmarkEnumerator_GetNodeTypeName_Unknown", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error copying template file..
/// </summary>
public static string BrukerTimsTofMethodExporter_ExportMethod_Error_copying_template_file_ {
get {
return ResourceManager.GetString("BrukerTimsTofMethodExporter_ExportMethod_Error_copying_template_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Getting scheduling....
/// </summary>
public static string BrukerTimsTofMethodExporter_ExportMethod_Getting_scheduling___ {
get {
return ResourceManager.GetString("BrukerTimsTofMethodExporter_ExportMethod_Getting_scheduling___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scheduling failure (no targets?).
/// </summary>
public static string BrukerTimsTofMethodExporter_ExportMethod_Scheduling_failure__no_targets__ {
get {
return ResourceManager.GetString("BrukerTimsTofMethodExporter_ExportMethod_Scheduling_failure__no_targets__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Template is required for method export..
/// </summary>
public static string BrukerTimsTofMethodExporter_ExportMethod_Template_is_required_for_method_export_ {
get {
return ResourceManager.GetString("BrukerTimsTofMethodExporter_ExportMethod_Template_is_required_for_method_export_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to add the FASTA file {0}..
/// </summary>
public static string BuildBackgroundProteomeDlg_AddFastaFile_An_error_occurred_attempting_to_add_the_FASTA_file__0__ {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_AddFastaFile_An_error_occurred_attempting_to_add_the_F" +
"ASTA_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The added file included {0} repeated protein sequences. Their names were added as aliases to ensure the protein list contains only one copy of each sequence..
/// </summary>
public static string BuildBackgroundProteomeDlg_AddFastaFile_The_added_file_included__0__repeated_protein_sequences__Their_names_were_added_as_aliases_to_ensure_the_protein_list_contains_only_one_copy_of_each_sequence_ {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_AddFastaFile_The_added_file_included__0__repeated_prot" +
"ein_sequences__Their_names_were_added_as_aliases_to_ensure_the_protein_list_cont" +
"ains_only_one_copy_of_each_sequence_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add FASTA File.
/// </summary>
public static string BuildBackgroundProteomeDlg_btnAddFastaFile_Click_Add_FASTA_File {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_btnAddFastaFile_Click_Add_FASTA_File", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to create the proteome file {0}..
/// </summary>
public static string BuildBackgroundProteomeDlg_btnCreate_Click_An_error_occurred_attempting_to_create_the_proteome_file__0__ {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_btnCreate_Click_An_error_occurred_attempting_to_create" +
"_the_proteome_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Create Background Proteome.
/// </summary>
public static string BuildBackgroundProteomeDlg_btnCreate_Click_Create_Background_Proteome {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_btnCreate_Click_Create_Background_Proteome", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Open Background Proteome.
/// </summary>
public static string BuildBackgroundProteomeDlg_btnOpen_Click_Open_Background_Protoeme {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_btnOpen_Click_Open_Background_Protoeme", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Proteome File.
/// </summary>
public static string BuildBackgroundProteomeDlg_FILTER_PROTDB_Proteome_File {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_FILTER_PROTDB_Proteome_File", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Choose a valid proteome file, or click the 'Create' button to create a new one from FASTA files..
/// </summary>
public static string BuildBackgroundProteomeDlg_OkDialog_Choose_a_valid_proteome_file__or_click_the__Create__button_to_create_a_new_one_from_FASTA_files {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_OkDialog_Choose_a_valid_proteome_file__or_click_the__C" +
"reate__button_to_create_a_new_one_from_FASTA_files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please specify a full path to the proteome file..
/// </summary>
public static string BuildBackgroundProteomeDlg_OkDialog_Please_specify_a_full_path_to_the_proteome_file {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_OkDialog_Please_specify_a_full_path_to_the_proteome_fi" +
"le", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The background proteome '{0}' already exists..
/// </summary>
public static string BuildBackgroundProteomeDlg_OkDialog_The_background_proteome__0__already_exists {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_OkDialog_The_background_proteome__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The proteome file {0} does not exist..
/// </summary>
public static string BuildBackgroundProteomeDlg_OkDialog_The_proteome_file__0__does_not_exist {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_OkDialog_The_proteome_file__0__does_not_exist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The proteome file is not valid..
/// </summary>
public static string BuildBackgroundProteomeDlg_OkDialog_The_proteome_file_is_not_valid {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_OkDialog_The_proteome_file_is_not_valid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must specify a proteome file..
/// </summary>
public static string BuildBackgroundProteomeDlg_OkDialog_You_must_specify_a_proteome_file {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_OkDialog_You_must_specify_a_proteome_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Click the 'Add File' button to add a FASTA file, and create a new proteome file..
/// </summary>
public static string BuildBackgroundProteomeDlg_RefreshStatus_Click_the_Add_File_button_to_add_a_FASTA_file_and_create_a_new_proteome_file {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_RefreshStatus_Click_the_Add_File_button_to_add_a_FASTA" +
"_file_and_create_a_new_proteome_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Click the 'Open' button to choose an existing proteome file, or click the 'Create' button to create a new proteome file..
/// </summary>
public static string BuildBackgroundProteomeDlg_RefreshStatus_Click_the_Open_button_to_choose_an_existing_proteome_file_or_click_the_Create_button_to_create_a_new_proteome_file {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_RefreshStatus_Click_the_Open_button_to_choose_an_exist" +
"ing_proteome_file_or_click_the_Create_button_to_create_a_new_proteome_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading protein information from {0}.
/// </summary>
public static string BuildBackgroundProteomeDlg_RefreshStatus_Loading_protein_information_from__0__ {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_RefreshStatus_Loading_protein_information_from__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading Proteome File.
/// </summary>
public static string BuildBackgroundProteomeDlg_RefreshStatus_Loading_Proteome_File {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_RefreshStatus_Loading_Proteome_File", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The proteome file contains {0} proteins..
/// </summary>
public static string BuildBackgroundProteomeDlg_RefreshStatus_The_proteome_file_contains__0__proteins {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_RefreshStatus_The_proteome_file_contains__0__proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The proteome has already been digested..
/// </summary>
public static string BuildBackgroundProteomeDlg_RefreshStatus_The_proteome_has_already_been_digested {
get {
return ResourceManager.GetString("BuildBackgroundProteomeDlg_RefreshStatus_The_proteome_has_already_been_digested", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred reading files in the directory {0}..
/// </summary>
public static string BuildLibraryDlg_AddDirectory_An_error_occurred_reading_files_in_the_directory__0__ {
get {
return ResourceManager.GetString("BuildLibraryDlg_AddDirectory_An_error_occurred_reading_files_in_the_directory__0_" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Find Input Files.
/// </summary>
public static string BuildLibraryDlg_AddDirectory_Find_Input_Files {
get {
return ResourceManager.GetString("BuildLibraryDlg_AddDirectory_Find_Input_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} is a library file and does not need to be built. Would you like to add this library to the document?.
/// </summary>
public static string BuildLibraryDlg_AddInputFiles_The_file__0__is_a_library_file_and_does_not_need_to_be_built__Would_you_like_to_add_this_library_to_the_document_ {
get {
return ResourceManager.GetString("BuildLibraryDlg_AddInputFiles_The_file__0__is_a_library_file_and_does_not_need_to" +
"_be_built__Would_you_like_to_add_this_library_to_the_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} is not a valid library input file..
/// </summary>
public static string BuildLibraryDlg_AddInputFiles_The_file__0__is_not_a_valid_library_input_file {
get {
return ResourceManager.GetString("BuildLibraryDlg_AddInputFiles_The_file__0__is_not_a_valid_library_input_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following files are not valid library input files:.
/// </summary>
public static string BuildLibraryDlg_AddInputFiles_The_following_files_are_not_valid_library_input_files {
get {
return ResourceManager.GetString("BuildLibraryDlg_AddInputFiles_The_following_files_are_not_valid_library_input_fil" +
"es", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to These files are library files and do not need to be built. Edit the list of libraries to add them directly..
/// </summary>
public static string BuildLibraryDlg_AddInputFiles_These_files_are_library_files_and_do_not_need_to_be_built__Edit_the_list_of_libraries_to_add_them_directly_ {
get {
return ResourceManager.GetString("BuildLibraryDlg_AddInputFiles_These_files_are_library_files_and_do_not_need_to_be" +
"_built__Edit_the_list_of_libraries_to_add_them_directly_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add Input Directory.
/// </summary>
public static string BuildLibraryDlg_btnAddDirectory_Click_Add_Input_Directory {
get {
return ResourceManager.GetString("BuildLibraryDlg_btnAddDirectory_Click_Add_Input_Directory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add Input Files.
/// </summary>
public static string BuildLibraryDlg_btnAddFile_Click_Add_Input_Files {
get {
return ResourceManager.GetString("BuildLibraryDlg_btnAddFile_Click_Add_Input_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Matched Peptides (.
/// </summary>
public static string BuildLibraryDlg_btnAddFile_Click_Matched_Peptides {
get {
return ResourceManager.GetString("BuildLibraryDlg_btnAddFile_Click_Matched_Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Next >.
/// </summary>
public static string BuildLibraryDlg_btnPrevious_Click__Next__ {
get {
return ResourceManager.GetString("BuildLibraryDlg_btnPrevious_Click__Next__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Finding library input files in.
/// </summary>
public static string BuildLibraryDlg_FindInputFiles_Finding_library_input_files_in {
get {
return ResourceManager.GetString("BuildLibraryDlg_FindInputFiles_Finding_library_input_files_in", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Finish.
/// </summary>
public static string BuildLibraryDlg_OkWizardPage_Finish {
get {
return ResourceManager.GetString("BuildLibraryDlg_OkWizardPage_Finish", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Access violation attempting to write to {0}..
/// </summary>
public static string BuildLibraryDlg_ValidateBuilder_Access_violation_attempting_to_write_to__0__ {
get {
return ResourceManager.GetString("BuildLibraryDlg_ValidateBuilder_Access_violation_attempting_to_write_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure attempting to create a file in {0}..
/// </summary>
public static string BuildLibraryDlg_ValidateBuilder_Failure_attempting_to_create_a_file_in__0__ {
get {
return ResourceManager.GetString("BuildLibraryDlg_ValidateBuilder_Failure_attempting_to_create_a_file_in__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please check that you have write access to this folder..
/// </summary>
public static string BuildLibraryDlg_ValidateBuilder_Please_check_that_you_have_write_access_to_this_folder_ {
get {
return ResourceManager.GetString("BuildLibraryDlg_ValidateBuilder_Please_check_that_you_have_write_access_to_this_f" +
"older_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The directory {0} does not exist..
/// </summary>
public static string BuildLibraryDlg_ValidateBuilder_The_directory__0__does_not_exist {
get {
return ResourceManager.GetString("BuildLibraryDlg_ValidateBuilder_The_directory__0__does_not_exist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The lab authority name {0} is not valid. This should look like an internet server address (e.g. mylab.myu.edu), and be unlikely to be used by any other lab, but need not refer to an actual server..
/// </summary>
public static string BuildLibraryDlg_ValidateBuilder_The_lab_authority_name__0__is_not_valid_This_should_look_like_an_internet_server_address_e_g_mylab_myu_edu_and_be_unlikely_to_be_used_by_any_other_lab_but_need_not_refer_to_an_actual_server {
get {
return ResourceManager.GetString("BuildLibraryDlg_ValidateBuilder_The_lab_authority_name__0__is_not_valid_This_shou" +
"ld_look_like_an_internet_server_address_e_g_mylab_myu_edu_and_be_unlikely_to_be_" +
"used_by_any_other_lab_but_need_not_refer_to_an_actual_server", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The library identifier {0} is not valid. Identifiers start with a letter, number or underscore, and contain only letters, numbers, underscores and dashes..
/// </summary>
public static string BuildLibraryDlg_ValidateBuilder_The_library_identifier__0__is_not_valid_Identifiers_start_with_a_letter_number_or_underscore_and_contain_only_letters_numbers_underscores_and_dashes {
get {
return ResourceManager.GetString("BuildLibraryDlg_ValidateBuilder_The_library_identifier__0__is_not_valid_Identifie" +
"rs_start_with_a_letter_number_or_underscore_and_contain_only_letters_numbers_und" +
"erscores_and_dashes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The output path {0} is a directory. You must specify a file path..
/// </summary>
public static string BuildLibraryDlg_ValidateBuilder_The_output_path__0__is_a_directory_You_must_specify_a_file_path {
get {
return ResourceManager.GetString("BuildLibraryDlg_ValidateBuilder_The_output_path__0__is_a_directory_You_must_speci" +
"fy_a_file_path", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must specify an output file path..
/// </summary>
public static string BuildLibraryDlg_ValidateBuilder_You_must_specify_an_output_file_path {
get {
return ResourceManager.GetString("BuildLibraryDlg_ValidateBuilder_You_must_specify_an_output_file_path", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library {0}.
/// </summary>
public static string BuildLibraryNotification_BuildLibraryNotification_Library__0__ {
get {
return ResourceManager.GetString("BuildLibraryNotification_BuildLibraryNotification_Library__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This library contains iRT values. Do you want to create a retention time predictor with these values?.
/// </summary>
public static string BuildPeptideSearchLibraryControl_AddExistingLibrary_This_library_contains_iRT_values__Do_you_want_to_create_a_retention_time_predictor_with_these_values_ {
get {
return ResourceManager.GetString("BuildPeptideSearchLibraryControl_AddExistingLibrary_This_library_contains_iRT_val" +
"ues__Do_you_want_to_create_a_retention_time_predictor_with_these_values_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while processing retention times..
/// </summary>
public static string BuildPeptideSearchLibraryControl_AddIrtLibraryTable_An_error_occurred_while_processing_retention_times_ {
get {
return ResourceManager.GetString("BuildPeptideSearchLibraryControl_AddIrtLibraryTable_An_error_occurred_while_proce" +
"ssing_retention_times_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Processing Retention Times.
/// </summary>
public static string BuildPeptideSearchLibraryControl_AddIrtLibraryTable_Processing_Retention_Times {
get {
return ResourceManager.GetString("BuildPeptideSearchLibraryControl_AddIrtLibraryTable_Processing_Retention_Times", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add document spectral library.
/// </summary>
public static string BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Add_document_spectral_library {
get {
return ResourceManager.GetString("BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Add_document_spectral_" +
"library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Building document library for peptide search..
/// </summary>
public static string BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Building_document_library_for_peptide_search_ {
get {
return ResourceManager.GetString("BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Building_document_libr" +
"ary_for_peptide_search_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Building Peptide Search Library.
/// </summary>
public static string BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Building_Peptide_Search_Library {
get {
return ResourceManager.GetString("BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Building_Peptide_Searc" +
"h_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to build the library {0}..
/// </summary>
public static string BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Failed_to_build_the_library__0__ {
get {
return ResourceManager.GetString("BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Failed_to_build_the_li" +
"brary__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Files to search:.
/// </summary>
public static string BuildPeptideSearchLibraryControl_Files_to_search_ {
get {
return ResourceManager.GetString("BuildPeptideSearchLibraryControl_Files_to_search_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to import the {0} library..
/// </summary>
public static string BuildPeptideSearchLibraryControl_LoadPeptideSearchLibrary_An_error_occurred_attempting_to_import_the__0__library_ {
get {
return ResourceManager.GetString("BuildPeptideSearchLibraryControl_LoadPeptideSearchLibrary_An_error_occurred_attem" +
"pting_to_import_the__0__library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading Library.
/// </summary>
public static string BuildPeptideSearchLibraryControl_LoadPeptideSearchLibrary_Loading_Library {
get {
return ResourceManager.GetString("BuildPeptideSearchLibraryControl_LoadPeptideSearchLibrary_Loading_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Result files:.
/// </summary>
public static string BuildPeptideSearchLibraryControl_Result_files_ {
get {
return ResourceManager.GetString("BuildPeptideSearchLibraryControl_Result_files_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed reading block from file..
/// </summary>
public static string BulkReadException_BulkReadException_Failed_reading_block_from_file {
get {
return ResourceManager.GetString("BulkReadException_BulkReadException_Failed_reading_block_from_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library entry not found {0}..
/// </summary>
public static string CachedLibrary_LoadSpectrum_Library_entry_not_found__0__ {
get {
return ResourceManager.GetString("CachedLibrary_LoadSpectrum_Library_entry_not_found__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid entries were found in the library '{0}'.
///{1} of the {2} peptides or molecules were invalid, including:
///{3}.
/// </summary>
public static string CachedLibrary_WarnInvalidEntries_ {
get {
return ResourceManager.GetString("CachedLibrary_WarnInvalidEntries_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Start value must be less than End value..
/// </summary>
public static string CalculateIsolationSchemeDlg_OkDialog_Start_value_must_be_less_than_End_value {
get {
return ResourceManager.GetString("CalculateIsolationSchemeDlg_OkDialog_Start_value_must_be_less_than_End_value", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The number of generated windows could not be adjusted to be a multiple of the windows per scan. Try changing the windows per scan or the End value..
/// </summary>
public static string CalculateIsolationSchemeDlg_OkDialog_The_number_of_generated_windows_could_not_be_adjusted_to_be_a_multiple_of_the_windows_per_scan_Try_changing_the_windows_per_scan_or_the_End_value {
get {
return ResourceManager.GetString("CalculateIsolationSchemeDlg_OkDialog_The_number_of_generated_windows_could_not_be" +
"_adjusted_to_be_a_multiple_of_the_windows_per_scan_Try_changing_the_windows_per_" +
"scan_or_the_End_value", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Window width must be an integer value when optimize window placement is selected..
/// </summary>
public static string CalculateIsolationSchemeDlg_OkDialog_Window_width_must_be_an_integer {
get {
return ResourceManager.GetString("CalculateIsolationSchemeDlg_OkDialog_Window_width_must_be_an_integer", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Window width must be less than or equal to the isolation range..
/// </summary>
public static string CalculateIsolationSchemeDlg_OkDialog_Window_width_must_be_less_than_or_equal_to_the_isolation_range {
get {
return ResourceManager.GetString("CalculateIsolationSchemeDlg_OkDialog_Window_width_must_be_less_than_or_equal_to_t" +
"he_isolation_range", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Odd numbered window widths are not supported for overlapped demultiplexing with optimized window placement selected..
/// </summary>
public static string CalculateIsolationSchemeDlg_OkDialog_Window_width_not_even {
get {
return ResourceManager.GetString("CalculateIsolationSchemeDlg_OkDialog_Window_width_not_even", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Calculator {
get {
object obj = ResourceManager.GetObject("Calculator", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Regression equation calculation.
/// </summary>
public static string CalibrateIrtDlg_btnGraph_Click_Regression_equation_calculation {
get {
return ResourceManager.GetString("CalibrateIrtDlg_btnGraph_Click_Regression_equation_calculation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calibrated iRT values.
/// </summary>
public static string CalibrateIrtDlg_btnGraphIrts_Click_Calibrated_iRT_values {
get {
return ResourceManager.GetString("CalibrateIrtDlg_btnGraphIrts_Click_Calibrated_iRT_values", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please enter at least {0} standard peptides..
/// </summary>
public static string CalibrateIrtDlg_OkDialog_Please_enter_at_least__0__standard_peptides_ {
get {
return ResourceManager.GetString("CalibrateIrtDlg_OkDialog_Please_enter_at_least__0__standard_peptides_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The iRT standard {0} already exists..
/// </summary>
public static string CalibrateIrtDlg_OkDialog_The_iRT_standard__0__already_exists_ {
get {
return ResourceManager.GetString("CalibrateIrtDlg_OkDialog_The_iRT_standard__0__already_exists_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document contains results for {0} peptide(s) not in this standard, which is less than the minimum requirement of {1} to calibrate a standard..
/// </summary>
public static string CalibrateIrtDlg_SetCalibrationPeptides_The_document_contains_results_for__0__peptide_s__not_in_this_standard__which_is_less_than_the_minimum_requirement_of__1__to_calibrate_a_standard_ {
get {
return ResourceManager.GetString("CalibrateIrtDlg_SetCalibrationPeptides_The_document_contains_results_for__0__pept" +
"ide_s__not_in_this_standard__which_is_less_than_the_minimum_requirement_of__1__t" +
"o_calibrate_a_standard_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT.
/// </summary>
public static string CalibrateIrtDlg_ShowGraph_iRT {
get {
return ResourceManager.GetString("CalibrateIrtDlg_ShowGraph_iRT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measured.
/// </summary>
public static string CalibrateIrtDlg_ShowGraph_Measured {
get {
return ResourceManager.GetString("CalibrateIrtDlg_ShowGraph_Measured", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to New iRT.
/// </summary>
public static string CalibrateIrtDlg_ShowGraph_New_iRT {
get {
return ResourceManager.GetString("CalibrateIrtDlg_ShowGraph_New_iRT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Old iRT.
/// </summary>
public static string CalibrateIrtDlg_ShowGraph_Old_iRT {
get {
return ResourceManager.GetString("CalibrateIrtDlg_ShowGraph_Old_iRT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} peptides.
/// </summary>
public static string CalibrateIrtDlg_StandardsChanged__0__peptides {
get {
return ResourceManager.GetString("CalibrateIrtDlg_StandardsChanged__0__peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 peptide.
/// </summary>
public static string CalibrateIrtDlg_StandardsChanged__1_peptide {
get {
return ResourceManager.GetString("CalibrateIrtDlg_StandardsChanged__1_peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid fixed point peptides..
/// </summary>
public static string CalibrateIrtDlg_TryGetLine_Invalid_fixed_point_peptides_ {
get {
return ResourceManager.GetString("CalibrateIrtDlg_TryGetLine_Invalid_fixed_point_peptides_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Maximum fixed point peptide must have a greater measured retention time than the minimum fixed point peptide..
/// </summary>
public static string CalibrateIrtDlg_TryGetLine_Maximum_fixed_point_peptide_must_have_a_greater_measured_retention_time_than_the_minimum_fixed_point_peptide_ {
get {
return ResourceManager.GetString("CalibrateIrtDlg_TryGetLine_Maximum_fixed_point_peptide_must_have_a_greater_measur" +
"ed_retention_time_than_the_minimum_fixed_point_peptide_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Standard calibration peptides are required..
/// </summary>
public static string CalibrateIrtDlg_TryGetLine_Standard_calibration_peptides_are_required_ {
get {
return ResourceManager.GetString("CalibrateIrtDlg_TryGetLine_Standard_calibration_peptides_are_required_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The standard must have two fixed points..
/// </summary>
public static string CalibrateIrtDlg_TryGetLine_The_standard_must_have_two_fixed_points {
get {
return ResourceManager.GetString("CalibrateIrtDlg_TryGetLine_The_standard_must_have_two_fixed_points", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document contains results for {0} peptides, but using fewer than {1} standard peptides is not recommended. Are you sure you want to continue?.
/// </summary>
public static string CalibrateIrtDlg_UseResults_The_document_contains_results_for__0__peptides__but_using_fewer_than__1__standard_peptides_is_not_recommended__Are_you_sure_you_want_to_continue_ {
get {
return ResourceManager.GetString("CalibrateIrtDlg_UseResults_The_document_contains_results_for__0__peptides__but_us" +
"ing_fewer_than__1__standard_peptides_is_not_recommended__Are_you_sure_you_want_t" +
"o_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document contains results for {0} peptides, which is less than the minimum requirement of {1} to calibrate a standard..
/// </summary>
public static string CalibrateIrtDlg_UseResults_The_document_contains_results_for__0__peptides__which_is_less_than_the_minimum_requirement_of__1__to_calibrate_a_standard_ {
get {
return ResourceManager.GetString("CalibrateIrtDlg_UseResults_The_document_contains_results_for__0__peptides__which_" +
"is_less_than_the_minimum_requirement_of__1__to_calibrate_a_standard_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document contains results for {0} peptides not in this standard, but using fewer than {1} standard peptides is not recommended. Are you sure you want to continue?.
/// </summary>
public static string CalibrateIrtDlg_UseResults_The_document_contains_results_for__0__peptides_not_in_this_standard__but_using_fewer_than__1__standard_peptides_is_not_recommended__Are_you_sure_you_want_to_continue_ {
get {
return ResourceManager.GetString("CalibrateIrtDlg_UseResults_The_document_contains_results_for__0__peptides_not_in_" +
"this_standard__but_using_fewer_than__1__standard_peptides_is_not_recommended__Ar" +
"e_you_sure_you_want_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must contain results to calibrate a standard..
/// </summary>
public static string CalibrateIrtDlg_UseResults_The_document_must_contain_results_to_calibrate_a_standard {
get {
return ResourceManager.GetString("CalibrateIrtDlg_UseResults_The_document_must_contain_results_to_calibrate_a_stand" +
"ard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to calculate the calibration curve for the because there are different Precursor Concentrations specified for the label {0}..
/// </summary>
public static string CalibrationCurveFitter_GetCalibrationCurve_Unable_to_calculate_the_calibration_curve_for_the_because_there_are_different_Precursor_Concentrations_specified_for_the_label__0__ {
get {
return ResourceManager.GetString("CalibrationCurveFitter_GetCalibrationCurve_Unable_to_calculate_the_calibration_cu" +
"rve_for_the_because_there_are_different_Precursor_Concentrations_specified_for_t" +
"he_label__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CiRT (discovered).
/// </summary>
public static string CalibrationGridViewDriver_CiRT_option_name {
get {
return ResourceManager.GetString("CalibrationGridViewDriver_CiRT_option_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculate from regression.
/// </summary>
public static string CalibrationGridViewDriver_FindEvenlySpacedPeptides_Calculate_from_regression {
get {
return ResourceManager.GetString("CalibrationGridViewDriver_FindEvenlySpacedPeptides_Calculate_from_regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculating scores.
/// </summary>
public static string CalibrationGridViewDriver_FindEvenlySpacedPeptides_Calculating_scores {
get {
return ResourceManager.GetString("CalibrationGridViewDriver_FindEvenlySpacedPeptides_Calculating_scores", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Predefined values.
/// </summary>
public static string CalibrationGridViewDriver_FindEvenlySpacedPeptides_Predefined_values {
get {
return ResourceManager.GetString("CalibrationGridViewDriver_FindEvenlySpacedPeptides_Predefined_values", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This document contains {0} CiRT peptides. Would you like to use {1} of them as your iRT standards?.
/// </summary>
public static string CalibrationGridViewDriver_FindEvenlySpacedPeptides_This_document_contains__0__CiRT_peptides__Would_you_like_to_use__1__of_them_as_your_iRT_standards_ {
get {
return ResourceManager.GetString("CalibrationGridViewDriver_FindEvenlySpacedPeptides_This_document_contains__0__CiR" +
"T_peptides__Would_you_like_to_use__1__of_them_as_your_iRT_standards_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Would you like to use the predefined iRT values or calculate new iRT values based on the regression?.
/// </summary>
public static string CalibrationGridViewDriver_FindEvenlySpacedPeptides_Would_you_like_to_use_the_predefined_iRT_values_ {
get {
return ResourceManager.GetString("CalibrationGridViewDriver_FindEvenlySpacedPeptides_Would_you_like_to_use_the_pred" +
"efined_iRT_values_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Standard peptides must exist in the database..
/// </summary>
public static string ChangeIrtPeptidesDlg_OkDialog_Standard_peptides_must_exist_in_the_database {
get {
return ResourceManager.GetString("ChangeIrtPeptidesDlg_OkDialog_Standard_peptides_must_exist_in_the_database", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following peptides were removed:.
/// </summary>
public static string ChangeIrtPeptidesDlg_OkDialog_The_following_peptides_were_removed_ {
get {
return ResourceManager.GetString("ChangeIrtPeptidesDlg_OkDialog_The_following_peptides_were_removed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following sequences are not currently in the database:.
/// </summary>
public static string ChangeIrtPeptidesDlg_OkDialog_The_following_sequences_are_not_currently_in_the_database {
get {
return ResourceManager.GetString("ChangeIrtPeptidesDlg_OkDialog_The_following_sequences_are_not_currently_in_the_da" +
"tabase", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The sequence '{0}' is not currently in the database..
/// </summary>
public static string ChangeIrtPeptidesDlg_OkDialog_The_sequence__0__is_not_currently_in_the_database {
get {
return ResourceManager.GetString("ChangeIrtPeptidesDlg_OkDialog_The_sequence__0__is_not_currently_in_the_database", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Would you like to remove them from the document?.
/// </summary>
public static string ChangeIrtPeptidesDlg_OkDialog_Would_you_like_to_remove_them_from_the_document_ {
get {
return ResourceManager.GetString("ChangeIrtPeptidesDlg_OkDialog_Would_you_like_to_remove_them_from_the_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change Annotation Settings.
/// </summary>
public static string ChooseAnnotationsDlg_OkDialog_Change_Annotation_Settings {
get {
return ResourceManager.GetString("ChooseAnnotationsDlg_OkDialog_Change_Annotation_Settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Transition List (iRT standards).
/// </summary>
public static string ChooseIrtStandardPeptides_ImportTextFile_Import_Transition_List__iRT_standards_ {
get {
return ResourceManager.GetString("ChooseIrtStandardPeptides_ImportTextFile_Import_Transition_List__iRT_standards_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition List.
/// </summary>
public static string ChooseIrtStandardPeptides_ImportTextFile_Transition_List {
get {
return ResourceManager.GetString("ChooseIrtStandardPeptides_ImportTextFile_Transition_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition list field must contain a path to a valid file..
/// </summary>
public static string ChooseIrtStandardPeptides_OkDialog_Transition_list_field_must_contain_a_path_to_a_valid_file_ {
get {
return ResourceManager.GetString("ChooseIrtStandardPeptides_OkDialog_Transition_list_field_must_contain_a_path_to_a" +
"_valid_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Known iRTs.
/// </summary>
public static string ChooseIrtStandardPeptidesDlg_OkDialog_Known_iRTs {
get {
return ResourceManager.GetString("ChooseIrtStandardPeptidesDlg_OkDialog_Known_iRTs", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library iRTs.
/// </summary>
public static string ChooseIrtStandardPeptidesDlg_OkDialog_Library_iRTs {
get {
return ResourceManager.GetString("ChooseIrtStandardPeptidesDlg_OkDialog_Library_iRTs", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Linear regression.
/// </summary>
public static string ChooseIrtStandardPeptidesDlg_OkDialog_Linear_regression {
get {
return ResourceManager.GetString("ChooseIrtStandardPeptidesDlg_OkDialog_Linear_regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please select a protein containing the list of standard peptides for the iRT calculator..
/// </summary>
public static string ChooseIrtStandardPeptidesDlg_OkDialog_Please_select_a_protein_containing_the_list_of_standard_peptides_for_the_iRT_calculator_ {
get {
return ResourceManager.GetString("ChooseIrtStandardPeptidesDlg_OkDialog_Please_select_a_protein_containing_the_list" +
"_of_standard_peptides_for_the_iRT_calculator_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Choose retention time filter replicates.
/// </summary>
public static string ChooseSchedulingReplicatesDlg_btnOk_Click_Choose_retention_time_filter_replicates {
get {
return ResourceManager.GetString("ChooseSchedulingReplicatesDlg_btnOk_Click_Choose_retention_time_filter_replicates" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The set of replicates in this document has changed. Please choose again which replicates to use for the retention time filter..
/// </summary>
public static string ChooseSchedulingReplicatesDlg_btnOk_Click_The_set_of_replicates_in_this_document_has_changed___Please_choose_again_which_replicates_to_use_for_the_retention_time_filter_ {
get {
return ResourceManager.GetString("ChooseSchedulingReplicatesDlg_btnOk_Click_The_set_of_replicates_in_this_document_" +
"has_changed___Please_choose_again_which_replicates_to_use_for_the_retention_time" +
"_filter_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must choose at least one replicate.
/// </summary>
public static string ChooseSchedulingReplicatesDlg_btnOk_Click_You_must_choose_at_least_one_replicate {
get {
return ResourceManager.GetString("ChooseSchedulingReplicatesDlg_btnOk_Click_You_must_choose_at_least_one_replicate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading {0} cache.
/// </summary>
public static string ChromatogramCache_Load_Loading__0__cache {
get {
return ResourceManager.GetString("ChromatogramCache_Load_Loading__0__cache", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure trying to read scan IDs.
/// </summary>
public static string ChromatogramCache_LoadScanIdBytes_Failure_trying_to_read_scan_IDs {
get {
return ResourceManager.GetString("ChromatogramCache_LoadScanIdBytes_Failure_trying_to_read_scan_IDs", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file appears to be corrupted and cannot be read.
///It is recommended that you delete this file so that Skyline can create a new file by again extracting chromatograms from the raw data files..
/// </summary>
public static string ChromatogramCache_LoadStructs_FileCorrupted {
get {
return ResourceManager.GetString("ChromatogramCache_LoadStructs_FileCorrupted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please check for a newer release..
/// </summary>
public static string ChromatogramCache_LoadStructs_Please_check_for_a_newer_release_ {
get {
return ResourceManager.GetString("ChromatogramCache_LoadStructs_Please_check_for_a_newer_release_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The SKYD file format {0} is not supported by Skyline {1}..
/// </summary>
public static string ChromatogramCache_LoadStructs_The_SKYD_file_format__0__is_not_supported_by_Skyline__1__ {
get {
return ResourceManager.GetString("ChromatogramCache_LoadStructs_The_SKYD_file_format__0__is_not_supported_by_Skylin" +
"e__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data truncation in cache header. File may be corrupted..
/// </summary>
public static string ChromatogramCache_ReadComplete_Data_truncation_in_cache_header_File_may_be_corrupted {
get {
return ResourceManager.GetString("ChromatogramCache_ReadComplete_Data_truncation_in_cache_header_File_may_be_corrup" +
"ted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure writing cache. Specified {0} peaks exceed total peak count {1}.
/// </summary>
public static string ChromatogramCache_WriteStructs_Failure_writing_cache___Specified__0__peaks_exceed_total_peak_count__1_ {
get {
return ResourceManager.GetString("ChromatogramCache_WriteStructs_Failure_writing_cache___Specified__0__peaks_exceed" +
"_total_peak_count__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collision Cross Section.
/// </summary>
public static string ChromatogramContextMenu_Collision_Cross_Section {
get {
return ResourceManager.GetString("ChromatogramContextMenu_Collision_Cross_Section", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Compensation Voltage.
/// </summary>
public static string ChromatogramContextMenu_InsertIonMobilityMenuItems_Compensation_Voltage {
get {
return ResourceManager.GetString("ChromatogramContextMenu_InsertIonMobilityMenuItems_Compensation_Voltage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Drift Time.
/// </summary>
public static string ChromatogramContextMenu_InsertIonMobilityMenuItems_Drift_Time {
get {
return ResourceManager.GetString("ChromatogramContextMenu_InsertIonMobilityMenuItems_Drift_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Inverse Ion Mobility.
/// </summary>
public static string ChromatogramContextMenu_InsertIonMobilityMenuItems_Inverse_Ion_Mobility {
get {
return ResourceManager.GetString("ChromatogramContextMenu_InsertIonMobilityMenuItems_Inverse_Ion_Mobility", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ion Mobility.
/// </summary>
public static string ChromatogramContextMenu_InsertIonMobilityMenuItems_Ion_Mobility {
get {
return ResourceManager.GetString("ChromatogramContextMenu_InsertIonMobilityMenuItems_Ion_Mobility", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This import appears to be taking longer than expected. If importing from a network drive, consider canceling this import, copying to local disk and retrying..
/// </summary>
public static string ChromatogramDataProvider_GetChromatogram_This_import_appears_to_be_taking_longer_than_expected__If_importing_from_a_network_drive__consider_canceling_this_import__copying_to_local_disk_and_retrying_ {
get {
return ResourceManager.GetString("ChromatogramDataProvider_GetChromatogram_This_import_appears_to_be_taking_longer_" +
"than_expected__If_importing_from_a_network_drive__consider_canceling_this_import" +
"__copying_to_local_disk_and_retrying_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Bad chromatogram data for charge {0} state of peptide {1}.
/// </summary>
public static string ChromatogramExporter_Export_Bad_chromatogram_data_for_charge__0__state_of_peptide__1_ {
get {
return ResourceManager.GetString("ChromatogramExporter_Export_Bad_chromatogram_data_for_charge__0__state_of_peptide" +
"__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Corrupted chromatogram data at charge {0} state of peptide {1}.
/// </summary>
public static string ChromatogramExporter_Export_Corrupted_chromatogram_data_at_charge__0__state_of_peptide__1_ {
get {
return ResourceManager.GetString("ChromatogramExporter_Export_Corrupted_chromatogram_data_at_charge__0__state_of_pe" +
"ptide__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting Chromatograms for {0}.
/// </summary>
public static string ChromatogramExporter_Export_Exporting_Chromatograms_for__0_ {
get {
return ResourceManager.GetString("ChromatogramExporter_Export_Exporting_Chromatograms_for__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to One or more missing chromatograms at charge state {0} of {1}.
/// </summary>
public static string ChromatogramExporter_ExportGroupNode_One_or_more_missing_chromatograms_at_charge_state__0__of__1_ {
get {
return ResourceManager.GetString("ChromatogramExporter_ExportGroupNode_One_or_more_missing_chromatograms_at_charge_" +
"state__0__of__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid extractor name..
/// </summary>
public static string ChromatogramExporter_GetExtractorName_Invalid_extractor_name_ {
get {
return ResourceManager.GetString("ChromatogramExporter_GetExtractorName_Invalid_extractor_name_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure trying to read points.
/// </summary>
public static string ChromatogramGroupInfo_ReadChromatogram_Failure_trying_to_read_points {
get {
return ResourceManager.GetString("ChromatogramGroupInfo_ReadChromatogram_Failure_trying_to_read_points", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The index {0} must be between 0 and {1}.
/// </summary>
public static string ChromatogramInfo_ChromatogramInfo_The_index__0__must_be_between_0_and__1__ {
get {
return ResourceManager.GetString("ChromatogramInfo_ChromatogramInfo_The_index__0__must_be_between_0_and__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Chromatogram Libraries.
/// </summary>
public static string ChromatogramLibrary_FILTER_CLIB_Chromatogram_Libraries {
get {
return ResourceManager.GetString("ChromatogramLibrary_FILTER_CLIB_Chromatogram_Libraries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading {0}.
/// </summary>
public static string ChromatogramLibrary_Load_Loading__0_ {
get {
return ResourceManager.GetString("ChromatogramLibrary_Load_Loading__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exception reading cache:{0}.
/// </summary>
public static string ChromatogramLibrary_LoadFromCache_Exception_reading_cache__0_ {
get {
return ResourceManager.GetString("ChromatogramLibrary_LoadFromCache_Exception_reading_cache__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error loading chromatogram library:{0}.
/// </summary>
public static string ChromatogramLibrary_LoadLibraryFromDatabase_Error_loading_chromatogram_library__0_ {
get {
return ResourceManager.GetString("ChromatogramLibrary_LoadLibraryFromDatabase_Error_loading_chromatogram_library__0" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reading precursors from {0}.
/// </summary>
public static string ChromatogramLibrary_LoadLibraryFromDatabase_Reading_precursors_from__0_ {
get {
return ResourceManager.GetString("ChromatogramLibrary_LoadLibraryFromDatabase_Reading_precursors_from__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak Area.
/// </summary>
public static string ChromatogramLibrarySpec_PEPTIDE_RANK_PEAK_AREA_Peak_Area {
get {
return ResourceManager.GetString("ChromatogramLibrarySpec_PEPTIDE_RANK_PEAK_AREA_Peak_Area", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempting to save results info for a file that cannot be found..
/// </summary>
public static string ChromatogramSet_GetOrdinalSaveId_Attempting_to_save_results_info_for_a_file_that_cannot_be_found {
get {
return ResourceManager.GetString("ChromatogramSet_GetOrdinalSaveId_Attempting_to_save_results_info_for_a_file_that_" +
"cannot_be_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempt to serialize list containing invalid type..
/// </summary>
public static string ChromatogramSet_WriteXml_Attempt_to_serialize_list_containing_invalid_type {
get {
return ResourceManager.GetString("ChromatogramSet_WriteXml_Attempt_to_serialize_list_containing_invalid_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This document contains only negative ion mode transitions, and the imported file contains only positive ion mode data so nothing can be loaded..
/// </summary>
public static string ChromCacheBuilder_BuildCache_This_document_contains_only_negative_ion_mode_transitions__and_the_imported_file_contains_only_positive_ion_mode_data_so_nothing_can_be_loaded_ {
get {
return ResourceManager.GetString("ChromCacheBuilder_BuildCache_This_document_contains_only_negative_ion_mode_transi" +
"tions__and_the_imported_file_contains_only_positive_ion_mode_data_so_nothing_can" +
"_be_loaded_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This document contains only positive ion mode transitions, and the imported file contains only negative ion mode data so nothing can be loaded. Negative ion mode transitions need to have negative charge values..
/// </summary>
public static string ChromCacheBuilder_BuildCache_This_document_contains_only_positive_ion_mode_transitions__and_the_imported_file_contains_only_negative_ion_mode_data_so_nothing_can_be_loaded___Negative_ion_mode_transitions_need_to_have_negative_charge_values_ {
get {
return ResourceManager.GetString("ChromCacheBuilder_BuildCache_This_document_contains_only_positive_ion_mode_transi" +
"tions__and_the_imported_file_contains_only_negative_ion_mode_data_so_nothing_can" +
"_be_loaded___Negative_ion_mode_transitions_need_to_have_negative_charge_values_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Importing {0}.
/// </summary>
public static string ChromCacheBuilder_BuildNextFileInner_Importing__0__ {
get {
return ResourceManager.GetString("ChromCacheBuilder_BuildNextFileInner_Importing__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Recalculating scores for {0}.
/// </summary>
public static string ChromCacheBuilder_BuildNextFileInner_Recalculating_scores_for__0_ {
get {
return ResourceManager.GetString("ChromCacheBuilder_BuildNextFileInner_Recalculating_scores_for__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not exist..
/// </summary>
public static string ChromCacheBuilder_BuildNextFileInner_The_file__0__does_not_exist {
get {
return ResourceManager.GetString("ChromCacheBuilder_BuildNextFileInner_The_file__0__does_not_exist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The sample {0} contains no usable data..
/// </summary>
public static string ChromCacheBuilder_BuildNextFileInner_The_sample__0__contains_no_usable_data {
get {
return ResourceManager.GetString("ChromCacheBuilder_BuildNextFileInner_The_sample__0__contains_no_usable_data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The path '{0}' was not found among previously imported results..
/// </summary>
public static string ChromCacheBuilder_GetRecalcFileBuildInfo_The_path___0___was_not_found_among_previously_imported_results_ {
get {
return ResourceManager.GetString("ChromCacheBuilder_GetRecalcFileBuildInfo_The_path___0___was_not_found_among_previ" +
"ously_imported_results_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to finish importing chromatograms because the retention time predictor linear regression failed..
/// </summary>
public static string ChromCacheBuilder_Read_Unable_to_finish_importing_chromatograms_because_the_retention_time_predictor_linear_regression_failed_ {
get {
return ResourceManager.GetString("ChromCacheBuilder_Read_Unable_to_finish_importing_chromatograms_because_the_reten" +
"tion_time_predictor_linear_regression_failed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Existing write threads: {0}.
/// </summary>
public static string ChromCacheBuilder_WriteLoop_Existing_write_threads___0_ {
get {
return ResourceManager.GetString("ChromCacheBuilder_WriteLoop_Existing_write_threads___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure writing cache file..
/// </summary>
public static string ChromCacheBuilder_WriteLoop_Failure_writing_cache_file {
get {
return ResourceManager.GetString("ChromCacheBuilder_WriteLoop_Failure_writing_cache_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transitions of the same precursor found with different peak counts {0} and {1}.
/// </summary>
public static string ChromCacheBuilder_WriteLoop_Transitions_of_the_same_precursor_found_with_different_peak_counts__0__and__1__ {
get {
return ResourceManager.GetString("ChromCacheBuilder_WriteLoop_Transitions_of_the_same_precursor_found_with_differen" +
"t_peak_counts__0__and__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed importing results file '{0}'..
/// </summary>
public static string ChromCacheBuildException_GetMessage_Failed_importing_results_file___0___ {
get {
return ResourceManager.GetString("ChromCacheBuildException_GetMessage_Failed_importing_results_file___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed importing results file '{0}', sample {1}..
/// </summary>
public static string ChromCacheBuildException_GetMessage_Failed_importing_results_file___0____sample__1__ {
get {
return ResourceManager.GetString("ChromCacheBuildException_GetMessage_Failed_importing_results_file___0____sample__" +
"1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected end of file in {0}..
/// </summary>
public static string ChromCacheJoiner_FinishRead_Unexpected_end_of_file_in__0__ {
get {
return ResourceManager.GetString("ChromCacheJoiner_FinishRead_Unexpected_end_of_file_in__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to create cache '{0}'..
/// </summary>
public static string ChromCacheJoiner_JoinNextPart_Failed_to_create_cache__0__ {
get {
return ResourceManager.GetString("ChromCacheJoiner_JoinNextPart_Failed_to_create_cache__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Joining file {0}.
/// </summary>
public static string ChromCacheJoiner_JoinNextPart_Joining_file__0__ {
get {
return ResourceManager.GetString("ChromCacheJoiner_JoinNextPart_Joining_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure attempting to write the file {0}.
/// </summary>
public static string ChromCacheWriter_Complete_Failure_attempting_to_write_the_file__0_ {
get {
return ResourceManager.GetString("ChromCacheWriter_Complete_Failure_attempting_to_write_the_file__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to minutes.
/// </summary>
public static string ChromChartPropertyDlg_cbRelative_CheckedChanged_minutes {
get {
return ResourceManager.GetString("ChromChartPropertyDlg_cbRelative_CheckedChanged_minutes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to widths.
/// </summary>
public static string ChromChartPropertyDlg_cbRelative_CheckedChanged_widths {
get {
return ResourceManager.GetString("ChromChartPropertyDlg_cbRelative_CheckedChanged_widths", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Times ({0}) and intensities ({1}) disagree in point count..
/// </summary>
public static string ChromCollected_ChromCollected_Times__0__and_intensities__1__disagree_in_point_count {
get {
return ResourceManager.GetString("ChromCollected_ChromCollected_Times__0__and_intensities__1__disagree_in_point_cou" +
"nt", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Intensities ({0}) and mass errors ({1}) disagree in point count..
/// </summary>
public static string ChromCollector_ReleaseChromatogram_Intensities___0___and_mass_errors___1___disagree_in_point_count_ {
get {
return ResourceManager.GetString("ChromCollector_ReleaseChromatogram_Intensities___0___and_mass_errors___1___disagr" +
"ee_in_point_count_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The time interval {0} to {1} is not valid..
/// </summary>
public static string ChromDataSet_GetExtents_The_time_interval__0__to__1__is_not_valid {
get {
return ResourceManager.GetString("ChromDataSet_GetExtents_The_time_interval__0__to__1__is_not_valid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Incorrectly sorted chromatograms {0} > {1}.
/// </summary>
public static string ChromDataSet_MarkOptimizationData_Incorrectly_sorted_chromatograms__0__1__ {
get {
return ResourceManager.GetString("ChromDataSet_MarkOptimizationData_Incorrectly_sorted_chromatograms__0__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected null peak.
/// </summary>
public static string ChromDataSet_MergePeaks_Unexpected_null_peak {
get {
return ResourceManager.GetString("ChromDataSet_MergePeaks_Unexpected_null_peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to empty.
/// </summary>
public static string ChromDataSet_ToString_empty {
get {
return ResourceManager.GetString("ChromDataSet_ToString_empty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Explicit.
/// </summary>
public static string ChromGraphItem_AddAnnotations_Explicit {
get {
return ResourceManager.GetString("ChromGraphItem_AddAnnotations_Explicit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ID.
/// </summary>
public static string ChromGraphItem_AddAnnotations_ID {
get {
return ResourceManager.GetString("ChromGraphItem_AddAnnotations_ID", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Predicted.
/// </summary>
public static string ChromGraphItem_AddAnnotations_Predicted {
get {
return ResourceManager.GetString("ChromGraphItem_AddAnnotations_Predicted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} - base peak.
/// </summary>
public static string ChromGraphItem_Title__0____base_peak {
get {
return ResourceManager.GetString("ChromGraphItem_Title__0____base_peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} - TIC.
/// </summary>
public static string ChromGraphItem_Title__0____TIC {
get {
return ResourceManager.GetString("ChromGraphItem_Title__0____TIC", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Step {0}.
/// </summary>
public static string ChromGraphItem_Title_Step__0_ {
get {
return ResourceManager.GetString("ChromGraphItem_Title_Step__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid chromatogram ID {0} found. Failure parsing m/z values..
/// </summary>
public static string ChromKey_FromId_Invalid_chromatogram_ID__0__found_Failure_parsing_mz_values {
get {
return ResourceManager.GetString("ChromKey_FromId_Invalid_chromatogram_ID__0__found_Failure_parsing_mz_values", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid chromatogram ID {0} found. The ID must include both precursor and product m/z values..
/// </summary>
public static string ChromKey_FromId_Invalid_chromatogram_ID__0__found_The_ID_must_include_both_precursor_and_product_mz_values {
get {
return ResourceManager.GetString("ChromKey_FromId_Invalid_chromatogram_ID__0__found_The_ID_must_include_both_precur" +
"sor_and_product_mz_values", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' is not a valid chromatogram ID..
/// </summary>
public static string ChromKey_FromId_The_value__0__is_not_a_valid_chromatogram_ID {
get {
return ResourceManager.GetString("ChromKey_FromId_The_value__0__is_not_a_valid_chromatogram_ID", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap ChromLib {
get {
object obj = ResourceManager.GetObject("ChromLib", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to ClipboardEx implementation problem.
/// </summary>
public static string ClipboardEx_GetData_ClipboardEx_implementation_problem {
get {
return ResourceManager.GetString("ClipboardEx_GetData_ClipboardEx_implementation_problem", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed setting data to the clipboard..
/// </summary>
public static string ClipboardHelper_GetCopyErrorMessage_Failed_setting_data_to_clipboard_ {
get {
return ResourceManager.GetString("ClipboardHelper_GetCopyErrorMessage_Failed_setting_data_to_clipboard_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The process '{0}' (ID = {1}) has the clipboard open..
/// </summary>
public static string ClipboardHelper_GetOpenClipboardMessage_The_process__0__ID__1__has_the_clipboard_open {
get {
return ResourceManager.GetString("ClipboardHelper_GetOpenClipboardMessage_The_process__0__ID__1__has_the_clipboard_" +
"open", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed getting data from the clipboard..
/// </summary>
public static string ClipboardHelper_GetPasteErrorMessage_Failed_getting_data_from_the_clipboard_ {
get {
return ResourceManager.GetString("ClipboardHelper_GetPasteErrorMessage_Failed_getting_data_from_the_clipboard_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Collapse {
get {
object obj = ResourceManager.GetObject("Collapse", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Adding ion mobility data from {0}.
/// </summary>
public static string CollisionalCrossSectionGridViewDriver_AddSpectralLibrary_Adding_ion_mobility_data_from__0_ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriver_AddSpectralLibrary_Adding_ion_mobility_data" +
"_from__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding Spectral Library.
/// </summary>
public static string CollisionalCrossSectionGridViewDriver_AddSpectralLibrary_Adding_Spectral_Library {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriver_AddSpectralLibrary_Adding_Spectral_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to load the library file {0}..
/// </summary>
public static string CollisionalCrossSectionGridViewDriver_AddSpectralLibrary_An_error_occurred_attempting_to_load_the_library_file__0__ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriver_AddSpectralLibrary_An_error_occurred_attemp" +
"ting_to_load_the_library_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The library {0} does not contain ion mobility information..
/// </summary>
public static string CollisionalCrossSectionGridViewDriver_AddSpectralLibrary_The_library__0__does_not_contain_ion_mobility_information_ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriver_AddSpectralLibrary_The_library__0__does_not" +
"_contain_ion_mobility_information_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reading ion mobility data from {0}..
/// </summary>
public static string CollisionalCrossSectionGridViewDriver_ProcessDriftTimes_Reading_ion_mobility_data_from__0__ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriver_ProcessDriftTimes_Reading_ion_mobility_data" +
"_from__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reading ion mobility information.
/// </summary>
public static string CollisionalCrossSectionGridViewDriver_ProcessIonMobilityValues_Reading_ion_mobility_information {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriver_ProcessIonMobilityValues_Reading_ion_mobili" +
"ty_information", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The sequence {0} is already present in the list..
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_DoRowValidating_The_sequence__0__is_already_present_in_the_list_ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_DoRowValidating_The_sequence__0__is_alr" +
"eady_present_in_the_list_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} is not a valid charge. Precursor charges must be integers with absolute value between 1 and {1}..
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow__0__is_not_a_valid_charge__Precursor_charges_must_be_integers_with_absolute_value_between_1_and__1__ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow__0__is_not_a_valid_charge__" +
"Precursor_charges_must_be_integers_with_absolute_value_between_1_and__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot read high energy ion mobility offset value "{0}" on line {1}..
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_Cannot_read_high_energy_ion_mobility_offset_value___0___on_line__1__ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_Cannot_read_high_energy_ion" +
"_mobility_offset_value___0___on_line__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not parse adduct description "{0}" on line {1}.
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_Could_not_parse_adduct_description___0___on_line__1_ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_Could_not_parse_adduct_desc" +
"ription___0___on_line__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid number format {0} for collisional cross section on line {1}..
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_Invalid_number_format__0__for_collisional_cross_section_on_line__1__ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_Invalid_number_format__0__f" +
"or_collisional_cross_section_on_line__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid number format {0} for ion mobility on line {1}..
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_Invalid_number_format__0__for_ion_mobility_on_line__1__ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_Invalid_number_format__0__f" +
"or_ion_mobility_on_line__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing adduct description on line {0}.
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_Missing_adduct_description_on_line__0_ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_Missing_adduct_description_" +
"on_line__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing collisional cross section value on line {0}..
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_Missing_collisional_cross_section_value_on_line__0__ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_Missing_collisional_cross_s" +
"ection_value_on_line__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing ion mobility value on line {0}..
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_Missing_ion_mobility_value_on_line__0__ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_Missing_ion_mobility_value_" +
"on_line__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing peptide sequence on line {0}..
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_Missing_peptide_sequence_on_line__0__ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_Missing_peptide_sequence_on" +
"_line__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Supported units include: {0}.
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_Supported_units_include___0_ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_Supported_units_include___0" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The collisional cross section {0} must be greater than zero on line {1}..
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_The_collisional_cross_section__0__must_be_greater_than_zero_on_line__1__ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_The_collisional_cross_secti" +
"on__0__must_be_greater_than_zero_on_line__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The ion mobility value "{0}" on line {1} must be greater than zero.
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_The_ion_mobility_value___0___on_line__1__must_be_greater_than_zero {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_The_ion_mobility_value___0_" +
"__on_line__1__must_be_greater_than_zero", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The pasted text must at a minimum contain columns for peptide and adduct, along with collisional cross section and/or ion mobility..
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_The_pasted_text_must_at_a_minimum_contain_columns_for_peptide_and_adduct__along_with_collisional_cross_section_and_or_ion_mobility_ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_The_pasted_text_must_at_a_m" +
"inimum_contain_columns_for_peptide_and_adduct__along_with_collisional_cross_sect" +
"ion_and_or_ion_mobility_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The text {0} is not a valid peptide sequence on line {1}..
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_The_text__0__is_not_a_valid_peptide_sequence_on_line__1__ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_The_text__0__is_not_a_valid" +
"_peptide_sequence_on_line__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unrecognized ion mobility units "{0}" on line {1}.
/// </summary>
public static string CollisionalCrossSectionGridViewDriverBase_ValidateRow_Unrecognized_ion_mobility_units___0___on_line__1_ {
get {
return ResourceManager.GetString("CollisionalCrossSectionGridViewDriverBase_ValidateRow_Unrecognized_ion_mobility_u" +
"nits___0___on_line__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Collision Energy Regression:.
/// </summary>
public static string CollisionEnergyList_Label_Collision_Energy_Regression {
get {
return ResourceManager.GetString("CollisionEnergyList_Label_Collision_Energy_Regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Collision Energy Regressions.
/// </summary>
public static string CollisionEnergyList_Title_Edit_Collision_Energy_Regressions {
get {
return ResourceManager.GetString("CollisionEnergyList_Title_Edit_Collision_Energy_Regressions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collision energy regression contains multiple coefficients for charge {0}..
/// </summary>
public static string CollisionEnergyRegression_Validate_Collision_energy_regression_contains_multiple_coefficients_for_charge__0__ {
get {
return ResourceManager.GetString("CollisionEnergyRegression_Validate_Collision_energy_regression_contains_multiple_" +
"coefficients_for_charge__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collision energy regressions require at least one regression function..
/// </summary>
public static string CollisionEnergyRegression_Validate_Collision_energy_regressions_require_at_least_one_regression_function {
get {
return ResourceManager.GetString("CollisionEnergyRegression_Validate_Collision_energy_regressions_require_at_least_" +
"one_regression_function", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline classic.
/// </summary>
public static string ColorSchemeList_DEFAULT_Skyline_classic {
get {
return ResourceManager.GetString("ColorSchemeList_DEFAULT_Skyline_classic", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Distinct.
/// </summary>
public static string ColorSchemeList_GetDefaults_Distinct {
get {
return ResourceManager.GetString("ColorSchemeList_GetDefaults_Distinct", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Eggplant lemonade.
/// </summary>
public static string ColorSchemeList_GetDefaults_Eggplant_lemonade {
get {
return ResourceManager.GetString("ColorSchemeList_GetDefaults_Eggplant_lemonade", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to High contrast.
/// </summary>
public static string ColorSchemeList_GetDefaults_High_contrast {
get {
return ResourceManager.GetString("ColorSchemeList_GetDefaults_High_contrast", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Duplicate column '{0}'.
/// </summary>
public static string Columns_Columns_Duplicate_column___0__ {
get {
return ResourceManager.GetString("Columns_Columns_Duplicate_column___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing column '{0}'.
/// </summary>
public static string Columns_Columns_Missing_column___0__ {
get {
return ResourceManager.GetString("Columns_Columns_Missing_column___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unrecognized column '{0}'.
/// </summary>
public static string Columns_Columns_Unrecognized_column___0__ {
get {
return ResourceManager.GetString("Columns_Columns_Unrecognized_column___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find table for {0}.
/// </summary>
public static string ColumnSet_GetColumnInfos_Unable_to_find_table_for__0_ {
get {
return ResourceManager.GetString("ColumnSet_GetColumnInfos_Unable_to_find_table_for__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected report type.
/// </summary>
public static string ColumnSet_GetColumnInfos_Unexpected_report_type {
get {
return ResourceManager.GetString("ColumnSet_GetColumnInfos_Unexpected_report_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide.
/// </summary>
public static string ColumnSet_GetTransitionsTable_Peptide {
get {
return ResourceManager.GetString("ColumnSet_GetTransitionsTable_Peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides.
/// </summary>
public static string ColumnSet_GetTransitionsTable_Peptides {
get {
return ResourceManager.GetString("ColumnSet_GetTransitionsTable_Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor.
/// </summary>
public static string ColumnSet_GetTransitionsTable_Precursor {
get {
return ResourceManager.GetString("ColumnSet_GetTransitionsTable_Precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursors.
/// </summary>
public static string ColumnSet_GetTransitionsTable_Precursors {
get {
return ResourceManager.GetString("ColumnSet_GetTransitionsTable_Precursors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Protein.
/// </summary>
public static string ColumnSet_GetTransitionsTable_Protein {
get {
return ResourceManager.GetString("ColumnSet_GetTransitionsTable_Protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition.
/// </summary>
public static string ColumnSet_GetTransitionsTable_Transition {
get {
return ResourceManager.GetString("ColumnSet_GetTransitionsTable_Transition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transitions.
/// </summary>
public static string ColumnSet_GetTransitionsTable_Transitions {
get {
return ResourceManager.GetString("ColumnSet_GetTransitionsTable_Transitions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The dwell time {0} must be between {1} and {2}..
/// </summary>
public static string CommandArgs_DwellTime_The_dwell_time__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("CommandArgs_DwellTime_The_dwell_time__0__must_be_between__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The arguments {0} and {1} options cannot be used together..
/// </summary>
public static string CommandArgs_ErrorArgsExclusiveText_Error__The_arguments__0__and__1__options_cannot_be_used_together_ {
get {
return ResourceManager.GetString("CommandArgs_ErrorArgsExclusiveText_Error__The_arguments__0__and__1__options_canno" +
"t_be_used_together_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The arguments below can be used to install tools onto the Tools menu and do not rely on the '--in' argument because they independent of a specific Skyline document..
/// </summary>
public static string CommandArgs_GROUP_TOOLS_The_arguments_below_can_be_used_to_install_tools_onto_the_Tools_menu_and_do_not_rely_on_the____in__argument_because_they_independent_of_a_specific_Skyline_document_ {
get {
return ResourceManager.GetString("CommandArgs_GROUP_TOOLS_The_arguments_below_can_be_used_to_install_tools_onto_the" +
"_Tools_menu_and_do_not_rely_on_the____in__argument_because_they_independent_of_a" +
"_specific_Skyline_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Tools Installation.
/// </summary>
public static string CommandArgs_GROUP_TOOLS_Tools_Installation {
get {
return ResourceManager.GetString("CommandArgs_GROUP_TOOLS_Tools_Installation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The instrument type {0} is not valid for isolation list export.
/// </summary>
public static string CommandArgs_IsolationListInstrumentType_The_instrument_type__0__is_not_valid_for_isolation_list_export {
get {
return ResourceManager.GetString("CommandArgs_IsolationListInstrumentType_The_instrument_type__0__is_not_valid_for_" +
"isolation_list_export", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The instrument type {0} is not valid for method export.
/// </summary>
public static string CommandArgs_MethodInstrumentType_The_instrument_type__0__is_not_valid_for_method_export {
get {
return ResourceManager.GetString("CommandArgs_MethodInstrumentType_The_instrument_type__0__is_not_valid_for_method_" +
"export", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: A value is required for the following argument to upload the document to Panorama:
///{0}.
/// </summary>
public static string CommandArgs_PanoramaArgsComplete_ {
get {
return ResourceManager.GetString("CommandArgs_PanoramaArgsComplete_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: A value is required for the following arguments to upload the document to Panorama:
///{0}.
/// </summary>
public static string CommandArgs_PanoramaArgsComplete_plural_ {
get {
return ResourceManager.GetString("CommandArgs_PanoramaArgsComplete_plural_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} or '{1}'.
/// </summary>
public static string CommandArgs_ParseArgsInternal______0__or___1__ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal______0__or___1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Defaulting to none..
/// </summary>
public static string CommandArgs_ParseArgsInternal_Defaulting_to_none_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Defaulting_to_none_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Defaulting to standard..
/// </summary>
public static string CommandArgs_ParseArgsInternal_Defaulting_to_standard_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Defaulting_to_standard_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: "{0}" is not a valid value for {1}. It must be one of the following: {2}.
/// </summary>
public static string CommandArgs_ParseArgsInternal_Error____0___is_not_a_valid_value_for__1___It_must_be_one_of_the_following___2_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Error____0___is_not_a_valid_value_for__1___It_must_" +
"be_one_of_the_following___2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Attempting to exclude an unknown feature name '{0}'. Try one of the following:.
/// </summary>
public static string CommandArgs_ParseArgsInternal_Error__Attempting_to_exclude_an_unknown_feature_name___0____Try_one_of_the_following_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Error__Attempting_to_exclude_an_unknown_feature_nam" +
"e___0____Try_one_of_the_following_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Regular expression '{0}' does not have any groups. One group is required. The part of the file or sub-directory name that matches the first group in the regular expression is used as the replicate name..
/// </summary>
public static string CommandArgs_ParseArgsInternal_Error__Regular_expression___0___does_not_have_any_groups___String {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Error__Regular_expression___0___does_not_have_any_g" +
"roups___String", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Regular expression {0} cannot be parsed..
/// </summary>
public static string CommandArgs_ParseArgsInternal_Error__Regular_expression__0__cannot_be_parsed_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Error__Regular_expression__0__cannot_be_parsed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The specified working directory {0} does not exist..
/// </summary>
public static string CommandArgs_ParseArgsInternal_Error__The_specified_working_directory__0__does_not_exist_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Error__The_specified_working_directory__0__does_not" +
"_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Unexpected argument --{0}.
/// </summary>
public static string CommandArgs_ParseArgsInternal_Error__Unexpected_argument____0_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Error__Unexpected_argument____0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Use --in to specify a Skyline document to open..
/// </summary>
public static string CommandArgs_ParseArgsInternal_Error__Use___in_to_specify_a_Skyline_document_to_open_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Error__Use___in_to_specify_a_Skyline_document_to_op" +
"en_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to It must be a number. Defaulting to {0}..
/// </summary>
public static string CommandArgs_ParseArgsInternal_It_must_be_a_number__Defaulting_to__0__ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_It_must_be_a_number__Defaulting_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No isolation list will be exported..
/// </summary>
public static string CommandArgs_ParseArgsInternal_No_isolation_list_will_be_exported_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_No_isolation_list_will_be_exported_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No method will be exported..
/// </summary>
public static string CommandArgs_ParseArgsInternal_No_method_will_be_exported_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_No_method_will_be_exported_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No transition list will be exported..
/// </summary>
public static string CommandArgs_ParseArgsInternal_No_transition_list_will_be_exported_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_No_transition_list_will_be_exported_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: Incorrect Usage of the --tool-program-macro command..
/// </summary>
public static string CommandArgs_ParseArgsInternal_Warning__Incorrect_Usage_of_the___tool_program_macro_command_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Warning__Incorrect_Usage_of_the___tool_program_macr" +
"o_command_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: Invalid max transitions per injection parameter ({0})..
/// </summary>
public static string CommandArgs_ParseArgsInternal_Warning__Invalid_max_transitions_per_injection_parameter___0___ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Warning__Invalid_max_transitions_per_injection_para" +
"meter___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: Invalid optimization parameter ({0}). Use "ce", "dp", or "none"..
/// </summary>
public static string CommandArgs_ParseArgsInternal_Warning__Invalid_optimization_parameter___0____Use__ce____dp___or__none__ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Warning__Invalid_optimization_parameter___0____Use_" +
"_ce____dp___or__none__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: The export strategy {0} is not valid. It must be one of the following: "single", "protein" or "buckets". Defaulting to single..
/// </summary>
public static string CommandArgs_ParseArgsInternal_Warning__The_export_strategy__0__is_not_valid__It_must_be_one_of_the_following___string {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Warning__The_export_strategy__0__is_not_valid__It_m" +
"ust_be_one_of_the_following___string", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: The instrument type {0} is not valid. Please choose from:.
/// </summary>
public static string CommandArgs_ParseArgsInternal_Warning__The_instrument_type__0__is_not_valid__Please_choose_from_ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Warning__The_instrument_type__0__is_not_valid__Plea" +
"se_choose_from_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: The method type {0} is invalid. It must be one of the following: "standard", "scheduled" or "triggered"..
/// </summary>
public static string CommandArgs_ParseArgsInternal_Warning__The_method_type__0__is_invalid__It_must_be_one_of_the_following___standard____scheduled__or__triggered__ {
get {
return ResourceManager.GetString("CommandArgs_ParseArgsInternal_Warning__The_method_type__0__is_invalid__It_must_be" +
"_one_of_the_following___standard____scheduled__or__triggered__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Regular expression '{0}' for {1} cannot be parsed..
/// </summary>
public static string CommandArgs_ParseRegexArgument_Error__Regular_expression___0___for__1__cannot_be_parsed_ {
get {
return ResourceManager.GetString("CommandArgs_ParseRegexArgument_Error__Regular_expression___0___for__1__cannot_be_" +
"parsed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The primary transition count {0} must be between {1} and {2}..
/// </summary>
public static string CommandArgs_PrimaryTransitionCount_The_primary_transition_count__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("CommandArgs_PrimaryTransitionCount_The_primary_transition_count__0__must_be_betwe" +
"en__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The run length {0} must be between {1} and {2}..
/// </summary>
public static string CommandArgs_RunLength_The_run_length__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("CommandArgs_RunLength_The_run_length__0__must_be_between__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The instrument parameter {0} is not valid for optimization..
/// </summary>
public static string CommandArgs_ToOptimizeString_The_instrument_parameter__0__is_not_valid_for_optimization_ {
get {
return ResourceManager.GetString("CommandArgs_ToOptimizeString_The_instrument_parameter__0__is_not_valid_for_optimi" +
"zation_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The instrument type {0} is not valid for transition list export.
/// </summary>
public static string CommandArgs_TransListInstrumentType_The_instrument_type__0__is_not_valid_for_transition_list_export {
get {
return ResourceManager.GetString("CommandArgs_TransListInstrumentType_The_instrument_type__0__is_not_valid_for_tran" +
"sition_list_export", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Model cutoffs ({0}) must be in decreasing order greater than zero and less than {1}..
/// </summary>
public static string CommandArgs_ValidateReintegrateArgs_Error__Model_cutoffs___0___must_be_in_decreasing_order_greater_than_zero_and_less_than__1__ {
get {
return ResourceManager.GetString("CommandArgs_ValidateReintegrateArgs_Error__Model_cutoffs___0___must_be_in_decreas" +
"ing_order_greater_than_zero_and_less_than__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Model cutoffs cannot be applied in calibrating the Skyline default model..
/// </summary>
public static string CommandArgs_ValidateReintegrateArgs_Error__Model_cutoffs_cannot_be_applied_in_calibrating_the_Skyline_default_model_ {
get {
return ResourceManager.GetString("CommandArgs_ValidateReintegrateArgs_Error__Model_cutoffs_cannot_be_applied_in_cal" +
"ibrating_the_Skyline_default_model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use of the argument {0} requires one of the following arguments:.
/// </summary>
public static string CommandArgs_WarnArgRequirementText_Use_of_the_argument__0__requires_one_of_the_following_arguments_ {
get {
return ResourceManager.GetString("CommandArgs_WarnArgRequirementText_Use_of_the_argument__0__requires_one_of_the_fo" +
"llowing_arguments_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: Use of the argument {0} requires the argument {1}.
/// </summary>
public static string CommandArgs_WarnArgRequirment_Warning__Use_of_the_argument__0__requires_the_argument__1_ {
get {
return ResourceManager.GetString("CommandArgs_WarnArgRequirment_Warning__Use_of_the_argument__0__requires_the_argum" +
"ent__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Added {0} decoy peptides using '{1}' method.
/// </summary>
public static string CommandLine_AddDecoys_Added__0__decoy_peptides_using___1___method {
get {
return ResourceManager.GetString("CommandLine_AddDecoys_Added__0__decoy_peptides_using___1___method", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Decoys discarded.
/// </summary>
public static string CommandLine_AddDecoys_Decoys_discarded {
get {
return ResourceManager.GetString("CommandLine_AddDecoys_Decoys_discarded", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Attempting to add decoys to document with decoys..
/// </summary>
public static string CommandLine_AddDecoys_Error__Attempting_to_add_decoys_to_document_with_decoys_ {
get {
return ResourceManager.GetString("CommandLine_AddDecoys_Error__Attempting_to_add_decoys_to_document_with_decoys_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The number of peptides {0} must be less than the number of peptide precursor models for decoys {1}, or use {2}={3} decoy generation method..
/// </summary>
public static string CommandLine_AddDecoys_Error_The_number_of_peptides {
get {
return ResourceManager.GetString("CommandLine_AddDecoys_Error_The_number_of_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: No files match the file name pattern '{0}'..
/// </summary>
public static string CommandLine_ApplyFileAndSampleNameRegex_Error__No_files_match_the_file_name_pattern___0___ {
get {
return ResourceManager.GetString("CommandLine_ApplyFileAndSampleNameRegex_Error__No_files_match_the_file_name_patte" +
"rn___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: No files match the sample name pattern '{0}'..
/// </summary>
public static string CommandLine_ApplyFileAndSampleNameRegex_Error__No_files_match_the_sample_name_pattern___0___ {
get {
return ResourceManager.GetString("CommandLine_ApplyFileAndSampleNameRegex_Error__No_files_match_the_sample_name_pat" +
"tern___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File name '{0}' does not match the pattern '{1}'. Ignoring {2}.
/// </summary>
public static string CommandLine_ApplyFileNameRegex_File_name___0___does_not_match_the_pattern___1____Ignoring__2_ {
get {
return ResourceManager.GetString("CommandLine_ApplyFileNameRegex_File_name___0___does_not_match_the_pattern___1____" +
"Ignoring__2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: {0} does not match the regular expression..
/// </summary>
public static string CommandLine_ApplyNamingPattern_Error___0__does_not_match_the_regular_expression_ {
get {
return ResourceManager.GetString("CommandLine_ApplyNamingPattern_Error___0__does_not_match_the_regular_expression_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Duplicate replicate name '{0}' after applying regular expression..
/// </summary>
public static string CommandLine_ApplyNamingPattern_Error__Duplicate_replicate_name___0___after_applying_regular_expression_ {
get {
return ResourceManager.GetString("CommandLine_ApplyNamingPattern_Error__Duplicate_replicate_name___0___after_applyi" +
"ng_regular_expression_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Match to regular expression is empty for {0}..
/// </summary>
public static string CommandLine_ApplyNamingPattern_Error__Match_to_regular_expression_is_empty_for__0__ {
get {
return ResourceManager.GetString("CommandLine_ApplyNamingPattern_Error__Match_to_regular_expression_is_empty_for__0" +
"__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File '{0}' does not have a sample. Cannot apply sample name pattern. Ignoring..
/// </summary>
public static string CommandLine_ApplySampleNameRegex_File___0___does_not_have_a_sample__Cannot_apply_sample_name_pattern__Ignoring_ {
get {
return ResourceManager.GetString("CommandLine_ApplySampleNameRegex_File___0___does_not_have_a_sample__Cannot_apply_" +
"sample_name_pattern__Ignoring_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sample name '{0}' does not match the pattern '{1}'. Ignoring {2}.
/// </summary>
public static string CommandLine_ApplySampleNameRegex_Sample_name___0___does_not_match_the_pattern___1____Ignoring__2_ {
get {
return ResourceManager.GetString("CommandLine_ApplySampleNameRegex_Sample_name___0___does_not_match_the_pattern___1" +
"____Ignoring__2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: File does not exist: {0}..
/// </summary>
public static string CommandLine_CanReadFile_Error__File_does_not_exist___0__ {
get {
return ResourceManager.GetString("CommandLine_CanReadFile_Error__File_does_not_exist___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Replicate {0} in the document has an unexpected file {1}..
/// </summary>
public static string CommandLine_CheckReplicateFiles_Error__Replicate__0__in_the_document_has_an_unexpected_file__1__ {
get {
return ResourceManager.GetString("CommandLine_CheckReplicateFiles_Error__Replicate__0__in_the_document_has_an_unexp" +
"ected_file__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Could not find the spectral library {0} for this document..
/// </summary>
public static string CommandLine_ConnectLibrarySpecs_Error__Could_not_find_the_spectral_library__0__for_this_document_ {
get {
return ResourceManager.GetString("CommandLine_ConnectLibrarySpecs_Error__Could_not_find_the_spectral_library__0__fo" +
"r_this_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: Could not find the spectral library {0}.
/// </summary>
public static string CommandLine_ConnectLibrarySpecs_Warning__Could_not_find_the_spectral_library__0_ {
get {
return ResourceManager.GetString("CommandLine_ConnectLibrarySpecs_Warning__Could_not_find_the_spectral_library__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Importing an assay library to a document without an iRT calculator cannot create {0}, because it exists..
/// </summary>
public static string CommandLine_CreateIrtDatabase_Error__Importing_an_assay_library_to_a_document_without_an_iRT_calculator_cannot_create__0___because_it_exists_ {
get {
return ResourceManager.GetString("CommandLine_CreateIrtDatabase_Error__Importing_an_assay_library_to_a_document_wit" +
"hout_an_iRT_calculator_cannot_create__0___because_it_exists_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use the {0} argument to specify a file to create..
/// </summary>
public static string CommandLine_CreateIrtDatabase_Use_the__0__argument_to_specify_a_file_to_create_ {
get {
return ResourceManager.GetString("CommandLine_CreateIrtDatabase_Use_the__0__argument_to_specify_a_file_to_create_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Creating scoring model {0}.
/// </summary>
public static string CommandLine_CreateScoringModel_Creating_scoring_model__0_ {
get {
return ResourceManager.GetString("CommandLine_CreateScoringModel_Creating_scoring_model__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed to create scoring model..
/// </summary>
public static string CommandLine_CreateScoringModel_Error__Failed_to_create_scoring_model_ {
get {
return ResourceManager.GetString("CommandLine_CreateScoringModel_Error__Failed_to_create_scoring_model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: There are no decoy peptides in the document. Failed to create scoring model..
/// </summary>
public static string CommandLine_CreateScoringModel_Error__There_are_no_decoy_peptides_in_the_document__Failed_to_create_scoring_model_ {
get {
return ResourceManager.GetString("CommandLine_CreateScoringModel_Error__There_are_no_decoy_peptides_in_the_document" +
"__Failed_to_create_scoring_model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Excluding feature score '{0}'.
/// </summary>
public static string CommandLine_CreateScoringModel_Excluding_feature_score___0__ {
get {
return ResourceManager.GetString("CommandLine_CreateScoringModel_Excluding_feature_score___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Excluding feature scores:.
/// </summary>
public static string CommandLine_CreateScoringModel_Excluding_feature_scores_ {
get {
return ResourceManager.GetString("CommandLine_CreateScoringModel_Excluding_feature_scores_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Excluding feature scores is not permitted with the default Skyline model..
/// </summary>
public static string CommandLine_CreateUntrainedScoringModel_Error__Excluding_feature_scores_is_not_permitted_with_the_default_Skyline_model_ {
get {
return ResourceManager.GetString("CommandLine_CreateUntrainedScoringModel_Error__Excluding_feature_scores_is_not_pe" +
"rmitted_with_the_default_Skyline_model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Chromatograms file {0} exported successfully..
/// </summary>
public static string CommandLine_ExportChromatograms_Chromatograms_file__0__exported_successfully_ {
get {
return ResourceManager.GetString("CommandLine_ExportChromatograms_Chromatograms_file__0__exported_successfully_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: At least one chromatogram type must be selected.
/// </summary>
public static string CommandLine_ExportChromatograms_Error__At_least_one_chromatogram_type_must_be_selected {
get {
return ResourceManager.GetString("CommandLine_ExportChromatograms_Error__At_least_one_chromatogram_type_must_be_sel" +
"ected", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failure attempting to save chromatograms file {0}.
/// </summary>
public static string CommandLine_ExportChromatograms_Error__Failure_attempting_to_save_chromatograms_file__0_ {
get {
return ResourceManager.GetString("CommandLine_ExportChromatograms_Error__Failure_attempting_to_save_chromatograms_f" +
"ile__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The document must have imported results.
/// </summary>
public static string CommandLine_ExportChromatograms_Error__The_document_must_have_imported_results {
get {
return ResourceManager.GetString("CommandLine_ExportChromatograms_Error__The_document_must_have_imported_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting chromatograms file {0}....
/// </summary>
public static string CommandLine_ExportChromatograms_Exporting_chromatograms_file__0____ {
get {
return ResourceManager.GetString("CommandLine_ExportChromatograms_Exporting_chromatograms_file__0____", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: You must specify an output file to write to with the --exp-file=path/to/file parameter. No transition list will be exported..
/// </summary>
public static string CommandLine_ExportInstrumentFile_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: A template file is required to export a method..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__A_template_file_is_required_to_export_a_method_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__A_template_file_is_required_to_export_a_m" +
"ethod_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: the {0} instrument lacks support for direct method export for triggered acquisition..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__the__0__instrument_lacks_support_for_direct_method_export_for_triggered_acquisition_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__the__0__instrument_lacks_support_for_dire" +
"ct_method_export_for_triggered_acquisition_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The current document contains peptides without enough information to rank transitions for triggered acquisition..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__The_current_document_contains_peptides_without_enough_information_to_rank_transitions_for_triggered_acquisition_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__The_current_document_contains_peptides_wi" +
"thout_enough_information_to_rank_transitions_for_triggered_acquisition_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The file {0} could not be saved. Check that the specified file directory exists and is writeable..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__The_file__0__could_not_be_saved___Check_that_the_specified_file_directory_exists_and_is_writeable_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__The_file__0__could_not_be_saved___Check_t" +
"hat_the_specified_file_directory_exists_and_is_writeable_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The folder {0} does not appear to contain an Agilent QQQ method template. The folder is expected to have a .m extension, and contain the file qqqacqmethod.xsd..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__The_folder__0__does_not_appear_to_contain_an_Agilent_QQQ_method_template___The_folder_is_expected_to_have_a__m_extension__and_contain_the_file_qqqacqmethod_xsd_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__The_folder__0__does_not_appear_to_contain" +
"_an_Agilent_QQQ_method_template___The_folder_is_expected_to_have_a__m_extension_" +
"_and_contain_the_file_qqqacqmethod_xsd_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: the instrument type {0} does not support triggered acquisition..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__the_instrument_type__0__does_not_support_triggered_acquisition_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__the_instrument_type__0__does_not_support_" +
"triggered_acquisition_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: the retention time prediction calculator is unable to score. Check the calculator settings..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__the_retention_time_prediction_calculator_is_unable_to_score___Check_the_calculator_settings_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__the_retention_time_prediction_calculator_" +
"is_unable_to_score___Check_the_calculator_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: the retention time predictor is unable to auto-calculate a regression. Check to make sure the document contains times for all of the required standard peptides..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__the_retention_time_predictor_is_unable_to_auto_calculate_a_regression___Check_to_make_sure_the_document_contains_times_for_all_of_the_required_standard_peptides_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__the_retention_time_predictor_is_unable_to" +
"_auto_calculate_a_regression___Check_to_make_sure_the_document_contains_times_fo" +
"r_all_of_the_required_standard_peptides_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: the specified instrument {0} is not compatible with scheduled methods..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__the_specified_instrument__0__is_not_compatible_with_scheduled_methods_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__the_specified_instrument__0__is_not_compa" +
"tible_with_scheduled_methods_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: the specified replicate {0} does not exist in the document..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__the_specified_replicate__0__does_not_exist_in_the_document_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__the_specified_replicate__0__does_not_exis" +
"t_in_the_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The template extension {0} does not match the expected extension for the instrument {1}. No method will be exported..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__The_template_extension__0__does_not_match_the_expected_extension_for_the_instrument__1___No_method_will_be_exported_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__The_template_extension__0__does_not_match" +
"_the_expected_extension_for_the_instrument__1___No_method_will_be_exported_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The template file {0} does not exist..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__The_template_file__0__does_not_exist_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__The_template_file__0__does_not_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: to export a scheduled method, you must first choose a retention time predictor in Peptide Settings / Prediction..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__to_export_a_scheduled_method__you_must_first_choose_a_retention_time_predictor_in_Peptide_Settings___Prediction_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__to_export_a_scheduled_method__you_must_fi" +
"rst_choose_a_retention_time_predictor_in_Peptide_Settings___Prediction_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: to export a scheduled method, you must first choose a retention time predictor in Peptide Settings / Prediction, or import results for all peptides in the document..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__to_export_a_scheduled_method__you_must_first_choose_a_retention_time_predictor_in_Peptide_Settings___Prediction__or_import_results_for_all_peptides_in_the_document_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__to_export_a_scheduled_method__you_must_fi" +
"rst_choose_a_retention_time_predictor_in_Peptide_Settings___Prediction__or_impor" +
"t_results_for_all_peptides_in_the_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: To export a scheduled method, you must first import results for all peptides in the document..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__To_export_a_scheduled_method__you_must_first_import_results_for_all_peptides_in_the_document_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__To_export_a_scheduled_method__you_must_fi" +
"rst_import_results_for_all_peptides_in_the_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: triggered acquistion requires a spectral library or imported results in order to rank transitions..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Error__triggered_acquistion_requires_a_spectral_library_or_imported_results_in_order_to_rank_transitions_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Error__triggered_acquistion_requires_a_spectral_" +
"library_or_imported_results_in_order_to_rank_transitions_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to List {0} exported successfully..
/// </summary>
public static string CommandLine_ExportInstrumentFile_List__0__exported_successfully_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_List__0__exported_successfully_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Method {0} exported successfully..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Method__0__exported_successfully_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Method__0__exported_successfully_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No list will be exported..
/// </summary>
public static string CommandLine_ExportInstrumentFile_No_list_will_be_exported_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_No_list_will_be_exported_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No method will be exported..
/// </summary>
public static string CommandLine_ExportInstrumentFile_No_method_will_be_exported_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_No_method_will_be_exported_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: Max transitions per injection must be set to some value between {0} and {1} for export strategies "protein" and "buckets" and for scheduled methods. You specified {3}. Defaulting to {2}..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Warning__Max_transitions_per_injection_must_be_set_to_some_value_between__0__and__1__for_export_strategies__protein__and__buckets__and_for_scheduled_methods__You_specified__3___Defaulting_to__2__ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Warning__Max_transitions_per_injection_must_be_s" +
"et_to_some_value_between__0__and__1__for_export_strategies__protein__and__bucket" +
"s__and_for_scheduled_methods__You_specified__3___Defaulting_to__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: No export strategy specified (from "single", "protein" or "buckets"). Defaulting to "single"..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Warning__No_export_strategy_specified__from__single____protein__or__buckets____Defaulting_to__single__ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Warning__No_export_strategy_specified__from__sin" +
"gle____protein__or__buckets____Defaulting_to__single__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: The add-energy-ramp parameter is only applicable for Thermo transition lists. This parameter will be ignored..
/// </summary>
public static string CommandLine_ExportInstrumentFile_Warning__The_add_energy_ramp_parameter_is_only_applicable_for_Thermo_transition_lists__This_parameter_will_be_ignored_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Warning__The_add_energy_ramp_parameter_is_only_a" +
"pplicable_for_Thermo_transition_lists__This_parameter_will_be_ignored_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: The vendor {0} does not match the vendor in either the CE or DP prediction setting. Continuing exporting a transition list anyway....
/// </summary>
public static string CommandLine_ExportInstrumentFile_Warning__The_vendor__0__does_not_match_the_vendor_in_either_the_CE_or_DP_prediction_setting___Continuing_exporting_a_transition_list_anyway___ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_Warning__The_vendor__0__does_not_match_the_vendo" +
"r_in_either_the_CE_or_DP_prediction_setting___Continuing_exporting_a_transition_" +
"list_anyway___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must export a {0} transition list and manually import it into a method file using vendor software..
/// </summary>
public static string CommandLine_ExportInstrumentFile_You_must_export_a__0__transition_list_and_manually_import_it_into_a_method_file_using_vendor_software_ {
get {
return ResourceManager.GetString("CommandLine_ExportInstrumentFile_You_must_export_a__0__transition_list_and_manual" +
"ly_import_it_into_a_method_file_using_vendor_software_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check to make sure it is not read-only..
/// </summary>
public static string CommandLine_ExportLiveReport_Check_to_make_sure_it_is_not_read_only_ {
get {
return ResourceManager.GetString("CommandLine_ExportLiveReport_Check_to_make_sure_it_is_not_read_only_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failure attempting to save {0} report to {1}..
/// </summary>
public static string CommandLine_ExportLiveReport_Error__Failure_attempting_to_save__0__report_to__1__ {
get {
return ResourceManager.GetString("CommandLine_ExportLiveReport_Error__Failure_attempting_to_save__0__report_to__1__" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The report {0} could not be saved to {1}..
/// </summary>
public static string CommandLine_ExportLiveReport_Error__The_report__0__could_not_be_saved_to__1__ {
get {
return ResourceManager.GetString("CommandLine_ExportLiveReport_Error__The_report__0__could_not_be_saved_to__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The report {0} does not exist. If it has spaces in its name, use "double quotes" around the entire list of command parameters..
/// </summary>
public static string CommandLine_ExportLiveReport_Error__The_report__0__does_not_exist__If_it_has_spaces_in_its_name__use__double_quotes__around_the_entire_list_of_command_parameters_ {
get {
return ResourceManager.GetString("CommandLine_ExportLiveReport_Error__The_report__0__does_not_exist__If_it_has_spac" +
"es_in_its_name__use__double_quotes__around_the_entire_list_of_command_parameters" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting report {0}....
/// </summary>
public static string CommandLine_ExportLiveReport_Exporting_report__0____ {
get {
return ResourceManager.GetString("CommandLine_ExportLiveReport_Exporting_report__0____", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Report {0} exported successfully to {1}..
/// </summary>
public static string CommandLine_ExportLiveReport_Report__0__exported_successfully_to__1__ {
get {
return ResourceManager.GetString("CommandLine_ExportLiveReport_Report__0__exported_successfully_to__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: If you specify a report, you must specify the --report-file=path/to/file.csv parameter..
/// </summary>
public static string CommandLine_ExportReport_ {
get {
return ResourceManager.GetString("CommandLine_ExportReport_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failure attempting to save {0} report to {1}..
/// </summary>
public static string CommandLine_ExportReport_Error__Failure_attempting_to_save__0__report_to__1__ {
get {
return ResourceManager.GetString("CommandLine_ExportReport_Error__Failure_attempting_to_save__0__report_to__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The report {0} could not be saved to {1}. Check to make sure it is not read-only..
/// </summary>
public static string CommandLine_ExportReport_Error__The_report__0__could_not_be_saved_to__1____Check_to_make_sure_it_is_not_read_only_ {
get {
return ResourceManager.GetString("CommandLine_ExportReport_Error__The_report__0__could_not_be_saved_to__1____Check_" +
"to_make_sure_it_is_not_read_only_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The report {0} does not exist. If it has spaces in its name, use "double quotes" around the entire list of command parameters..
/// </summary>
public static string CommandLine_ExportReport_Error__The_report__0__does_not_exist__If_it_has_spaces_in_its_name__use__double_quotes__around_the_entire_list_of_command_parameters_ {
get {
return ResourceManager.GetString("CommandLine_ExportReport_Error__The_report__0__does_not_exist__If_it_has_spaces_i" +
"n_its_name__use__double_quotes__around_the_entire_list_of_command_parameters_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting report {0}....
/// </summary>
public static string CommandLine_ExportReport_Exporting_report__0____ {
get {
return ResourceManager.GetString("CommandLine_ExportReport_Exporting_report__0____", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Report {0} exported successfully..
/// </summary>
public static string CommandLine_ExportReport_Report__0__exported_successfully_ {
get {
return ResourceManager.GetString("CommandLine_ExportReport_Report__0__exported_successfully_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: Could not find the background proteome file {0}..
/// </summary>
public static string CommandLine_FindBackgroundProteome_Warning__Could_not_find_the_background_proteome_file__0__ {
get {
return ResourceManager.GetString("CommandLine_FindBackgroundProteome_Warning__Could_not_find_the_background_proteom" +
"e_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Could not find the ion mobility library {0}..
/// </summary>
public static string CommandLine_FindIonMobilityDatabase_Error__Could_not_find_the_ion_mobility_library__0__ {
get {
return ResourceManager.GetString("CommandLine_FindIonMobilityDatabase_Error__Could_not_find_the_ion_mobility_librar" +
"y__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Could not find the iRT database {0}..
/// </summary>
public static string CommandLine_FindIrtDatabase_Error__Could_not_find_the_iRT_database__0__ {
get {
return ResourceManager.GetString("CommandLine_FindIrtDatabase_Error__Could_not_find_the_iRT_database__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not find the optimization library {0}..
/// </summary>
public static string CommandLine_FindOptimizationDatabase_Could_not_find_the_optimization_library__0__ {
get {
return ResourceManager.GetString("CommandLine_FindOptimizationDatabase_Could_not_find_the_optimization_library__0__" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: {0}.
/// </summary>
public static string CommandLine_GeneralException_Error___0_ {
get {
return ResourceManager.GetString("CommandLine_GeneralException_Error___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failure reading file information from directory {0}..
/// </summary>
public static string CommandLine_GetDataSources_Error__Failure_reading_file_information_from_directory__0__ {
get {
return ResourceManager.GetString("CommandLine_GetDataSources_Error__Failure_reading_file_information_from_directory" +
"__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: No data sources found in directory {0}..
/// </summary>
public static string CommandLine_GetDataSources_Error__No_data_sources_found_in_directory__0__ {
get {
return ResourceManager.GetString("CommandLine_GetDataSources_Error__No_data_sources_found_in_directory__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed while reading annotations..
/// </summary>
public static string CommandLine_ImportAnnotations_Error__Failed_while_reading_annotations_ {
get {
return ResourceManager.GetString("CommandLine_ImportAnnotations_Error__Failed_while_reading_annotations_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The replicate {0} already exists in the given document and the --import-append option is not specified. The replicate will not be added to the document..
/// </summary>
public static string CommandLine_ImportDataFilesWithAppend_Error__The_replicate__0__already_exists_in_the_given_document_and_the___import_append_option_is_not_specified___The_replicate_will_not_be_added_to_the_document_ {
get {
return ResourceManager.GetString("CommandLine_ImportDataFilesWithAppend_Error__The_replicate__0__already_exists_in_" +
"the_given_document_and_the___import_append_option_is_not_specified___The_replica" +
"te_will_not_be_added_to_the_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Importing FASTA file {0}....
/// </summary>
public static string CommandLine_ImportFasta_Importing_FASTA_file__0____ {
get {
return ResourceManager.GetString("CommandLine_ImportFasta_Importing_FASTA_file__0____", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: No files left to import..
/// </summary>
public static string CommandLine_ImportResults_Error__No_files_left_to_import_ {
get {
return ResourceManager.GetString("CommandLine_ImportResults_Error__No_files_left_to_import_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} -> {1} Note: The file has already been imported. Ignoring....
/// </summary>
public static string CommandLine_ImportResultsFile__0______1___Note__The_file_has_already_been_imported__Ignoring___ {
get {
return ResourceManager.GetString("CommandLine_ImportResultsFile__0______1___Note__The_file_has_already_been_importe" +
"d__Ignoring___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding results....
/// </summary>
public static string CommandLine_ImportResultsFile_Adding_results___ {
get {
return ResourceManager.GetString("CommandLine_ImportResultsFile_Adding_results___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed importing the results file {0}..
/// </summary>
public static string CommandLine_ImportResultsFile_Error__Failed_importing_the_results_file__0__ {
get {
return ResourceManager.GetString("CommandLine_ImportResultsFile_Error__Failed_importing_the_results_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File write date {0} is after --import-before date {1}. Ignoring....
/// </summary>
public static string CommandLine_ImportResultsFile_File_write_date__0__is_after___import_before_date__1___Ignoring___ {
get {
return ResourceManager.GetString("CommandLine_ImportResultsFile_File_write_date__0__is_after___import_before_date__" +
"1___Ignoring___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File write date {0} is before --import-on-or-after date {1}. Ignoring....
/// </summary>
public static string CommandLine_ImportResultsFile_File_write_date__0__is_before___import_on_or_after_date__1___Ignoring___ {
get {
return ResourceManager.GetString("CommandLine_ImportResultsFile_File_write_date__0__is_before___import_on_or_after_" +
"date__1___Ignoring___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results added from {0} to replicate {1}..
/// </summary>
public static string CommandLine_ImportResultsFile_Results_added_from__0__to_replicate__1__ {
get {
return ResourceManager.GetString("CommandLine_ImportResultsFile_Results_added_from__0__to_replicate__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: Failed importing the results file {0}. Ignoring....
/// </summary>
public static string CommandLine_ImportResultsFile_Warning__Failed_importing_the_results_file__0____Ignoring___ {
get {
return ResourceManager.GetString("CommandLine_ImportResultsFile_Warning__Failed_importing_the_results_file__0____Ig" +
"noring___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Could not get last write time for file {0}..
/// </summary>
public static string CommandLine_ImportResultsInDir_Error__Could_not_get_last_write_time_for_file__0__ {
get {
return ResourceManager.GetString("CommandLine_ImportResultsInDir_Error__Could_not_get_last_write_time_for_file__0__" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding {0} modifications..
/// </summary>
public static string CommandLine_ImportSearch_Adding__0__modifications_ {
get {
return ResourceManager.GetString("CommandLine_ImportSearch_Adding__0__modifications_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding 1 modification..
/// </summary>
public static string CommandLine_ImportSearch_Adding_1_modification_ {
get {
return ResourceManager.GetString("CommandLine_ImportSearch_Adding_1_modification_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Creating spectral library from files:.
/// </summary>
public static string CommandLine_ImportSearch_Creating_spectral_library_from_files_ {
get {
return ResourceManager.GetString("CommandLine_ImportSearch_Creating_spectral_library_from_files_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading library.
/// </summary>
public static string CommandLine_ImportSearch_Loading_library {
get {
return ResourceManager.GetString("CommandLine_ImportSearch_Loading_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: Unable to locate results file '{0}'.
/// </summary>
public static string CommandLine_ImportSearch_Warning__Unable_to_locate_results_file___0__ {
get {
return ResourceManager.GetString("CommandLine_ImportSearch_Warning__Unable_to_locate_results_file___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: {0} must be set when using CiRT peptides..
/// </summary>
public static string CommandLine_ImportSearchInternal_Error___0__must_be_set_when_using_CiRT_peptides_ {
get {
return ResourceManager.GetString("CommandLine_ImportSearchInternal_Error___0__must_be_set_when_using_CiRT_peptides_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT standard set to {0}, but multiple iRT standards were found. iRT standard must be set explicitly..
/// </summary>
public static string CommandLine_ImportSearchInternal_iRT_standard_set_to__0___but_multiple_iRT_standards_were_found__iRT_standard_must_be_set_explicitly_ {
get {
return ResourceManager.GetString("CommandLine_ImportSearchInternal_iRT_standard_set_to__0___but_multiple_iRT_standa" +
"rds_were_found__iRT_standard_must_be_set_explicitly_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The iRT standard name '{0}' is invalid..
/// </summary>
public static string CommandLine_ImportSearchInternal_The_iRT_standard_name___0___is_invalid_ {
get {
return ResourceManager.GetString("CommandLine_ImportSearchInternal_The_iRT_standard_name___0___is_invalid_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed to load {0}..
/// </summary>
public static string CommandLine_ImportSkyr_ {
get {
return ResourceManager.GetString("CommandLine_ImportSkyr_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: {0} does not exist. --report-add command failed..
/// </summary>
public static string CommandLine_ImportSkyr_Error___0__does_not_exist____report_add_command_failed_ {
get {
return ResourceManager.GetString("CommandLine_ImportSkyr_Error___0__does_not_exist____report_add_command_failed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Success! Imported Reports from {0}.
/// </summary>
public static string CommandLine_ImportSkyr_Success__Imported_Reports_from__0_ {
get {
return ResourceManager.GetString("CommandLine_ImportSkyr_Success__Imported_Reports_from__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: A tool titled {0} already exists. Please use --tool-conflict-resolution=< overwrite | skip >. Tool titled {0} was not added..
/// </summary>
public static string CommandLine_ImportTool_ {
get {
return ResourceManager.GetString("CommandLine_ImportTool_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} was added to the Tools Menu..
/// </summary>
public static string CommandLine_ImportTool__0__was_added_to_the_Tools_Menu_ {
get {
return ResourceManager.GetString("CommandLine_ImportTool__0__was_added_to_the_Tools_Menu_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: If {0} is and argument the tool must have a Report Title. Use the --tool-report parameter to specify a report..
/// </summary>
public static string CommandLine_ImportTool_Error__If__0__is_and_argument_the_tool_must_have_a_Report_Title__Use_the___tool_report_parameter_to_specify_a_report_ {
get {
return ResourceManager.GetString("CommandLine_ImportTool_Error__If__0__is_and_argument_the_tool_must_have_a_Report_" +
"Title__Use_the___tool_report_parameter_to_specify_a_report_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Please import the report format for {0}. Use the --report-add parameter to add the missing custom report..
/// </summary>
public static string CommandLine_ImportTool_Error__Please_import_the_report_format_for__0____Use_the___report_add_parameter_to_add_the_missing_custom_report_ {
get {
return ResourceManager.GetString("CommandLine_ImportTool_Error__Please_import_the_report_format_for__0____Use_the__" +
"_report_add_parameter_to_add_the_missing_custom_report_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: the provided command for the tool {0} is not of a supported type. Supported Types are: {1}.
/// </summary>
public static string CommandLine_ImportTool_Error__the_provided_command_for_the_tool__0__is_not_of_a_supported_type___Supported_Types_are___1_ {
get {
return ResourceManager.GetString("CommandLine_ImportTool_Error__the_provided_command_for_the_tool__0__is_not_of_a_s" +
"upported_type___Supported_Types_are___1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: to import a tool it must have a name and a command. Use --tool-add to specify a name and use --tool-command to specify a command. The tool was not imported....
/// </summary>
public static string CommandLine_ImportTool_Error__to_import_a_tool_it_must_have_a_name_and_a_command___Use___tool_add_to_specify_a_name_and_use___tool_command_to_specify_a_command___The_tool_was_not_imported___ {
get {
return ResourceManager.GetString("CommandLine_ImportTool_Error__to_import_a_tool_it_must_have_a_name_and_a_command_" +
"__Use___tool_add_to_specify_a_name_and_use___tool_command_to_specify_a_command__" +
"_The_tool_was_not_imported___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The tool was not imported....
/// </summary>
public static string CommandLine_ImportTool_The_tool_was_not_imported___ {
get {
return ResourceManager.GetString("CommandLine_ImportTool_The_tool_was_not_imported___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: skipping tool {0} due to a name conflict..
/// </summary>
public static string CommandLine_ImportTool_Warning__skipping_tool__0__due_to_a_name_conflict_ {
get {
return ResourceManager.GetString("CommandLine_ImportTool_Warning__skipping_tool__0__due_to_a_name_conflict_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: the tool {0} was overwritten.
/// </summary>
public static string CommandLine_ImportTool_Warning__the_tool__0__was_overwritten {
get {
return ResourceManager.GetString("CommandLine_ImportTool_Warning__the_tool__0__was_overwritten", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Canceled installing tools from {0}..
/// </summary>
public static string CommandLine_ImportToolsFromZip_Error__Canceled_installing_tools_from__0__ {
get {
return ResourceManager.GetString("CommandLine_ImportToolsFromZip_Error__Canceled_installing_tools_from__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: the file specified with the --tool-add-zip command does not exist. Please verify the file location and try again..
/// </summary>
public static string CommandLine_ImportToolsFromZip_Error__the_file_specified_with_the___tool_add_zip_command_does_not_exist__Please_verify_the_file_location_and_try_again_ {
get {
return ResourceManager.GetString("CommandLine_ImportToolsFromZip_Error__the_file_specified_with_the___tool_add_zip_" +
"command_does_not_exist__Please_verify_the_file_location_and_try_again_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: the file specified with the --tool-add-zip command is not a .zip file. Please specify a valid .zip file..
/// </summary>
public static string CommandLine_ImportToolsFromZip_Error__the_file_specified_with_the___tool_add_zip_command_is_not_a__zip_file__Please_specify_a_valid__zip_file_ {
get {
return ResourceManager.GetString("CommandLine_ImportToolsFromZip_Error__the_file_specified_with_the___tool_add_zip_" +
"command_is_not_a__zip_file__Please_specify_a_valid__zip_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: to import tools from a zip you must specify a path --tool-add-zip must be followed by an existing path..
/// </summary>
public static string CommandLine_ImportToolsFromZip_Error__to_import_tools_from_a_zip_you_must_specify_a_path___tool_add_zip_must_be_followed_by_an_existing_path_ {
get {
return ResourceManager.GetString("CommandLine_ImportToolsFromZip_Error__to_import_tools_from_a_zip_you_must_specify" +
"_a_path___tool_add_zip_must_be_followed_by_an_existing_path_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Installed tool {0}.
/// </summary>
public static string CommandLine_ImportToolsFromZip_Installed_tool__0_ {
get {
return ResourceManager.GetString("CommandLine_ImportToolsFromZip_Installed_tool__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Installing tools from {0}.
/// </summary>
public static string CommandLine_ImportToolsFromZip_Installing_tools_from__0_ {
get {
return ResourceManager.GetString("CommandLine_ImportToolsFromZip_Installing_tools_from__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding {0} spectra to the library {1}.
/// </summary>
public static string CommandLine_ImportTransitionList_Adding__0__spectra_to_the_library__1_ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Adding__0__spectra_to_the_library__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: (line {0}, column {1}) {2}.
/// </summary>
public static string CommandLine_ImportTransitionList_Error___line__0___column__1____2_ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Error___line__0___column__1____2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Imported assay library {0} lacks ion abundance values..
/// </summary>
public static string CommandLine_ImportTransitionList_Error__Imported_assay_library__0__lacks_ion_abundance_values_ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Error__Imported_assay_library__0__lacks_ion_abun" +
"dance_values_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Imported assay library {0} lacks iRT and ion abundance values..
/// </summary>
public static string CommandLine_ImportTransitionList_Error__Imported_assay_library__0__lacks_iRT_and_ion_abundance_values_ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Error__Imported_assay_library__0__lacks_iRT_and_" +
"ion_abundance_values_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Imported assay library {0} lacks iRT values..
/// </summary>
public static string CommandLine_ImportTransitionList_Error__Imported_assay_library__0__lacks_iRT_values_ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Error__Imported_assay_library__0__lacks_iRT_valu" +
"es_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The name {0} specified with {1} was not found in the imported assay library..
/// </summary>
public static string CommandLine_ImportTransitionList_Error__The_name__0__specified_with__1__was_not_found_in_the_imported_assay_library_ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Error__The_name__0__specified_with__1__was_not_f" +
"ound_in_the_imported_assay_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: There is an existing library with the same name {0} as the document library to be created..
/// </summary>
public static string CommandLine_ImportTransitionList_Error__There_is_an_existing_library_with_the_same_name__0__as_the_document_library_to_be_created_ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Error__There_is_an_existing_library_with_the_sam" +
"e_name__0__as_the_document_library_to_be_created_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: To create the iRT database '{0}' for this assay library, you must specify the iRT standards using either of the arguments {1} or {2}.
/// </summary>
public static string CommandLine_ImportTransitionList_Error__To_create_the_iRT_database___0___for_this_assay_library__you_must_specify_the_iRT_standards_using_either_of_the_arguments__1__or__2_ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Error__To_create_the_iRT_database___0___for_this" +
"_assay_library__you_must_specify_the_iRT_standards_using_either_of_the_arguments" +
"__1__or__2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Finishing up import.
/// </summary>
public static string CommandLine_ImportTransitionList_Finishing_up_import {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Finishing_up_import", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Importing {0} iRT values into the iRT calculator {1}.
/// </summary>
public static string CommandLine_ImportTransitionList_Importing__0__iRT_values_into_the_iRT_calculator__1_ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Importing__0__iRT_values_into_the_iRT_calculator" +
"__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Importing iRT transition list {0}.
/// </summary>
public static string CommandLine_ImportTransitionList_Importing_iRT_transition_list__0_ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Importing_iRT_transition_list__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Importing transiton list {0}....
/// </summary>
public static string CommandLine_ImportTransitionList_Importing_transiton_list__0____ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Importing_transiton_list__0____", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: (line {0}, column {1}) {2}.
/// </summary>
public static string CommandLine_ImportTransitionList_Warning___line__0___column__1____2_ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Warning___line__0___column__1____2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: The document is missing iRT standards.
/// </summary>
public static string CommandLine_ImportTransitionList_Warning__The_document_is_missing_iRT_standards {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Warning__The_document_is_missing_iRT_standards", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning: The iRT calculator already contains {0} with the value {1}. Ignoring {2}.
/// </summary>
public static string CommandLine_ImportTransitionList_Warning__The_iRT_calculator_already_contains__0__with_the_value__1___Ignoring__2_ {
get {
return ResourceManager.GetString("CommandLine_ImportTransitionList_Warning__The_iRT_calculator_already_contains__0_" +
"_with_the_value__1___Ignoring__2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Added: {0}.
/// </summary>
public static string CommandLine_LogDocumentDelta_Added___0_ {
get {
return ResourceManager.GetString("CommandLine_LogDocumentDelta_Added___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removed: {0}.
/// </summary>
public static string CommandLine_LogDocumentDelta_Removed___0_ {
get {
return ResourceManager.GetString("CommandLine_LogDocumentDelta_Removed___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document unchanged.
/// </summary>
public static string CommandLine_LogNewEntries_Document_unchanged {
get {
return ResourceManager.GetString("CommandLine_LogNewEntries_Document_unchanged", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicate '{0}' already exists in the document, using '{1}' instead..
/// </summary>
public static string CommandLine_MakeReplicateNamesUnique_Replicate___0___already_exists_in_the_document__using___1___instead_ {
get {
return ResourceManager.GetString("CommandLine_MakeReplicateNamesUnique_Replicate___0___already_exists_in_the_docume" +
"nt__using___1___instead_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Limiting chromatogram noise to +/- {0} minutes around peak....
/// </summary>
public static string CommandLine_MinimizeResults_Limiting_chromatogram_noise_to______0__minutes_around_peak___ {
get {
return ResourceManager.GetString("CommandLine_MinimizeResults_Limiting_chromatogram_noise_to______0__minutes_around" +
"_peak___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Minimizing results to {0}.
/// </summary>
public static string CommandLine_MinimizeResults_Minimizing_results_to__0_ {
get {
return ResourceManager.GetString("CommandLine_MinimizeResults_Minimizing_results_to__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removing unused chromatograms....
/// </summary>
public static string CommandLine_MinimizeResults_Removing_unused_chromatograms___ {
get {
return ResourceManager.GetString("CommandLine_MinimizeResults_Removing_unused_chromatograms___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The Skyline file {0} does not exist..
/// </summary>
public static string CommandLine_OpenSkyFile_Error__The_Skyline_file__0__does_not_exist_ {
get {
return ResourceManager.GetString("CommandLine_OpenSkyFile_Error__The_Skyline_file__0__does_not_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: There was an error opening the file {0}.
/// </summary>
public static string CommandLine_OpenSkyFile_Error__There_was_an_error_opening_the_file__0_ {
get {
return ResourceManager.GetString("CommandLine_OpenSkyFile_Error__There_was_an_error_opening_the_file__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File {0} opened..
/// </summary>
public static string CommandLine_OpenSkyFile_File__0__opened_ {
get {
return ResourceManager.GetString("CommandLine_OpenSkyFile_File__0__opened_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Opening file....
/// </summary>
public static string CommandLine_OpenSkyFile_Opening_file___ {
get {
return ResourceManager.GetString("CommandLine_OpenSkyFile_Opening_file___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: No new results added. Skipping Panorama import..
/// </summary>
public static string CommandLine_PerformExportOperations_Error__No_new_results_added__Skipping_Panorama_import_ {
get {
return ResourceManager.GetString("CommandLine_PerformExportOperations_Error__No_new_results_added__Skipping_Panoram" +
"a_import_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Choose one of {0}.
/// </summary>
public static string CommandLine_RefineDocument_Choose_one_of__0_ {
get {
return ResourceManager.GetString("CommandLine_RefineDocument_Choose_one_of__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The label type '{0}' was not found in the document..
/// </summary>
public static string CommandLine_RefineDocument_Error__The_label_type___0___was_not_found_in_the_document_ {
get {
return ResourceManager.GetString("CommandLine_RefineDocument_Error__The_label_type___0___was_not_found_in_the_docum" +
"ent_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Refining document....
/// </summary>
public static string CommandLine_RefineDocument_Refining_document___ {
get {
return ResourceManager.GetString("CommandLine_RefineDocument_Refining_document___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed to reintegrate peaks successfully..
/// </summary>
public static string CommandLine_Reintegrate_Error__Failed_to_reintegrate_peaks_successfully_ {
get {
return ResourceManager.GetString("CommandLine_Reintegrate_Error__Failed_to_reintegrate_peaks_successfully_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The current peak scoring model is incompatible with one or more peptides in the document. Please train a new model..
/// </summary>
public static string CommandLine_Reintegrate_Error__The_current_peak_scoring_model_is_incompatible_with_one_or_more_peptides_in_the_document__Please_train_a_new_model_ {
get {
return ResourceManager.GetString("CommandLine_Reintegrate_Error__The_current_peak_scoring_model_is_incompatible_wit" +
"h_one_or_more_peptides_in_the_document__Please_train_a_new_model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Unknown peak scoring model '{0}'.
/// </summary>
public static string CommandLine_ReintegratePeaks_Error__Unknown_peak_scoring_model___0__ {
get {
return ResourceManager.GetString("CommandLine_ReintegratePeaks_Error__Unknown_peak_scoring_model___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: You must first import results into the document before reintegrating..
/// </summary>
public static string CommandLine_ReintegratePeaks_Error__You_must_first_import_results_into_the_document_before_reintegrating_ {
get {
return ResourceManager.GetString("CommandLine_ReintegratePeaks_Error__You_must_first_import_results_into_the_docume" +
"nt_before_reintegrating_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} -> {1} Note: The file has already been imported. Ignoring....
/// </summary>
public static string CommandLine_RemoveImportedFiles__0______1___Note__The_file_has_already_been_imported__Ignoring___ {
get {
return ResourceManager.GetString("CommandLine_RemoveImportedFiles__0______1___Note__The_file_has_already_been_impor" +
"ted__Ignoring___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removed {0}..
/// </summary>
public static string CommandLine_RemoveResults_Removed__0__ {
get {
return ResourceManager.GetString("CommandLine_RemoveResults_Removed__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removing all results.
/// </summary>
public static string CommandLine_RemoveResults_Removing_all_results {
get {
return ResourceManager.GetString("CommandLine_RemoveResults_Removing_all_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removing results before .
/// </summary>
public static string CommandLine_RemoveResults_Removing_results_before_ {
get {
return ResourceManager.GetString("CommandLine_RemoveResults_Removing_results_before_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed importing the file {0}. {1}.
/// </summary>
public static string CommandLine_Run_Error__Failed_importing_the_file__0____1_ {
get {
return ResourceManager.GetString("CommandLine_Run_Error__Failed_importing_the_file__0____1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed to get optimization function {0}. {1}.
/// </summary>
public static string CommandLine_Run_Error__Failed_to_get_optimization_function__0____1_ {
get {
return ResourceManager.GetString("CommandLine_Run_Error__Failed_to_get_optimization_function__0____1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed to open log file {0}.
/// </summary>
public static string CommandLine_Run_Error__Failed_to_open_log_file__0_ {
get {
return ResourceManager.GetString("CommandLine_Run_Error__Failed_to_open_log_file__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failure occurred. Exiting....
/// </summary>
public static string CommandLine_Run_Error__Failure_occurred__Exiting___ {
get {
return ResourceManager.GetString("CommandLine_Run_Error__Failure_occurred__Exiting___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: You cannot simultaneously export a transition list and a method. Neither will be exported. Please change the command line parameters..
/// </summary>
public static string CommandLine_Run_Error__You_cannot_simultaneously_export_a_transition_list_and_a_method___Neither_will_be_exported__ {
get {
return ResourceManager.GetString("CommandLine_Run_Error__You_cannot_simultaneously_export_a_transition_list_and_a_m" +
"ethod___Neither_will_be_exported__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exiting....
/// </summary>
public static string CommandLine_Run_Exiting___ {
get {
return ResourceManager.GetString("CommandLine_Run_Exiting___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Not setting library..
/// </summary>
public static string CommandLine_Run_Not_setting_library_ {
get {
return ResourceManager.GetString("CommandLine_Run_Not_setting_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Writing to log file {0}.
/// </summary>
public static string CommandLine_Run_Writing_to_log_file__0_ {
get {
return ResourceManager.GetString("CommandLine_Run_Writing_to_log_file__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: {0} does not exist. --batch-commands failed..
/// </summary>
public static string CommandLine_RunBatchCommands_Error___0__does_not_exist____batch_commands_failed_ {
get {
return ResourceManager.GetString("CommandLine_RunBatchCommands_Error___0__does_not_exist____batch_commands_failed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: failed to open file {0} --batch-commands command failed..
/// </summary>
public static string CommandLine_RunBatchCommands_Error__failed_to_open_file__0____batch_commands_command_failed_ {
get {
return ResourceManager.GetString("CommandLine_RunBatchCommands_Error__failed_to_open_file__0____batch_commands_comm" +
"and_failed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The file could not be saved to {0}. Check that the directory exists and is not read-only..
/// </summary>
public static string CommandLine_SaveFile_Error__The_file_could_not_be_saved_to__0____Check_that_the_directory_exists_and_is_not_read_only_ {
get {
return ResourceManager.GetString("CommandLine_SaveFile_Error__The_file_could_not_be_saved_to__0____Check_that_the_d" +
"irectory_exists_and_is_not_read_only_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File {0} saved..
/// </summary>
public static string CommandLine_SaveFile_File__0__saved_ {
get {
return ResourceManager.GetString("CommandLine_SaveFile_File__0__saved_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Saving file....
/// </summary>
public static string CommandLine_SaveFile_Saving_file___ {
get {
return ResourceManager.GetString("CommandLine_SaveFile_Saving_file___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed saving to the user configuration file..
/// </summary>
public static string CommandLine_SaveSettings_Error__Failed_saving_to_the_user_configuration_file_ {
get {
return ResourceManager.GetString("CommandLine_SaveSettings_Error__Failed_saving_to_the_user_configuration_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed attempting to change the transition filter settings..
/// </summary>
public static string CommandLine_SetFilterSettings_Error__Failed_attempting_to_change_the_transition_filter_settings_ {
get {
return ResourceManager.GetString("CommandLine_SetFilterSettings_Error__Failed_attempting_to_change_the_transition_f" +
"ilter_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing full-scan extraction to +/- {0} minutes from MS/MS IDs..
/// </summary>
public static string CommandLine_SetFullScanSettings_Changing_full_scan_extraction_to______0__minutes_from_MS_MS_IDs_ {
get {
return ResourceManager.GetString("CommandLine_SetFullScanSettings_Changing_full_scan_extraction_to______0__minutes_" +
"from_MS_MS_IDs_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing full-scan extraction to +/- {0} minutes from predicted value..
/// </summary>
public static string CommandLine_SetFullScanSettings_Changing_full_scan_extraction_to______0__minutes_from_predicted_value_ {
get {
return ResourceManager.GetString("CommandLine_SetFullScanSettings_Changing_full_scan_extraction_to______0__minutes_" +
"from_predicted_value_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing full scan precursor mass accuracy to {0} ppm..
/// </summary>
public static string CommandLine_SetFullScanSettings_Changing_full_scan_precursor_mass_accuracy_to__0__ppm_ {
get {
return ResourceManager.GetString("CommandLine_SetFullScanSettings_Changing_full_scan_precursor_mass_accuracy_to__0_" +
"_ppm_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing full-scan precursor resolution to {0}..
/// </summary>
public static string CommandLine_SetFullScanSettings_Changing_full_scan_precursor_resolution_to__0__ {
get {
return ResourceManager.GetString("CommandLine_SetFullScanSettings_Changing_full_scan_precursor_resolution_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing full-scan precursor resolving power to {0}..
/// </summary>
public static string CommandLine_SetFullScanSettings_Changing_full_scan_precursor_resolving_power_to__0__ {
get {
return ResourceManager.GetString("CommandLine_SetFullScanSettings_Changing_full_scan_precursor_resolving_power_to__" +
"0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing full-scan precursor resolving power to {0} at {1}..
/// </summary>
public static string CommandLine_SetFullScanSettings_Changing_full_scan_precursor_resolving_power_to__0__at__1__ {
get {
return ResourceManager.GetString("CommandLine_SetFullScanSettings_Changing_full_scan_precursor_resolving_power_to__" +
"0__at__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing full scan product mass accuracy to {0} ppm..
/// </summary>
public static string CommandLine_SetFullScanSettings_Changing_full_scan_product_mass_accuracy_to__0__ppm_ {
get {
return ResourceManager.GetString("CommandLine_SetFullScanSettings_Changing_full_scan_product_mass_accuracy_to__0__p" +
"pm_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing full-scan product resolution to {0}..
/// </summary>
public static string CommandLine_SetFullScanSettings_Changing_full_scan_product_resolution_to__0__ {
get {
return ResourceManager.GetString("CommandLine_SetFullScanSettings_Changing_full_scan_product_resolution_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing full-scan product resolving power to {0}..
/// </summary>
public static string CommandLine_SetFullScanSettings_Changing_full_scan_product_resolving_power_to__0__ {
get {
return ResourceManager.GetString("CommandLine_SetFullScanSettings_Changing_full_scan_product_resolving_power_to__0_" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing full-scan product resolving power to {0} at {1}..
/// </summary>
public static string CommandLine_SetFullScanSettings_Changing_full_scan_product_resolving_power_to__0__at__1__ {
get {
return ResourceManager.GetString("CommandLine_SetFullScanSettings_Changing_full_scan_product_resolving_power_to__0_" +
"_at__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed attempting to change the transiton full-scan settings..
/// </summary>
public static string CommandLine_SetFullScanSettings_Error__Failed_attempting_to_change_the_transiton_full_scan_settings_ {
get {
return ResourceManager.GetString("CommandLine_SetFullScanSettings_Error__Failed_attempting_to_change_the_transiton_" +
"full_scan_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing ion mobility spectral library resolving power to {0}..
/// </summary>
public static string CommandLine_SetImsSettings_Changing_ion_mobility_spectral_library_resolving_power_to__0__ {
get {
return ResourceManager.GetString("CommandLine_SetImsSettings_Changing_ion_mobility_spectral_library_resolving_power" +
"_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enabling extraction based on spectral library ion mobility values..
/// </summary>
public static string CommandLine_SetImsSettings_Enabling_extraction_based_on_spectral_library_ion_mobility_values_ {
get {
return ResourceManager.GetString("CommandLine_SetImsSettings_Enabling_extraction_based_on_spectral_library_ion_mobi" +
"lity_values_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed attempting to change the ion mobility settings..
/// </summary>
public static string CommandLine_SetImsSettings_Error__Failed_attempting_to_change_the_ion_mobility_settings_ {
get {
return ResourceManager.GetString("CommandLine_SetImsSettings_Error__Failed_attempting_to_change_the_ion_mobility_se" +
"ttings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Cannot set library name without path..
/// </summary>
public static string CommandLine_SetLibrary_Error__Cannot_set_library_name_without_path_ {
get {
return ResourceManager.GetString("CommandLine_SetLibrary_Error__Cannot_set_library_name_without_path_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The file {0} appears to be a redundant library..
/// </summary>
public static string CommandLine_SetLibrary_Error__The_file__0__appears_to_be_a_redundant_library_ {
get {
return ResourceManager.GetString("CommandLine_SetLibrary_Error__The_file__0__appears_to_be_a_redundant_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The file {0} does not exist..
/// </summary>
public static string CommandLine_SetLibrary_Error__The_file__0__does_not_exist_ {
get {
return ResourceManager.GetString("CommandLine_SetLibrary_Error__The_file__0__does_not_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The file {0} is not a supported spectral library file format..
/// </summary>
public static string CommandLine_SetLibrary_Error__The_file__0__is_not_a_supported_spectral_library_file_format_ {
get {
return ResourceManager.GetString("CommandLine_SetLibrary_Error__The_file__0__is_not_a_supported_spectral_library_fi" +
"le_format_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The library you are trying to add conflicts with a library already in the file..
/// </summary>
public static string CommandLine_SetLibrary_Error__The_library_you_are_trying_to_add_conflicts_with_a_library_already_in_the_file_ {
get {
return ResourceManager.GetString("CommandLine_SetLibrary_Error__The_library_you_are_trying_to_add_conflicts_with_a_" +
"library_already_in_the_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed attempting to change the transition prediction settings..
/// </summary>
public static string CommandLine_SetPredictTranSettings_Error__Failed_attempting_to_change_the_transition_prediction_settings_ {
get {
return ResourceManager.GetString("CommandLine_SetPredictTranSettings_Error__Failed_attempting_to_change_the_transit" +
"ion_prediction_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use the argument --import-search-prefer-embedded-spectra to force the library build to use embedded spectra, or place the original spectrum files in one of the directories listed above and rerun..
/// </summary>
public static string CommandLine_ShowLibraryMissingExternalSpectraError_Description {
get {
return ResourceManager.GetString("CommandLine_ShowLibraryMissingExternalSpectraError_Description", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error.
/// </summary>
public static string CommandLineTest_ConsoleAddFastaTest_Error {
get {
return ResourceManager.GetString("CommandLineTest_ConsoleAddFastaTest_Error", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning.
/// </summary>
public static string CommandLineTest_ConsoleAddFastaTest_Warning {
get {
return ResourceManager.GetString("CommandLineTest_ConsoleAddFastaTest_Warning", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to successfully..
/// </summary>
public static string CommandLineTest_ConsolePathCoverage_successfully_ {
get {
return ResourceManager.GetString("CommandLineTest_ConsolePathCoverage_successfully_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Message: .
/// </summary>
public static string CommandProgressMonitor_UpdateProgressInternal_Message__ {
get {
return ResourceManager.GetString("CommandProgressMonitor_UpdateProgressInternal_Message__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error:.
/// </summary>
public static string CommandStatusWriter_WriteLine_Error_ {
get {
return ResourceManager.GetString("CommandStatusWriter_WriteLine_Error_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Waiting....
/// </summary>
public static string CommandWaitBroker_UpdateProgress_Waiting___ {
get {
return ResourceManager.GetString("CommandWaitBroker_UpdateProgress_Waiting___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Done.
/// </summary>
public static string CommandWaitBroker_Wait_Done {
get {
return ResourceManager.GetString("CommandWaitBroker_Wait_Done", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Comment {
get {
object obj = ResourceManager.GetObject("Comment", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Always.
/// </summary>
public static string CompactFormatOption_ALWAYS_Always {
get {
return ResourceManager.GetString("CompactFormatOption_ALWAYS_Always", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Never.
/// </summary>
public static string CompactFormatOption_NEVER_Never {
get {
return ResourceManager.GetString("CompactFormatOption_NEVER_Never", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only for large files.
/// </summary>
public static string CompactFormatOption_ONLY_FOR_LARGE_FILES_Only_for_large_files {
get {
return ResourceManager.GetString("CompactFormatOption_ONLY_FOR_LARGE_FILES_Only_for_large_files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <Compare...>.
/// </summary>
public static string CompareElement_CompareElement__Compare____ {
get {
return ResourceManager.GetString("CompareElement_CompareElement__Compare____", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Documents have different number of transition groups, {0} vs {1}..
/// </summary>
public static string ComparePeakBoundaries_ComputeMatches_Documents_have_different_number_of_transition_groups___0__vs__1__ {
get {
return ResourceManager.GetString("ComparePeakBoundaries_ComputeMatches_Documents_have_different_number_of_transitio" +
"n_groups___0__vs__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Number of results in transition group {0} does not match between the two documents.
/// </summary>
public static string ComparePeakBoundaries_ComputeMatches_Number_of_results_in_transition_group__0__does_not_match_between_the_two_documents {
get {
return ResourceManager.GetString("ComparePeakBoundaries_ComputeMatches_Number_of_results_in_transition_group__0__do" +
"es_not_match_between_the_two_documents", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing q value for peptide {0} of file {1}.
/// </summary>
public static string ComparePeakBoundaries_GenerateComparison_Missing_q_value_for_peptide__0__of_file__1_ {
get {
return ResourceManager.GetString("ComparePeakBoundaries_GenerateComparison_Missing_q_value_for_peptide__0__of_file_" +
"_1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Model or File:.
/// </summary>
public static string ComparePeakBoundariesList_Label__Model_or_File_ {
get {
return ResourceManager.GetString("ComparePeakBoundariesList_Label__Model_or_File_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Peak Boundary Comparisons.
/// </summary>
public static string ComparePeakBoundariesList_Title_Edit_Peak_Boundary_Comparisons {
get {
return ResourceManager.GetString("ComparePeakBoundariesList_Title_Edit_Peak_Boundary_Comparisons", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Observed FPR:.
/// </summary>
public static string ComparePeakPickingDlg_checkObserved_CheckedChanged_Observed_FPR_ {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_checkObserved_CheckedChanged_Observed_FPR_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Q value cutoff:.
/// </summary>
public static string ComparePeakPickingDlg_checkObserved_CheckedChanged_Q_value_cutoff_ {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_checkObserved_CheckedChanged_Q_value_cutoff_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find the peptide {0} with charge state {1}.
/// </summary>
public static string ComparePeakPickingDlg_ClickGridViewItem_Unable_to_find_the_peptide__0__with_charge_state__1_ {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_ClickGridViewItem_Unable_to_find_the_peptide__0__with_charg" +
"e_state__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fraction of Manual ID's.
/// </summary>
public static string ComparePeakPickingDlg_ComparePeakPickingDlg_Fraction_of_Manual_ID_s {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_ComparePeakPickingDlg_Fraction_of_Manual_ID_s", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fraction of Peak Groups.
/// </summary>
public static string ComparePeakPickingDlg_ComparePeakPickingDlg_Fraction_of_Peak_Groups {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_ComparePeakPickingDlg_Fraction_of_Peak_Groups", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Total Correct Peaks.
/// </summary>
public static string ComparePeakPickingDlg_ComparePeakPickingDlg_Total_Correct_Peaks {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_ComparePeakPickingDlg_Total_Correct_Peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add models/files for comparison to see a q-Q plot.
/// </summary>
public static string ComparePeakPickingDlg_InitializeGraphPanes_Add_models_files_for_comparison_to_see_a_q_Q_plot {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_InitializeGraphPanes_Add_models_files_for_comparison_to_see" +
"_a_q_Q_plot", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add models/files for comparison to see a ROC plot..
/// </summary>
public static string ComparePeakPickingDlg_InitializeGraphPanes_Add_models_files_for_comparison_to_see_a_ROC_plot_ {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_InitializeGraphPanes_Add_models_files_for_comparison_to_see" +
"_a_ROC_plot_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add models/files for comparison to see an analysis of runs.
/// </summary>
public static string ComparePeakPickingDlg_InitializeGraphPanes_Add_models_files_for_comparison_to_see_an_analysis_of_runs {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_InitializeGraphPanes_Add_models_files_for_comparison_to_see" +
"_an_analysis_of_runs", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Expected False Positive Rate.
/// </summary>
public static string ComparePeakPickingDlg_InitializeGraphPanes_Expected_False_Positive_Rate {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_InitializeGraphPanes_Expected_False_Positive_Rate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Observed False Positive Rate.
/// </summary>
public static string ComparePeakPickingDlg_InitializeGraphPanes_Observed_False_Positive_Rate {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_InitializeGraphPanes_Observed_False_Positive_Rate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicate Name.
/// </summary>
public static string ComparePeakPickingDlg_InitializeGraphPanes_Replicate_Name {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_InitializeGraphPanes_Replicate_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Refresh {0}.
/// </summary>
public static string ComparePeakPickingDlg_RefreshDocument_Refresh__0_ {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_RefreshDocument_Refresh__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Save Model Comparison Data.
/// </summary>
public static string ComparePeakPickingDlg_SaveData_Save_Model_Comparison_Data {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_SaveData_Save_Model_Comparison_Data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Either the ROC or Q-q plot tab must be selected to save a graph..
/// </summary>
public static string ComparePeakPickingDlg_SaveGraph_Either_the_ROC_or_Q_q_plot_tab_must_be_selected_to_save_a_graph_ {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_SaveGraph_Either_the_ROC_or_Q_q_plot_tab_must_be_selected_t" +
"o_save_a_graph_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Save Model Comparison Graph.
/// </summary>
public static string ComparePeakPickingDlg_SaveGraph_Save_Model_Comparison_Graph {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_SaveGraph_Save_Model_Comparison_Graph", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} observed false positive rate.
/// </summary>
public static string ComparePeakPickingDlg_UpdateGraph__0__observed_false_positive_rate {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_UpdateGraph__0__observed_false_positive_rate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} significance threshold.
/// </summary>
public static string ComparePeakPickingDlg_UpdateGraph__0__significance_threshold {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_UpdateGraph__0__significance_threshold", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Equality.
/// </summary>
public static string ComparePeakPickingDlg_UpdateGraph_Equality {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_UpdateGraph_Equality", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Q-Q Comparison.
/// </summary>
public static string ComparePeakPickingDlg_UpdateGraph_Q_Q_Comparison {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_UpdateGraph_Q_Q_Comparison", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicate Comparison (Observed FPR < {0}).
/// </summary>
public static string ComparePeakPickingDlg_UpdateGraph_Replicate_Comparison__Observed_FPR____0__ {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_UpdateGraph_Replicate_Comparison__Observed_FPR____0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicate Comparison (q value < {0}).
/// </summary>
public static string ComparePeakPickingDlg_UpdateGraph_Replicate_Comparison__q_value____0__ {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_UpdateGraph_Replicate_Comparison__q_value____0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ROC Plot Comparison.
/// </summary>
public static string ComparePeakPickingDlg_UpdateGraph_ROC_Plot_Comparison {
get {
return ResourceManager.GetString("ComparePeakPickingDlg_UpdateGraph_ROC_Plot_Comparison", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Compensation &Voltage Parameters:.
/// </summary>
public static string CompensationVoltageList_Label_Compensation__Voltage_Parameters_ {
get {
return ResourceManager.GetString("CompensationVoltageList_Label_Compensation__Voltage_Parameters_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Compensation Voltage Parameter Sets.
/// </summary>
public static string CompensationVoltageList_Title_Edit_Compensation_Voltage_Parameter_Sets {
get {
return ResourceManager.GetString("CompensationVoltageList_Title_Edit_Compensation_Voltage_Parameter_Sets", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cancel.
/// </summary>
public static string ConfigureToolsDlg_AddFromFile_Cancel {
get {
return ResourceManager.GetString("ConfigureToolsDlg_AddFromFile_Cancel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must save changes before installing tools. Would you like to save changes?.
/// </summary>
public static string ConfigureToolsDlg_AddFromFile_You_must_save_changes_before_installing_tools__Would_you_like_to_save_changes_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_AddFromFile_You_must_save_changes_before_installing_tools__Woul" +
"d_you_like_to_save_changes_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Zip Files.
/// </summary>
public static string ConfigureToolsDlg_AddFromFile_Zip_Files {
get {
return ResourceManager.GetString("ConfigureToolsDlg_AddFromFile_Zip_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Contacting the server.
/// </summary>
public static string ConfigureToolsDlg_AddFromWeb_Contacting_the_server {
get {
return ResourceManager.GetString("ConfigureToolsDlg_AddFromWeb_Contacting_the_server", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown error connecting to the tool store.
/// </summary>
public static string ConfigureToolsDlg_AddFromWeb_Unknown_error_connecting_to_the_tool_store {
get {
return ResourceManager.GetString("ConfigureToolsDlg_AddFromWeb_Unknown_error_connecting_to_the_tool_store", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All Executables.
/// </summary>
public static string ConfigureToolsDlg_btnFindCommand_Click_All_Executables {
get {
return ResourceManager.GetString("ConfigureToolsDlg_btnFindCommand_Click_All_Executables", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Batch Files.
/// </summary>
public static string ConfigureToolsDlg_btnFindCommand_Click_Batch_Files {
get {
return ResourceManager.GetString("ConfigureToolsDlg_btnFindCommand_Click_Batch_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Command Files.
/// </summary>
public static string ConfigureToolsDlg_btnFindCommand_Click_Command_Files {
get {
return ResourceManager.GetString("ConfigureToolsDlg_btnFindCommand_Click_Command_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Information Files.
/// </summary>
public static string ConfigureToolsDlg_btnFindCommand_Click_Information_Files {
get {
return ResourceManager.GetString("ConfigureToolsDlg_btnFindCommand_Click_Information_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Perl Scripts.
/// </summary>
public static string ConfigureToolsDlg_btnFindCommand_Click_Perl_Scripts {
get {
return ResourceManager.GetString("ConfigureToolsDlg_btnFindCommand_Click_Perl_Scripts", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Python Scripts.
/// </summary>
public static string ConfigureToolsDlg_btnFindCommand_Click_Python_Scripts {
get {
return ResourceManager.GetString("ConfigureToolsDlg_btnFindCommand_Click_Python_Scripts", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you wish to Save changes?.
/// </summary>
public static string ConfigureToolsDlg_Cancel_Do_you_wish_to_Save_changes_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_Cancel_Do_you_wish_to_Save_changes_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Note: if you would like the command to launch a link, make sure to include http:// or https://.
/// </summary>
public static string ConfigureToolsDlg_CheckPassTool__Note__if_you_would_like_the_command_to_launch_a_link__make_sure_to_include_http____or_https___ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassTool__Note__if_you_would_like_the_command_to_launch_a_" +
"link__make_sure_to_include_http____or_https___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The command for {0} may not exist in that location. Would you like to edit it?.
/// </summary>
public static string ConfigureToolsDlg_CheckPassTool__The_command_for__0__may_not_exist_in_that_location__Would_you_like_to_edit_it__ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassTool__The_command_for__0__may_not_exist_in_that_locati" +
"on__Would_you_like_to_edit_it__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to If you would like the command to launch a link, make sure to include http:// or https://.
/// </summary>
public static string ConfigureToolsDlg_CheckPassTool_if_you_would_like_the_command_to_launch_a_link__make_sure_to_include_http____or_https___ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassTool_if_you_would_like_the_command_to_launch_a_link__m" +
"ake_sure_to_include_http____or_https___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Supported Types: {1}.
/// </summary>
public static string ConfigureToolsDlg_CheckPassTool_Supported_Types___1_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassTool_Supported_Types___1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The command cannot be blank. Please enter a valid command for {0}.
/// </summary>
public static string ConfigureToolsDlg_CheckPassTool_The_command_cannot_be_blank__please_enter_a_valid_command_for__0_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassTool_The_command_cannot_be_blank__please_enter_a_valid" +
"_command_for__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The command for {0} must be of a supported type..
/// </summary>
public static string ConfigureToolsDlg_CheckPassTool_The_command_for__0__must_be_of_a_supported_type {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassTool_The_command_for__0__must_be_of_a_supported_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must enter a valid title for the tool..
/// </summary>
public static string ConfigureToolsDlg_CheckPassTool_You_must_enter_a_valid_title_for_the_tool {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassTool_You_must_enter_a_valid_title_for_the_tool", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to $(ToolDir) is not a valid macro for a tool that was not installed and therefore does not have a Tool Directory..
/// </summary>
public static string ConfigureToolsDlg_CheckPassToolInternal_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassToolInternal_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to $(ToolDir) is not a valid macro for a tool that was not installed and therefore does not have a Tool Directory..
/// </summary>
public static string ConfigureToolsDlg_CheckPassToolInternal__ToolDir__is_not_a_valid_macro_for_a_tool_that_was_not_installed_and_therefore_does_not_have_a_Tool_Directory_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassToolInternal__ToolDir__is_not_a_valid_macro_for_a_tool" +
"_that_was_not_installed_and_therefore_does_not_have_a_Tool_Directory_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please select a report or remove {0} from arguments..
/// </summary>
public static string ConfigureToolsDlg_CheckPassToolInternal_Please_select_a_report_or_remove__0__from_arguments_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassToolInternal_Please_select_a_report_or_remove__0__from" +
"_arguments_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please specify a valid URL..
/// </summary>
public static string ConfigureToolsDlg_CheckPassToolInternal_Please_specify_a_valid_URL_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassToolInternal_Please_specify_a_valid_URL_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Tool titles must be unique, please enter a unique title for this tool..
/// </summary>
public static string ConfigureToolsDlg_CheckPassToolInternal_Tool_titles_must_be_unique__please_enter_a_unique_title_for_this_tool_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassToolInternal_Tool_titles_must_be_unique__please_enter_" +
"a_unique_title_for_this_tool_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You have provided {0} as an argument but have not selected a report..
/// </summary>
public static string ConfigureToolsDlg_CheckPassToolInternal_You_have_provided__0__as_an_argument_but_have_not_selected_a_report_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CheckPassToolInternal_You_have_provided__0__as_an_argument_but_" +
"have_not_selected_a_report_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A file named {0} already exists that isn't identical to the one for tool {1}.
/// </summary>
public static string ConfigureToolsDlg_CopyinFile_A_file_named_0_already_exists_that_isn_t_identical_to_the_one_for_tool__1 {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CopyinFile_A_file_named_0_already_exists_that_isn_t_identical_t" +
"o_the_one_for_tool__1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing the file {0}. Tool ({1}) Import Failed.
/// </summary>
public static string ConfigureToolsDlg_CopyinFile_Missing_the_file_0_Tool_1_Import_Failed {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CopyinFile_Missing_the_file_0_Tool_1_Import_Failed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Not importing this tool....
/// </summary>
public static string ConfigureToolsDlg_CopyinFile_Not_importing_this_tool {
get {
return ResourceManager.GetString("ConfigureToolsDlg_CopyinFile_Not_importing_this_tool", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to [New Tool{0}].
/// </summary>
public static string ConfigureToolsDlg_GetTitle__New_Tool_0__ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_GetTitle__New_Tool_0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error connecting to the Tool Store: {0}.
/// </summary>
public static string ConfigureToolsDlg_GetZipFromWeb_Error_connecting_to_the_Tool_Store___0_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_GetZipFromWeb_Error_connecting_to_the_Tool_Store___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An annotation with the following name already exists:.
/// </summary>
public static string ConfigureToolsDlg_OverwriteAnnotations_An_annotation_with_the_following_name_already_exists_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteAnnotations_An_annotation_with_the_following_name_alre" +
"ady_exists_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Annotations with the following names already exist:.
/// </summary>
public static string ConfigureToolsDlg_OverwriteAnnotations_Annotations_with_the_following_names_already_exist_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteAnnotations_Annotations_with_the_following_names_alrea" +
"dy_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to overwrite or keep the existing annotations?.
/// </summary>
public static string ConfigureToolsDlg_OverwriteAnnotations_Do_you_want_to_overwrite_or_keep_the_existing_annotations_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteAnnotations_Do_you_want_to_overwrite_or_keep_the_exist" +
"ing_annotations_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Keep Existing.
/// </summary>
public static string ConfigureToolsDlg_OverwriteAnnotations_Keep_Existing {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteAnnotations_Keep_Existing", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you wish to overwrite or install in parallel?.
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_or_install_in_parallel_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_or_install_in_pa" +
"rallel_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you wish to overwrite with the older version {0} or install in parallel?.
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_with_the_older_version__0__or_install_in_parallel_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_with_the_older_v" +
"ersion__0__or_install_in_parallel_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you wish to reinstall or install in parallel?.
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_reinstall_or_install_in_parallel_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_reinstall_or_install_in_pa" +
"rallel_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you wish to upgrade to {0} or install in parallel?.
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_upgrade_to__0__or_install_in_parallel_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_upgrade_to__0__or_install_" +
"in_parallel_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to In Parallel.
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_In_Parallel {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_In_Parallel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overwrite.
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_Overwrite {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_Overwrite", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reinstall.
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_Reinstall {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_Reinstall", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The tool {0} is already installed..
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_already_installed_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_already_installed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The tool {0} is currently installed..
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_currently_installed_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_currently_installed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The tool {0} is in conflict with the new installation.
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_in_conflict_with_the_new_installation {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_in_conflict_with_the_new_" +
"installation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This installation would modify the following reports.
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_This_installation_would_modify_the_following_reports {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_This_installation_would_modify_the_follow" +
"ing_reports", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This installation would modify the report titled {0}.
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_This_installation_would_modify_the_report_titled__0_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_This_installation_would_modify_the_report" +
"_titled__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This is an older installation v{0} of the tool {1}.
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_This_is_an_older_installation_v_0__of_the_tool__1_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_This_is_an_older_installation_v_0__of_the" +
"_tool__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Upgrade.
/// </summary>
public static string ConfigureToolsDlg_OverwriteOrInParallel_Upgrade {
get {
return ResourceManager.GetString("ConfigureToolsDlg_OverwriteOrInParallel_Upgrade", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Arguments collected at run time.
/// </summary>
public static string ConfigureToolsDlg_PopulateMacroDropdown_Arguments_collected_at_run_time {
get {
return ResourceManager.GetString("ConfigureToolsDlg_PopulateMacroDropdown_Arguments_collected_at_run_time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File path to a temporary report.
/// </summary>
public static string ConfigureToolsDlg_PopulateMacroDropdown_File_path_to_a_temporary_report {
get {
return ResourceManager.GetString("ConfigureToolsDlg_PopulateMacroDropdown_File_path_to_a_temporary_report", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to N/A.
/// </summary>
public static string ConfigureToolsDlg_PopulateMacroDropdown_N_A {
get {
return ResourceManager.GetString("ConfigureToolsDlg_PopulateMacroDropdown_N_A", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Command:.
/// </summary>
public static string ConfigureToolsDlg_textCommand_TextChanged__Command_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_textCommand_TextChanged__Command_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Query params:.
/// </summary>
public static string ConfigureToolsDlg_textCommand_TextChanged__Query_params_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_textCommand_TextChanged__Query_params_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A&rguments:.
/// </summary>
public static string ConfigureToolsDlg_textCommand_TextChanged_A_rguments_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_textCommand_TextChanged_A_rguments_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to U&RL:.
/// </summary>
public static string ConfigureToolsDlg_textCommand_TextChanged_U_RL_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_textCommand_TextChanged_U_RL_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to continue?.
/// </summary>
public static string ConfigureToolsDlg_UnpackZipTool_Do_you_want_to_continue_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_UnpackZipTool_Do_you_want_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error deleting the directory of the existing tool. Please close anything using that directory and try the overwriting import again later.
/// </summary>
public static string ConfigureToolsDlg_UnpackZipTool_Error_deleting_the_directory_of_the_existing_tool__Please_close_anything_using_that_directory_and_try_the_overwriting_import_again_later {
get {
return ResourceManager.GetString("ConfigureToolsDlg_UnpackZipTool_Error_deleting_the_directory_of_the_existing_tool" +
"__Please_close_anything_using_that_directory_and_try_the_overwriting_import_agai" +
"n_later", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error unpacking zipped tools.
/// </summary>
public static string ConfigureToolsDlg_unpackZipTool_Error_unpacking_zipped_tools {
get {
return ResourceManager.GetString("ConfigureToolsDlg_unpackZipTool_Error_unpacking_zipped_tools", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed attempting to extract the tool from {0}.
/// </summary>
public static string ConfigureToolsDlg_UnpackZipTool_Failed_attempting_to_extract_the_tool_from__0_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_UnpackZipTool_Failed_attempting_to_extract_the_tool_from__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to process file {0}. The tool described failed to import..
/// </summary>
public static string ConfigureToolsDlg_unpackZipTool_Failed_to_process_file_0_The_tool_described_failed_to_import {
get {
return ResourceManager.GetString("ConfigureToolsDlg_unpackZipTool_Failed_to_process_file_0_The_tool_described_faile" +
"d_to_import", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to read file {0}. The tool described failed to import..
/// </summary>
public static string ConfigureToolsDlg_unpackZipTool_Failed_to_read_file_0_The_tool_described_failed_to_import {
get {
return ResourceManager.GetString("ConfigureToolsDlg_unpackZipTool_Failed_to_read_file_0_The_tool_described_failed_t" +
"o_import", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to In Parallel.
/// </summary>
public static string ConfigureToolsDlg_UnpackZipTool_In_Parallel {
get {
return ResourceManager.GetString("ConfigureToolsDlg_UnpackZipTool_In_Parallel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid file selected. No tools added..
/// </summary>
public static string ConfigureToolsDlg_unpackZipTool_Invalid_file_selected__No_tools_added_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_unpackZipTool_Invalid_file_selected__No_tools_added_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid Tool Description in file {0}..
/// </summary>
public static string ConfigureToolsDlg_unpackZipTool_Invalid_Tool_Description_in_file__0__ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_unpackZipTool_Invalid_Tool_Description_in_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overwrite.
/// </summary>
public static string ConfigureToolsDlg_UnpackZipTool_Overwrite {
get {
return ResourceManager.GetString("ConfigureToolsDlg_UnpackZipTool_Overwrite", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to skipping that tool..
/// </summary>
public static string ConfigureToolsDlg_unpackZipTool_skipping_that_tool_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_unpackZipTool_skipping_that_tool_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is a naming conflict. You already installed a tool from a zip folder with the name {0}. Would you like to overwrite or install in parallel?.
/// </summary>
public static string ConfigureToolsDlg_UnpackZipTool_There_is_a_naming_conflict__You_already_installed_a_tool_from_a_zip_folder_with_the_name__0___Would_you_like_to_overwrite_or_install_in_parallel_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_UnpackZipTool_There_is_a_naming_conflict__You_already_installed" +
"_a_tool_from_a_zip_folder_with_the_name__0___Would_you_like_to_overwrite_or_inst" +
"all_in_parallel_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is a naming conflict in unpacking the zip. Tool importing canceled!.
/// </summary>
public static string ConfigureToolsDlg_unpackZipTool_There_is_a_naming_conflict_in_unpacking_the_zip__Tool_importing_canceled_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_unpackZipTool_There_is_a_naming_conflict_in_unpacking_the_zip__" +
"Tool_importing_canceled_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Title and Command are required.
/// </summary>
public static string ConfigureToolsDlg_unpackZipTool_Title_and_Command_are_required {
get {
return ResourceManager.GetString("ConfigureToolsDlg_unpackZipTool_Title_and_Command_are_required", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning, overwriting will delete the following tools:.
/// </summary>
public static string ConfigureToolsDlg_UnpackZipTool_Warning__overwriting_will_delete_the_following_tools_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_UnpackZipTool_Warning__overwriting_will_delete_the_following_to" +
"ols_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Warning, overwriting will delete the tool {0}. Do you want to continue?.
/// </summary>
public static string ConfigureToolsDlg_UnpackZipTool_Warning__overwriting_will_delete_the_tool__0___Do_you_want_to_continue_ {
get {
return ResourceManager.GetString("ConfigureToolsDlg_UnpackZipTool_Warning__overwriting_will_delete_the_tool__0___Do" +
"_you_want_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Copy {
get {
object obj = ResourceManager.GetObject("Copy", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Copy_Bitmap {
get {
object obj = ResourceManager.GetObject("Copy_Bitmap", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Copy.
/// </summary>
public static string CopyEmfToolStripMenuItem_AddToContextMenu_Copy {
get {
return ResourceManager.GetString("CopyEmfToolStripMenuItem_AddToContextMenu_Copy", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Metafile image copied to clipboard.
/// </summary>
public static string CopyEmfToolStripMenuItem_CopyEmf_Metafile_image_copied_to_clipboard {
get {
return ResourceManager.GetString("CopyEmfToolStripMenuItem_CopyEmf_Metafile_image_copied_to_clipboard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to copy metafile image to the clipboard..
/// </summary>
public static string CopyEmfToolStripMenuItem_CopyEmf_Unable_to_copy_metafile_image_to_the_clipboard {
get {
return ResourceManager.GetString("CopyEmfToolStripMenuItem_CopyEmf_Unable_to_copy_metafile_image_to_the_clipboard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copy Metafile.
/// </summary>
public static string CopyEmfToolStripMenuItem_CopyEmfToolStripMenuItem_Copy_Metafile {
get {
return ResourceManager.GetString("CopyEmfToolStripMenuItem_CopyEmfToolStripMenuItem_Copy_Metafile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed setting data to clipboard..
/// </summary>
public static string CopyGraphDataToolStripMenuItem_CopyGraphData_Failed_setting_data_to_clipboard {
get {
return ResourceManager.GetString("CopyGraphDataToolStripMenuItem_CopyGraphData_Failed_setting_data_to_clipboard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copy Data.
/// </summary>
public static string CopyGraphDataToolStripMenuItem_CopyGraphDataToolStripMenuItem_Copy_Data {
get {
return ResourceManager.GetString("CopyGraphDataToolStripMenuItem_CopyGraphDataToolStripMenuItem_Copy_Data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not read the pasted transition list. Transition list must be in separated columns and cannot contain blank lines..
/// </summary>
public static string CopyPasteTest_DoTest_Could_not_read_the_pasted_transition_list___Transition_list_must_be_in_separated_columns_and_cannot_contain_blank_lines_ {
get {
return ResourceManager.GetString("CopyPasteTest_DoTest_Could_not_read_the_pasted_transition_list___Transition_list_" +
"must_be_in_separated_columns_and_cannot_contain_blank_lines_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not open web Browser to show link:.
/// </summary>
public static string Could_not_open_web_Browser_to_show_link_ {
get {
return ResourceManager.GetString("Could_not_open_web_Browser_to_show_link_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The specified file is not a valid iRT database..
/// </summary>
public static string CreateIrtCalculatorDlg_BrowseDb_The_specified_file_is_not_a_valid_iRT_database_ {
get {
return ResourceManager.GetString("CreateIrtCalculatorDlg_BrowseDb_The_specified_file_is_not_a_valid_iRT_database_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Transition List (iRT standards).
/// </summary>
public static string CreateIrtCalculatorDlg_ImportTextFile_Import_Transition_List__iRT_standards_ {
get {
return ResourceManager.GetString("CreateIrtCalculatorDlg_ImportTextFile_Import_Transition_List__iRT_standards_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A calculator with that name already exists. Do you want to replace it?.
/// </summary>
public static string CreateIrtCalculatorDlg_OkDialog_A_calculator_with_that_name_already_exists___Do_you_want_to_replace_it_ {
get {
return ResourceManager.GetString("CreateIrtCalculatorDlg_OkDialog_A_calculator_with_that_name_already_exists___Do_y" +
"ou_want_to_replace_it_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculator name cannot be empty..
/// </summary>
public static string CreateIrtCalculatorDlg_OkDialog_Calculator_name_cannot_be_empty {
get {
return ResourceManager.GetString("CreateIrtCalculatorDlg_OkDialog_Calculator_name_cannot_be_empty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot read the database file {0}..
/// </summary>
public static string CreateIrtCalculatorDlg_OkDialog_Cannot_read_the_database_file__0_ {
get {
return ResourceManager.GetString("CreateIrtCalculatorDlg_OkDialog_Cannot_read_the_database_file__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error reading iRT standards transition list: {0}.
/// </summary>
public static string CreateIrtCalculatorDlg_OkDialog_Error_reading_iRT_standards_transition_list___0_ {
get {
return ResourceManager.GetString("CreateIrtCalculatorDlg_OkDialog_Error_reading_iRT_standards_transition_list___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to open the database file: {0}.
/// </summary>
public static string CreateIrtCalculatorDlg_OkDialog_Failed_to_open_the_database_file___0_ {
get {
return ResourceManager.GetString("CreateIrtCalculatorDlg_OkDialog_Failed_to_open_the_database_file___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT database field must contain a path to a valid file..
/// </summary>
public static string CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_contain_a_path_to_a_valid_file_ {
get {
return ResourceManager.GetString("CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_contain_a_path_to_a_valid" +
"_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT database field must not be empty..
/// </summary>
public static string CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_not_be_empty_ {
get {
return ResourceManager.GetString("CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_not_be_empty_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please select a protein containing the list of standard peptides for the iRT calculator..
/// </summary>
public static string CreateIrtCalculatorDlg_OkDialog_Please_select_a_protein_containing_the_list_of_standard_peptides_for_the_iRT_calculator_ {
get {
return ResourceManager.GetString("CreateIrtCalculatorDlg_OkDialog_Please_select_a_protein_containing_the_list_of_st" +
"andard_peptides_for_the_iRT_calculator_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition list field must contain a path to a valid file..
/// </summary>
public static string CreateIrtCalculatorDlg_OkDialog_Transition_list_field_must_contain_a_path_to_a_valid_file_ {
get {
return ResourceManager.GetString("CreateIrtCalculatorDlg_OkDialog_Transition_list_field_must_contain_a_path_to_a_va" +
"lid_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Expected '{0}'.
/// </summary>
public static string CrosslinkSequenceParser_Expected_Expected___0__ {
get {
return ResourceManager.GetString("CrosslinkSequenceParser_Expected_Expected___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to parse '{0}' as a number.
/// </summary>
public static string CrosslinkSequenceParser_ParseCrosslink_Unable_to_parse___0___as_a_number {
get {
return ResourceManager.GetString("CrosslinkSequenceParser_ParseCrosslink_Unable_to_parse___0___as_a_number", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid peptide sequence.
/// </summary>
public static string CrosslinkSequenceParser_ParseCrosslinkLibraryKey_Invalid_peptide_sequence {
get {
return ResourceManager.GetString("CrosslinkSequenceParser_ParseCrosslinkLibraryKey_Invalid_peptide_sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ion.
/// </summary>
public static string CustomIon_DisplayName_Ion {
get {
return ResourceManager.GetString("CustomIon_DisplayName_Ion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule.
/// </summary>
public static string CustomMolecule_DisplayName_Molecule {
get {
return ResourceManager.GetString("CustomMolecule_DisplayName_Molecule", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Custom molecules must specify a formula or valid monoisotopic and average masses..
/// </summary>
public static string CustomMolecule_Validate_Custom_molecules_must_specify_a_formula_or_valid_monoisotopic_and_average_masses_ {
get {
return ResourceManager.GetString("CustomMolecule_Validate_Custom_molecules_must_specify_a_formula_or_valid_monoisot" +
"opic_and_average_masses_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The mass {0} of the custom molecule exceeds the maximum of {1}..
/// </summary>
public static string CustomMolecule_Validate_The_mass__0__of_the_custom_molecule_exceeeds_the_maximum_of__1__ {
get {
return ResourceManager.GetString("CustomMolecule_Validate_The_mass__0__of_the_custom_molecule_exceeeds_the_maximum_" +
"of__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The mass {0} of the custom molecule is less than the minimum of {1}..
/// </summary>
public static string CustomMolecule_Validate_The_mass__0__of_the_custom_molecule_is_less_than_the_minimum_of__1__ {
get {
return ResourceManager.GetString("CustomMolecule_Validate_The_mass__0__of_the_custom_molecule_is_less_than_the_mini" +
"mum_of__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Cut {
get {
object obj = ResourceManager.GetObject("Cut", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Dash {
get {
object obj = ResourceManager.GetObject("Dash", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to {0} points.
/// </summary>
public static string Data_ToString__0__points {
get {
return ResourceManager.GetString("Data_ToString__0__points", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The type {0} must have a column of type {1}.
/// </summary>
public static string Database_GetJoinColumn_The_type__0__must_have_a_column_of_type__1_ {
get {
return ResourceManager.GetString("Database_GetJoinColumn_The_type__0__must_have_a_column_of_type__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot join tables of same type..
/// </summary>
public static string Database_Join_Cannot_join_tables_of_same_type {
get {
return ResourceManager.GetString("Database_Join_Cannot_join_tables_of_same_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The database for the calculator {0} could not be opened. Check that the file {1} was not moved or deleted..
/// </summary>
public static string DatabaseNotConnectedException_DatabaseNotConnectedException_The_database_for_the_calculator__0__could_not_be_opened__Check_that_the_file__1__was_not_moved_or_deleted {
get {
return ResourceManager.GetString("DatabaseNotConnectedException_DatabaseNotConnectedException_The_database_for_the_" +
"calculator__0__could_not_be_opened__Check_that_the_file__1__was_not_moved_or_del" +
"eted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Disconnected.
/// </summary>
public static string DataboundGraph_AttachToOwner_Disconnected {
get {
return ResourceManager.GetString("DataboundGraph_AttachToOwner_Disconnected", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Waiting for data.
/// </summary>
public static string DataboundGraph_AttachToOwner_Waiting_for_data {
get {
return ResourceManager.GetString("DataboundGraph_AttachToOwner_Waiting_for_data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Heat Map.
/// </summary>
public static string DataboundGridControl_DataboundGridControl_Show_Heat_Map {
get {
return ResourceManager.GetString("DataboundGridControl_DataboundGridControl_Show_Heat_Map", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show PCA Plot.
/// </summary>
public static string DataboundGridControl_DataboundGridControl_Show_PCA_Plot {
get {
return ResourceManager.GetString("DataboundGridControl_DataboundGridControl_Show_PCA_Plot", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occured while displaying the data rows:.
/// </summary>
public static string DataboundGridControl_DisplayError_An_error_occured_while_displaying_the_data_rows_ {
get {
return ResourceManager.GetString("DataboundGridControl_DisplayError_An_error_occured_while_displaying_the_data_rows" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to continue to see these error messages?.
/// </summary>
public static string DataboundGridControl_DisplayError_Do_you_want_to_continue_to_see_these_error_messages_ {
get {
return ResourceManager.GetString("DataboundGridControl_DisplayError_Do_you_want_to_continue_to_see_these_error_mess" +
"ages_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error setting value:.
/// </summary>
public static string DataboundGridControl_DoFillDown_Error_setting_value_ {
get {
return ResourceManager.GetString("DataboundGridControl_DoFillDown_Error_setting_value_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Filling {0}/{1} rows.
/// </summary>
public static string DataboundGridControl_DoFillDown_Filling__0___1__rows {
get {
return ResourceManager.GetString("DataboundGridControl_DoFillDown_Filling__0___1__rows", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fill Down.
/// </summary>
public static string DataboundGridControl_FillDown_Fill_Down {
get {
return ResourceManager.GetString("DataboundGridControl_FillDown_Fill_Down", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occured while performing clustering..
/// </summary>
public static string DataboundGridControl_GetClusteredResults_An_error_occured_while_performing_clustering_ {
get {
return ResourceManager.GetString("DataboundGridControl_GetClusteredResults_An_error_occured_while_performing_cluste" +
"ring_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to choose a set of columns to use for hierarchical clustering..
/// </summary>
public static string DataboundGridControl_GetClusteredResults_Unable_to_choose_a_set_of_columns_to_use_for_hierarchical_clustering_ {
get {
return ResourceManager.GetString("DataboundGridControl_GetClusteredResults_Unable_to_choose_a_set_of_columns_to_use" +
"_for_hierarchical_clustering_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Audit Log.
/// </summary>
public static string DataGridType_AUDIT_LOG_Audit_Log {
get {
return ResourceManager.GetString("DataGridType_AUDIT_LOG_Audit_Log", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document Grid.
/// </summary>
public static string DataGridType_DOCUMENT_GRID_Document_Grid {
get {
return ResourceManager.GetString("DataGridType_DOCUMENT_GRID_Document_Grid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Group Comparison.
/// </summary>
public static string DataGridType_GROUP_COMPARISON_Group_Comparison {
get {
return ResourceManager.GetString("DataGridType_GROUP_COMPARISON_Group_Comparison", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to List.
/// </summary>
public static string DataGridType_LIST_List {
get {
return ResourceManager.GetString("DataGridType_LIST_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results Grid.
/// </summary>
public static string DataGridType_RESULTS_GRID_Results_Grid {
get {
return ResourceManager.GetString("DataGridType_RESULTS_GRID_Results_Grid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cleared {0}/{1} rows.
/// </summary>
public static string DataGridViewPasteHandler_ClearCells_Cleared__0___1__rows {
get {
return ResourceManager.GetString("DataGridViewPasteHandler_ClearCells_Cleared__0___1__rows", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Clear cells.
/// </summary>
public static string DataGridViewPasteHandler_DataGridViewOnKeyDown_Clear_cells {
get {
return ResourceManager.GetString("DataGridViewPasteHandler_DataGridViewOnKeyDown_Clear_cells", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Paste.
/// </summary>
public static string DataGridViewPasteHandler_DataGridViewOnKeyDown_Paste {
get {
return ResourceManager.GetString("DataGridViewPasteHandler_DataGridViewOnKeyDown_Paste", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Updating document settings to match edits..
/// </summary>
public static string DataGridViewPasteHandler_EndDeferSettingsChangesOnDocument_Updating_settings {
get {
return ResourceManager.GetString("DataGridViewPasteHandler_EndDeferSettingsChangesOnDocument_Updating_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Pasting row {0}.
/// </summary>
public static string DataGridViewPasteHandler_Paste_Pasting_row__0_ {
get {
return ResourceManager.GetString("DataGridViewPasteHandler_Paste_Pasting_row__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error converting '{0}' to required type: {1}.
/// </summary>
public static string DataGridViewPasteHandler_TryConvertValue_Error_converting___0___to_required_type___1_ {
get {
return ResourceManager.GetString("DataGridViewPasteHandler_TryConvertValue_Error_converting___0___to_required_type_" +
"__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap DataProcessing {
get {
object obj = ResourceManager.GetObject("DataProcessing", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to The URI {0} is not well formed..
/// </summary>
public static string DataSettings_ChangePanoramaPublishUri_The_URI__0__is_not_well_formed_ {
get {
return ResourceManager.GetString("DataSettings_ChangePanoramaPublishUri_The_URI__0__is_not_well_formed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to read sample information from the file {0}..
/// </summary>
public static string DataSourceUtil_GetWiffSubPaths_An_error_occurred_attempting_to_read_sample_information_from_the_file__0__ {
get {
return ResourceManager.GetString("DataSourceUtil_GetWiffSubPaths_An_error_occurred_attempting_to_read_sample_inform" +
"ation_from_the_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file may be corrupted, missing, or the correct libraries may not be installed..
/// </summary>
public static string DataSourceUtil_GetWiffSubPaths_The_file_may_be_corrupted_missing_or_the_correct_libraries_may_not_be_installed {
get {
return ResourceManager.GetString("DataSourceUtil_GetWiffSubPaths_The_file_may_be_corrupted_missing_or_the_correct_l" +
"ibraries_may_not_be_installed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding iRT values for imported peptides.
/// </summary>
public static string DbIrtPeptide_FindNonConflicts_Adding_iRT_values_for_imported_peptides {
get {
return ResourceManager.GetString("DbIrtPeptide_FindNonConflicts_Adding_iRT_values_for_imported_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Optimization type out of range.
/// </summary>
public static string DbOptimization_DbOptimization_Optimization_type_out_of_range {
get {
return ResourceManager.GetString("DbOptimization_DbOptimization_Optimization_type_out_of_range", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enzymes file {0} not found.
/// </summary>
public static string DdaSearch_MSAmandaSearchWrapper_enzymes_file__0__not_found {
get {
return ResourceManager.GetString("DdaSearch_MSAmandaSearchWrapper_enzymes_file__0__not_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Instruments file {0} not found.
/// </summary>
public static string DdaSearch_MSAmandaSearchWrapper_Instruments_file_not_found {
get {
return ResourceManager.GetString("DdaSearch_MSAmandaSearchWrapper_Instruments_file_not_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Obo files (psi-ms.obo and unimod.obo) not found.
/// </summary>
public static string DdaSearch_MSAmandaSearchWrapper_Obo_files_not_found {
get {
return ResourceManager.GetString("DdaSearch_MSAmandaSearchWrapper_Obo_files_not_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unimod file {0} not found.
/// </summary>
public static string DdaSearch_MSAmandaSearchWrapper_unimod_file__0__not_found {
get {
return ResourceManager.GetString("DdaSearch_MSAmandaSearchWrapper_unimod_file__0__not_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Search failed: {0}.
/// </summary>
public static string DdaSearch_Search_failed__0 {
get {
return ResourceManager.GetString("DdaSearch_Search_failed__0", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Search is being canceled..
/// </summary>
public static string DdaSearch_Search_is_canceled {
get {
return ResourceManager.GetString("DdaSearch_Search_is_canceled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fragment ions must be selected.
/// </summary>
public static string DdaSearch_SearchSettingsControl_Fragment_ions_must_be_selected {
get {
return ResourceManager.GetString("DdaSearch_SearchSettingsControl_Fragment_ions_must_be_selected", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to MS1 Tolerance incorrect.
/// </summary>
public static string DdaSearch_SearchSettingsControl_MS1_Tolerance_incorrect {
get {
return ResourceManager.GetString("DdaSearch_SearchSettingsControl_MS1_Tolerance_incorrect", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to MS2 Tolerance incorrect.
/// </summary>
public static string DdaSearch_SearchSettingsControl_MS2_Tolerance_incorrect {
get {
return ResourceManager.GetString("DdaSearch_SearchSettingsControl_MS2_Tolerance_incorrect", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Conversion cancelled..
/// </summary>
public static string DDASearchControl_RunSearch_Conversion_cancelled_ {
get {
return ResourceManager.GetString("DDASearchControl_RunSearch_Conversion_cancelled_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Conversion failed..
/// </summary>
public static string DDASearchControl_RunSearch_Conversion_failed_ {
get {
return ResourceManager.GetString("DDASearchControl_RunSearch_Conversion_failed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Conversion finished..
/// </summary>
public static string DDASearchControl_RunSearch_Conversion_finished_ {
get {
return ResourceManager.GetString("DDASearchControl_RunSearch_Conversion_finished_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Search canceled..
/// </summary>
public static string DDASearchControl_SearchProgress_Search_canceled {
get {
return ResourceManager.GetString("DDASearchControl_SearchProgress_Search_canceled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Search done..
/// </summary>
public static string DDASearchControl_SearchProgress_Search_done {
get {
return ResourceManager.GetString("DDASearchControl_SearchProgress_Search_done", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Search failed..
/// </summary>
public static string DDASearchControl_SearchProgress_Search_failed {
get {
return ResourceManager.GetString("DDASearchControl_SearchProgress_Search_failed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Starting search....
/// </summary>
public static string DDASearchControl_SearchProgress_Starting_search {
get {
return ResourceManager.GetString("DDASearchControl_SearchProgress_Starting_search", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Declustering Potential Regressions:.
/// </summary>
public static string DeclusterPotentialList_Label_Declustering_Potential_Regressions {
get {
return ResourceManager.GetString("DeclusterPotentialList_Label_Declustering_Potential_Regressions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Declustering Potential Regressions.
/// </summary>
public static string DeclusterPotentialList_Title_Edit_Declustering_Potential_Regressions {
get {
return ResourceManager.GetString("DeclusterPotentialList_Title_Edit_Declustering_Potential_Regressions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fast Overlap (Experimental).
/// </summary>
public static string DeconvolutionMethod_FAST_OVERLAP_Fast_Overlap {
get {
return ResourceManager.GetString("DeconvolutionMethod_FAST_OVERLAP_Fast_Overlap", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overlap and MSX.
/// </summary>
public static string DeconvolutionMethod_MSX_OVERLAP_Overlap_and_MSX {
get {
return ResourceManager.GetString("DeconvolutionMethod_MSX_OVERLAP_Overlap_and_MSX", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Random Mass Shift.
/// </summary>
public static string DecoyGeneration_ADD_RANDOM_Random_Mass_Shift {
get {
return ResourceManager.GetString("DecoyGeneration_ADD_RANDOM_Random_Mass_Shift", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reverse Sequence.
/// </summary>
public static string DecoyGeneration_REVERSE_SEQUENCE_Reverse_Sequence {
get {
return ResourceManager.GetString("DecoyGeneration_REVERSE_SEQUENCE_Reverse_Sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shuffle Sequence.
/// </summary>
public static string DecoyGeneration_SHUFFLE_SEQUENCE_Shuffle_Sequence {
get {
return ResourceManager.GetString("DecoyGeneration_SHUFFLE_SEQUENCE_Shuffle_Sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Choose a type for this annotation to apply to..
/// </summary>
public static string DefineAnnotationDlg_OkDialog_Choose_a_type_for_this_annotation_to_apply_to_ {
get {
return ResourceManager.GetString("DefineAnnotationDlg_OkDialog_Choose_a_type_for_this_annotation_to_apply_to_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Choose a value for this annotation..
/// </summary>
public static string DefineAnnotationDlg_OkDialog_Choose_a_value_for_this_annotation_ {
get {
return ResourceManager.GetString("DefineAnnotationDlg_OkDialog_Choose_a_value_for_this_annotation_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Choose at least one type for this annotation to apply to..
/// </summary>
public static string DefineAnnotationDlg_OkDialog_Choose_at_least_one_type_for_this_annotation_to_apply_to {
get {
return ResourceManager.GetString("DefineAnnotationDlg_OkDialog_Choose_at_least_one_type_for_this_annotation_to_appl" +
"y_to", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is already an annotation defined named '{0}'..
/// </summary>
public static string DefineAnnotationDlg_OkDialog_There_is_already_an_annotation_defined_named__0__ {
get {
return ResourceManager.GetString("DefineAnnotationDlg_OkDialog_There_is_already_an_annotation_defined_named__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Delete {
get {
object obj = ResourceManager.GetObject("Delete", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Delete Molecules....
/// </summary>
public static string DeletePeptides_GetMenuItemText_Delete_Molecules___ {
get {
return ResourceManager.GetString("DeletePeptides_GetMenuItemText_Delete_Molecules___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Delete Peptides....
/// </summary>
public static string DeletePeptides_MenuItemText_Delete_Peptides___ {
get {
return ResourceManager.GetString("DeletePeptides_MenuItemText_Delete_Peptides___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Delete Precursors....
/// </summary>
public static string DeletePrecursors_MenuItemText_Delete_Precursors___ {
get {
return ResourceManager.GetString("DeletePrecursors_MenuItemText_Delete_Precursors___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Delete Molecule Lists....
/// </summary>
public static string DeleteProteins_MenuItemText_Delete_Molecule_Lists___ {
get {
return ResourceManager.GetString("DeleteProteins_MenuItemText_Delete_Molecule_Lists___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Delete Proteins....
/// </summary>
public static string DeleteProteins_MenuItemText_Delete_Proteins___ {
get {
return ResourceManager.GetString("DeleteProteins_MenuItemText_Delete_Proteins___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Delete Transitions....
/// </summary>
public static string DeleteTransitions_MenuItemText_Delete_Transitions___ {
get {
return ResourceManager.GetString("DeleteTransitions_MenuItemText_Delete_Transitions___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The Isolation Scheme in Full Scan Settings is Inconsistently Specified..
/// </summary>
public static string Demultiplexer_GetDeconvRegionsForMz_TheIsolationSchemeIsInconsistentlySpecified {
get {
return ResourceManager.GetString("Demultiplexer_GetDeconvRegionsForMz_TheIsolationSchemeIsInconsistentlySpecified", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Count.
/// </summary>
public static string DetectionHistogramPane_Tooltip_Count {
get {
return ResourceManager.GetString("DetectionHistogramPane_Tooltip_Count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicate Count.
/// </summary>
public static string DetectionHistogramPane_Tooltip_ReplicateCount {
get {
return ResourceManager.GetString("DetectionHistogramPane_Tooltip_ReplicateCount", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicate Count.
/// </summary>
public static string DetectionHistogramPane_XAxis_Name {
get {
return ResourceManager.GetString("DetectionHistogramPane_XAxis_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Frequency.
/// </summary>
public static string DetectionHistogramPane_YAxis_Name {
get {
return ResourceManager.GetString("DetectionHistogramPane_YAxis_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide.
/// </summary>
public static string DetectionPlot_TargetType_Peptide {
get {
return ResourceManager.GetString("DetectionPlot_TargetType_Peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor.
/// </summary>
public static string DetectionPlot_TargetType_Precursor {
get {
return ResourceManager.GetString("DetectionPlot_TargetType_Precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Count.
/// </summary>
public static string DetectionPlot_YScale_One {
get {
return ResourceManager.GetString("DetectionPlot_YScale_One", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to % of all {0}s.
/// </summary>
public static string DetectionPlot_YScale_Percent {
get {
return ResourceManager.GetString("DetectionPlot_YScale_Percent", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to "Data retrieved successfully.".
/// </summary>
public static string DetectionPlotData_DataRetrieved_Label {
get {
return ResourceManager.GetString("DetectionPlotData_DataRetrieved_Label", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid Q-Value. Cannot be 0 or 1..
/// </summary>
public static string DetectionPlotData_InvalidQValue_Label {
get {
return ResourceManager.GetString("DetectionPlotData_InvalidQValue_Label", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No data loaded..
/// </summary>
public static string DetectionPlotData_NoDataLoaded_Label {
get {
return ResourceManager.GetString("DetectionPlotData_NoDataLoaded_Label", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document has no Q-Values. Train your mProphet model..
/// </summary>
public static string DetectionPlotData_NoQValuesInDocument_Label {
get {
return ResourceManager.GetString("DetectionPlotData_NoQValuesInDocument_Label", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document has no peptides or chromatograms..
/// </summary>
public static string DetectionPlotData_NoResults_Label {
get {
return ResourceManager.GetString("DetectionPlotData_NoResults_Label", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use properties dialog or modify the document to update the plot..
/// </summary>
public static string DetectionPlotData_UsePropertiesDialog_Label {
get {
return ResourceManager.GetString("DetectionPlotData_UsePropertiesDialog_Label", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to "Waiting for the document to load.".
/// </summary>
public static string DetectionPlotData_WaitingForDocumentLoad_Label {
get {
return ResourceManager.GetString("DetectionPlotData_WaitingForDocumentLoad_Label", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to all runs.
/// </summary>
public static string DetectionPlotPane_AllRunsLine_Name {
get {
return ResourceManager.GetString("DetectionPlotPane_AllRunsLine_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to at least {0} (of {1}) - {2:#,##0}.
/// </summary>
public static string DetectionPlotPane_AtLeastLine_Name {
get {
return ResourceManager.GetString("DetectionPlotPane_AtLeastLine_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to cumulative.
/// </summary>
public static string DetectionPlotPane_CumulativeLine_Name {
get {
return ResourceManager.GetString("DetectionPlotPane_CumulativeLine_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No data available for this plot..
/// </summary>
public static string DetectionPlotPane_EmptyPlot_Label {
get {
return ResourceManager.GetString("DetectionPlotPane_EmptyPlot_Label", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Operation canceled..
/// </summary>
public static string DetectionPlotPane_EmptyPlotCanceled_Label {
get {
return ResourceManager.GetString("DetectionPlotPane_EmptyPlotCanceled_Label", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error when retrieving plot data..
/// </summary>
public static string DetectionPlotPane_EmptyPlotError_Label {
get {
return ResourceManager.GetString("DetectionPlotPane_EmptyPlotError_Label", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mean: {0:#,##0}.
/// </summary>
public static string DetectionPlotPane_Label_Mean {
get {
return ResourceManager.GetString("DetectionPlotPane_Label_Mean", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Stddev:{1:#,##0}.
/// </summary>
public static string DetectionPlotPane_Label_Stddev {
get {
return ResourceManager.GetString("DetectionPlotPane_Label_Stddev", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All Count.
/// </summary>
public static string DetectionPlotPane_Tooltip_AllCount {
get {
return ResourceManager.GetString("DetectionPlotPane_Tooltip_AllCount", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Count.
/// </summary>
public static string DetectionPlotPane_Tooltip_Count {
get {
return ResourceManager.GetString("DetectionPlotPane_Tooltip_Count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cumulative Count.
/// </summary>
public static string DetectionPlotPane_Tooltip_CumulativeCount {
get {
return ResourceManager.GetString("DetectionPlotPane_Tooltip_CumulativeCount", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to -log10 of Q-Value Median.
/// </summary>
public static string DetectionPlotPane_Tooltip_QMedian {
get {
return ResourceManager.GetString("DetectionPlotPane_Tooltip_QMedian", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicate.
/// </summary>
public static string DetectionPlotPane_Tooltip_Replicate {
get {
return ResourceManager.GetString("DetectionPlotPane_Tooltip_Replicate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculating (Esc to cancel)....
/// </summary>
public static string DetectionPlotPane_WaitingForData_Label {
get {
return ResourceManager.GetString("DetectionPlotPane_WaitingForData_Label", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicate.
/// </summary>
public static string DetectionPlotPane_XAxis_Name {
get {
return ResourceManager.GetString("DetectionPlotPane_XAxis_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Detections ({0}).
/// </summary>
public static string DetectionPlotPane_YAxis_Name {
get {
return ResourceManager.GetString("DetectionPlotPane_YAxis_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to At least {0} replicates.
/// </summary>
public static string DetectionToolbarProperties_AtLeastNReplicates {
get {
return ResourceManager.GetString("DetectionToolbarProperties_AtLeastNReplicates", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Extraction Windows.
/// </summary>
public static string DiaIsolationWindowsGraphForm_checkBox1_CheckedChanged_Extraction_Windows {
get {
return ResourceManager.GetString("DiaIsolationWindowsGraphForm_checkBox1_CheckedChanged_Extraction_Windows", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cycle.
/// </summary>
public static string DiaIsolationWindowsGraphForm_DiaIsolationWindowsGraphForm_Cycle {
get {
return ResourceManager.GetString("DiaIsolationWindowsGraphForm_DiaIsolationWindowsGraphForm_Cycle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to m/z.
/// </summary>
public static string DiaIsolationWindowsGraphForm_DiaIsolationWindowsGraphForm_m_z {
get {
return ResourceManager.GetString("DiaIsolationWindowsGraphForm_DiaIsolationWindowsGraphForm_m_z", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measurement Windows.
/// </summary>
public static string DiaIsolationWindowsGraphForm_DiaIsolationWindowsGraphForm_Measurement_Windows {
get {
return ResourceManager.GetString("DiaIsolationWindowsGraphForm_DiaIsolationWindowsGraphForm_Measurement_Windows", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Re-using existing DIA-Umpire file (with equivalent settings) for {0}.
/// </summary>
public static string DiaUmpireDdaConverter_Run_Re_using_existing_DiaUmpire_file__with_equivalent_settings__for__0_ {
get {
return ResourceManager.GetString("DiaUmpireDdaConverter_Run_Re_using_existing_DiaUmpire_file__with_equivalent_setti" +
"ngs__for__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Starting DIA-Umpire conversion.
/// </summary>
public static string DiaUmpireDdaConverter_Run_Starting_DIA_Umpire_conversion {
get {
return ResourceManager.GetString("DiaUmpireDdaConverter_Run_Starting_DIA_Umpire_conversion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Digesting {0} proteome with {1}.
/// </summary>
public static string DigestHelper_Digest_Digesting__0__proteome_with__1__ {
get {
return ResourceManager.GetString("DigestHelper_Digest_Digesting__0__proteome_with__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to access internet to resolve protein details..
/// </summary>
public static string DigestHelper_LookupProteinMetadata_Unable_to_access_internet_to_resolve_protein_details_ {
get {
return ResourceManager.GetString("DigestHelper_LookupProteinMetadata_Unable_to_access_internet_to_resolve_protein_d" +
"etails_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to maximum missed cleavages.
/// </summary>
public static string DigestSettings_Validate_maximum_missed_cleavages {
get {
return ResourceManager.GetString("DigestSettings_Validate_maximum_missed_cleavages", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value {1} for {0} must be between {2} and {3}..
/// </summary>
public static string DigestSettings_ValidateIntRange_The_value__1__for__0__must_be_between__2__and__3__ {
get {
return ResourceManager.GetString("DigestSettings_ValidateIntRange_The_value__1__for__0__must_be_between__2__and__3_" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Source directory does not exist or could not be found: .
/// </summary>
public static string DirectoryEx_DirectoryCopy_Source_directory_does_not_exist_or_could_not_be_found__ {
get {
return ResourceManager.GetString("DirectoryEx_DirectoryCopy_Source_directory_does_not_exist_or_could_not_be_found__" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap directoryicon {
get {
object obj = ResourceManager.GetObject("directoryicon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to N/A.
/// </summary>
public static string DisplayEquation_N_A {
get {
return ResourceManager.GetString("DisplayEquation_N_A", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Column.
/// </summary>
public static string DisplayGraphsTypeExtension_LOCALIZED_VALUES_Column {
get {
return ResourceManager.GetString("DisplayGraphsTypeExtension_LOCALIZED_VALUES_Column", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Row.
/// </summary>
public static string DisplayGraphsTypeExtension_LOCALIZED_VALUES_Row {
get {
return ResourceManager.GetString("DisplayGraphsTypeExtension_LOCALIZED_VALUES_Row", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Tiled.
/// </summary>
public static string DisplayGraphsTypeExtension_LOCALIZED_VALUES_Tiled {
get {
return ResourceManager.GetString("DisplayGraphsTypeExtension_LOCALIZED_VALUES_Tiled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Full Name.
/// </summary>
public static string DisplayModificationOption_FULL_NAME_Full_Name {
get {
return ResourceManager.GetString("DisplayModificationOption_FULL_NAME_Full_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mass Difference.
/// </summary>
public static string DisplayModificationOption_MASS_DELTA_Mass_Difference {
get {
return ResourceManager.GetString("DisplayModificationOption_MASS_DELTA_Mass_Difference", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Not Shown.
/// </summary>
public static string DisplayModificationOption_NOT_SHOWN_Not_Shown {
get {
return ResourceManager.GetString("DisplayModificationOption_NOT_SHOWN_Not_Shown", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Three Letter Code.
/// </summary>
public static string DisplayModificationOption_THREE_LETTER_CODE_Three_Letter_Code {
get {
return ResourceManager.GetString("DisplayModificationOption_THREE_LETTER_CODE_Three_Letter_Code", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unimod ID.
/// </summary>
public static string DisplayModificationOption_UNIMOD_ID_Unimod_ID {
get {
return ResourceManager.GetString("DisplayModificationOption_UNIMOD_ID_Unimod_ID", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Index {0} exceeds length {1}.
/// </summary>
public static string DocNodeParent_GetPathTo_Index__0__exceeds_length__1__ {
get {
return ResourceManager.GetString("DocNodeParent_GetPathTo_Index__0__exceeds_length__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Node reported {0} descendants at depth {1}, but found only {2}..
/// </summary>
public static string DocNodeParent_GetPathTo_Node_reported__0__descendants_at_depth__1__but_found_only__2__ {
get {
return ResourceManager.GetString("DocNodeParent_GetPathTo_Node_reported__0__descendants_at_depth__1__but_found_only" +
"__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Msx.
/// </summary>
public static string DoconvolutionMethod_MSX_Msx {
get {
return ResourceManager.GetString("DoconvolutionMethod_MSX_Msx", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None.
/// </summary>
public static string DoconvolutionMethod_NONE_None {
get {
return ResourceManager.GetString("DoconvolutionMethod_NONE_None", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overlap.
/// </summary>
public static string DoconvolutionMethod_OVERLAP_Overlap {
get {
return ResourceManager.GetString("DoconvolutionMethod_OVERLAP_Overlap", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Annotation '{0}' does not apply to element '{1}'..
/// </summary>
public static string DocumentAnnotations_AnnotationDoesNotApplyException_Annotation___0___does_not_apply_to_element___1___ {
get {
return ResourceManager.GetString("DocumentAnnotations_AnnotationDoesNotApplyException_Annotation___0___does_not_app" +
"ly_to_element___1___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The element '{0}' cannot have annotations..
/// </summary>
public static string DocumentAnnotations_AnnotationsNotSupported_The_element___0___cannot_have_annotations_ {
get {
return ResourceManager.GetString("DocumentAnnotations_AnnotationsNotSupported_The_element___0___cannot_have_annotat" +
"ions_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not find element '{0}'..
/// </summary>
public static string DocumentAnnotations_ElementNotFoundException_Could_not_find_element___0___ {
get {
return ResourceManager.GetString("DocumentAnnotations_ElementNotFoundException_Could_not_find_element___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Updating calculated annotations.
/// </summary>
public static string DocumentAnnotationUpdater_UpdateAnnotations_Updating_calculated_annotations {
get {
return ResourceManager.GetString("DocumentAnnotationUpdater_UpdateAnnotations_Updating_calculated_annotations", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Report.
/// </summary>
public static string DocumentGridViewContext_CreateViewEditor_Edit_Report {
get {
return ResourceManager.GetString("DocumentGridViewContext_CreateViewEditor_Edit_Report", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete the {0} '{1}'?.
/// </summary>
public static string DocumentGridViewContext_Delete_Are_you_sure_you_want_to_delete_the__0____1___ {
get {
return ResourceManager.GetString("DocumentGridViewContext_Delete_Are_you_sure_you_want_to_delete_the__0____1___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete these {0} {1}?.
/// </summary>
public static string DocumentGridViewContext_Delete_Are_you_sure_you_want_to_delete_these__0___1__ {
get {
return ResourceManager.GetString("DocumentGridViewContext_Delete_Are_you_sure_you_want_to_delete_these__0___1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Preview: {0}.
/// </summary>
public static string DocumentGridViewContext_Preview_Preview___0_ {
get {
return ResourceManager.GetString("DocumentGridViewContext_Preview_Preview___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Preview New Report.
/// </summary>
public static string DocumentGridViewContext_Preview_Preview_New_Report {
get {
return ResourceManager.GetString("DocumentGridViewContext_Preview_Preview_New_Report", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete those items from those lists?.
/// </summary>
public static string DocumentSettingsDlg_OkDialog_Are_you_sure_you_want_to_delete_those_items_from_those_lists_ {
get {
return ResourceManager.GetString("DocumentSettingsDlg_OkDialog_Are_you_sure_you_want_to_delete_those_items_from_tho" +
"se_lists_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to List '{0}' with {1} items.
/// </summary>
public static string DocumentSettingsDlg_OkDialog_List___0___with__1__items {
get {
return ResourceManager.GetString("DocumentSettingsDlg_OkDialog_List___0___with__1__items", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following lists have items in them which will be deleted when you remove the lists from your document:.
/// </summary>
public static string DocumentSettingsDlg_OkDialog_The_following_lists_have_items_in_them_which_will_be_deleted_when_you_remove_the_lists_from_your_document_ {
get {
return ResourceManager.GetString("DocumentSettingsDlg_OkDialog_The_following_lists_have_items_in_them_which_will_be" +
"_deleted_when_you_remove_the_lists_from_your_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The list '{0}' has {1} items in it. If you remove that list from your document, those items will be deleted. Are you sure you want to delete those items from that list?.
/// </summary>
public static string DocumentSettingsDlg_OkDialog_The_list___0___has__1__items_in_it__If_you_remove_that_list_from_your_document__those_items_will_be_deleted__Are_you_sure_you_want_to_delete_those_items_from_that_list_ {
get {
return ResourceManager.GetString("DocumentSettingsDlg_OkDialog_The_list___0___has__1__items_in_it__If_you_remove_th" +
"at_list_from_your_document__those_items_will_be_deleted__Are_you_sure_you_want_t" +
"o_delete_those_items_from_that_list_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while applying the rule set '{0}'. Do you want to continue with the change to the Document Settings?.
/// </summary>
public static string DocumentSettingsDlg_ValidateMetadataRules_An_error_occurred_while_applying_the_rule___0____Do_you_want_to_continue_with_the_change_to_the_Document_Settings_ {
get {
return ResourceManager.GetString("DocumentSettingsDlg_ValidateMetadataRules_An_error_occurred_while_applying_the_ru" +
"le___0____Do_you_want_to_continue_with_the_change_to_the_Document_Settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to convert crosslinks in {0} to document format {1}..
/// </summary>
public static string DocumentWriter_WritePeptideXml_Unable_to_convert_crosslinks_in__0__to_document_format__1__ {
get {
return ResourceManager.GetString("DocumentWriter_WritePeptideXml_Unable_to_convert_crosslinks_in__0__to_document_fo" +
"rmat__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap down_pro32 {
get {
object obj = ResourceManager.GetObject("down_pro32", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Resolving power must be greater than 0..
/// </summary>
public static string DriftTimePredictor_Validate_Resolving_power_must_be_greater_than_0_ {
get {
return ResourceManager.GetString("DriftTimePredictor_Validate_Resolving_power_must_be_greater_than_0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fixed window width must be non negative..
/// </summary>
public static string DriftTimeWindowWidthCalculator_Validate_Fixed_window_width_must_be_non_negative_ {
get {
return ResourceManager.GetString("DriftTimeWindowWidthCalculator_Validate_Fixed window_width_must_be_non_negative_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak width must be non-negative..
/// </summary>
public static string DriftTimeWindowWidthCalculator_Validate_Peak_width_must_be_non_negative_ {
get {
return ResourceManager.GetString("DriftTimeWindowWidthCalculator_Validate_Peak_width_must_be_non_negative_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap DropImage {
get {
object obj = ResourceManager.GetObject("DropImage", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Line {0} has {1} fields when {2} expected..
/// </summary>
public static string DsvFileReader_ReadLine_Line__0__has__1__fields_when__2__expected_ {
get {
return ResourceManager.GetString("DsvFileReader_ReadLine_Line__0__has__1__fields_when__2__expected_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Edit_Redo {
get {
object obj = ResourceManager.GetObject("Edit_Redo", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Edit_Undo {
get {
object obj = ResourceManager.GetObject("Edit_Undo", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Edit_Undo_Multiple {
get {
object obj = ResourceManager.GetObject("Edit_Undo_Multiple", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Measured results must be completely loaded before they can be used to create a collision energy regression..
/// </summary>
public static string EditCEDlg_GetRegressionDatas_Measured_results_must_be_completely_loaded_before_they_can_be_used_to_create_a_collision_energy_regression {
get {
return ResourceManager.GetString("EditCEDlg_GetRegressionDatas_Measured_results_must_be_completely_loaded_before_th" +
"ey_can_be_used_to_create_a_collision_energy_regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collision energy regressions require at least one regression function..
/// </summary>
public static string EditCEDlg_OkDialog_Collision_energy_regressions_require_at_least_one_regression_function {
get {
return ResourceManager.GetString("EditCEDlg_OkDialog_Collision_energy_regressions_require_at_least_one_regression_f" +
"unction", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The collision energy regression '{0}' already exists..
/// </summary>
public static string EditCEDlg_OkDialog_The_collision_energy_regression__0__already_exists {
get {
return ResourceManager.GetString("EditCEDlg_OkDialog_The_collision_energy_regression__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collision Energy.
/// </summary>
public static string EditCEDlg_ShowGraph_Collision_Energy {
get {
return ResourceManager.GetString("EditCEDlg_ShowGraph_Collision_Energy", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collision Energy Regression Charge {0}.
/// </summary>
public static string EditCEDlg_ShowGraph_Collision_Energy_Regression_Charge__0__ {
get {
return ResourceManager.GetString("EditCEDlg_ShowGraph_Collision_Energy_Regression_Charge__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor m/z.
/// </summary>
public static string EditCEDlg_ShowGraph_Precursor_m_z {
get {
return ResourceManager.GetString("EditCEDlg_ShowGraph_Precursor_m_z", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insufficient data found to calculate a new regression..
/// </summary>
public static string EditCEDlg_UseCurrentData_Insufficient_data_found_to_calculate_a_new_regression {
get {
return ResourceManager.GetString("EditCEDlg_UseCurrentData_Insufficient_data_found_to_calculate_a_new_regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A value is required..
/// </summary>
public static string EditCEDlg_ValidateCell_A_value_is_required {
get {
return ResourceManager.GetString("EditCEDlg_ValidateCell_A_value_is_required", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The entry {0} is not valid..
/// </summary>
public static string EditCEDlg_ValidateCell_The_entry__0__is_not_valid {
get {
return ResourceManager.GetString("EditCEDlg_ValidateCell_The_entry__0__is_not_valid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The entry '{0}' is not a valid charge. Precursor charges must be between 1 and 5..
/// </summary>
public static string EditCEDlg_ValidateCharge_The_entry__0__is_not_a_valid_charge_Precursor_charges_must_be_between_1_and_5 {
get {
return ResourceManager.GetString("EditCEDlg_ValidateCharge_The_entry__0__is_not_a_valid_charge_Precursor_charges_mu" +
"st_be_between_1_and_5", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to On line {0}, {1}.
/// </summary>
public static string EditCEDlg_ValidateRegressionCellValues_On_line__0__1__ {
get {
return ResourceManager.GetString("EditCEDlg_ValidateRegressionCellValues_On_line__0__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to the value {0} is not a valid charge. Charges must be integer values between 1 and 5..
/// </summary>
public static string EditCEDlg_ValidateRegressionCellValues_the_value__0__is_not_a_valid_charge_Charges_must_be_integer_values_between_1_and_5 {
get {
return ResourceManager.GetString("EditCEDlg_ValidateRegressionCellValues_the_value__0__is_not_a_valid_charge_Charge" +
"s_must_be_integer_values_between_1_and_5", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to the value {0} is not a valid intercept..
/// </summary>
public static string EditCEDlg_ValidateRegressionCellValues_the_value__0__is_not_a_valid_intercept {
get {
return ResourceManager.GetString("EditCEDlg_ValidateRegressionCellValues_the_value__0__is_not_a_valid_intercept", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to the value {0} is not a valid slope..
/// </summary>
public static string EditCEDlg_ValidateRegressionCellValues_the_value__0__is_not_a_valid_slope {
get {
return ResourceManager.GetString("EditCEDlg_ValidateRegressionCellValues_the_value__0__is_not_a_valid_slope", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Maximum compensation voltage cannot be less than minimum compensation volatage..
/// </summary>
public static string EditCoVDlg_btnOk_Click_Maximum_compensation_voltage_cannot_be_less_than_minimum_compensation_volatage_ {
get {
return ResourceManager.GetString("EditCoVDlg_btnOk_Click_Maximum_compensation_voltage_cannot_be_less_than_minimum_c" +
"ompensation_volatage_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The compensation voltage parameters '{0}' already exist..
/// </summary>
public static string EditCoVDlg_btnOk_Click_The_compensation_voltage_parameters___0___already_exist_ {
get {
return ResourceManager.GetString("EditCoVDlg_btnOk_Click_The_compensation_voltage_parameters___0___already_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Monoisotopic m/z:.
/// </summary>
public static string EditCustomMoleculeDlg_EditCustomMoleculeDlg__Monoisotopic_m_z_ {
get {
return ResourceManager.GetString("EditCustomMoleculeDlg_EditCustomMoleculeDlg__Monoisotopic_m_z_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Monoisotopic mass:.
/// </summary>
public static string EditCustomMoleculeDlg_EditCustomMoleculeDlg__Monoisotopic_mass_ {
get {
return ResourceManager.GetString("EditCustomMoleculeDlg_EditCustomMoleculeDlg__Monoisotopic_mass_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A&verage m/z:.
/// </summary>
public static string EditCustomMoleculeDlg_EditCustomMoleculeDlg_A_verage_m_z_ {
get {
return ResourceManager.GetString("EditCustomMoleculeDlg_EditCustomMoleculeDlg_A_verage_m_z_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A&verage mass:.
/// </summary>
public static string EditCustomMoleculeDlg_EditCustomMoleculeDlg_A_verage_mass_ {
get {
return ResourceManager.GetString("EditCustomMoleculeDlg_EditCustomMoleculeDlg_A_verage_mass_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Addu&ct for {0}:.
/// </summary>
public static string EditCustomMoleculeDlg_EditCustomMoleculeDlg_Addu_ct_for__0__ {
get {
return ResourceManager.GetString("EditCustomMoleculeDlg_EditCustomMoleculeDlg_Addu_ct_for__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Chemi&cal formula:.
/// </summary>
public static string EditCustomMoleculeDlg_EditCustomMoleculeDlg_Chemi_cal_formula_ {
get {
return ResourceManager.GetString("EditCustomMoleculeDlg_EditCustomMoleculeDlg_Chemi_cal_formula_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A precursor with that adduct and label type already exists..
/// </summary>
public static string EditCustomMoleculeDlg_OkDialog_A_precursor_with_that_adduct_and_label_type_already_exists_ {
get {
return ResourceManager.GetString("EditCustomMoleculeDlg_OkDialog_A_precursor_with_that_adduct_and_label_type_alread" +
"y_exists_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A similar transition already exists..
/// </summary>
public static string EditCustomMoleculeDlg_OkDialog_A_similar_transition_already_exists_ {
get {
return ResourceManager.GetString("EditCustomMoleculeDlg_OkDialog_A_similar_transition_already_exists_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Custom molecules must have a mass greater than or equal to {0}..
/// </summary>
public static string EditCustomMoleculeDlg_OkDialog_Custom_molecules_must_have_a_mass_greater_than_or_equal_to__0__ {
get {
return ResourceManager.GetString("EditCustomMoleculeDlg_OkDialog_Custom_molecules_must_have_a_mass_greater_than_or_" +
"equal_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Custom molecules must have a mass less than or equal to {0}..
/// </summary>
public static string EditCustomMoleculeDlg_OkDialog_Custom_molecules_must_have_a_mass_less_than_or_equal_to__0__ {
get {
return ResourceManager.GetString("EditCustomMoleculeDlg_OkDialog_Custom_molecules_must_have_a_mass_less_than_or_equ" +
"al_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please specify the ion mobility units..
/// </summary>
public static string EditCustomMoleculeDlg_OkDialog_Please_specify_the_ion_mobility_units_ {
get {
return ResourceManager.GetString("EditCustomMoleculeDlg_OkDialog_Please_specify_the_ion_mobility_units_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The color scheme '{0}' already exists..
/// </summary>
public static string EditCustomThemeDlg_buttonSave_Click_The_color_scheme___0___already_exists_ {
get {
return ResourceManager.GetString("EditCustomThemeDlg_buttonSave_Click_The_color_scheme___0___already_exists_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Colors must be entered in HEX or RGB format..
/// </summary>
public static string EditCustomThemeDlg_dataGridViewColors_DataError_Colors_must_be_entered_in_HEX_or_RGB_format_ {
get {
return ResourceManager.GetString("EditCustomThemeDlg_dataGridViewColors_DataError_Colors_must_be_entered_in_HEX_or_" +
"RGB_format_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to parse the color '{0}'. Use HEX or RGB format..
/// </summary>
public static string EditCustomThemeDlg_DoPaste_Unable_to_parse_the_color___0____Use_HEX_or_RGB_format_ {
get {
return ResourceManager.GetString("EditCustomThemeDlg_DoPaste_Unable_to_parse_the_color___0____Use_HEX_or_RGB_format" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Set {0} to '{1}'.
/// </summary>
public static string EditDescription_GetUndoText_Set__0__to___1__ {
get {
return ResourceManager.GetString("EditDescription_GetUndoText_Set__0__to___1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measured results must be completely loaded before they can be used to create a declustering potential regression..
/// </summary>
public static string EditDPDlg_GetRegressionData_Measured_results_must_be_completely_loaded_before_they_can_be_used_to_create_a_declustering_potential_regression {
get {
return ResourceManager.GetString("EditDPDlg_GetRegressionData_Measured_results_must_be_completely_loaded_before_the" +
"y_can_be_used_to_create_a_declustering_potential_regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The declustering potential regression '{0}' already exists..
/// </summary>
public static string EditDPDlg_OkDialog_The_declustering_potential_regression__0__already_exists {
get {
return ResourceManager.GetString("EditDPDlg_OkDialog_The_declustering_potential_regression__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Declustering Potential.
/// </summary>
public static string EditDPDlg_ShowGraph_Declustering_Potential {
get {
return ResourceManager.GetString("EditDPDlg_ShowGraph_Declustering_Potential", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Declustering Potential Regression.
/// </summary>
public static string EditDPDlg_ShowGraph_Declustering_Potential_Regression {
get {
return ResourceManager.GetString("EditDPDlg_ShowGraph_Declustering_Potential_Regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor m/z.
/// </summary>
public static string EditDPDlg_ShowGraph_Precursor_m_z {
get {
return ResourceManager.GetString("EditDPDlg_ShowGraph_Precursor_m_z", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insufficient data found to calculate a new regression..
/// </summary>
public static string EditDPDlg_UseCurrentData_Insufficient_data_found_to_calculate_a_new_regression {
get {
return ResourceManager.GetString("EditDPDlg_UseCurrentData_Insufficient_data_found_to_calculate_a_new_regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The enzyme '{0}' already exists..
/// </summary>
public static string EditEnzymeDlg_OnClosing_The_enzyme__0__already_exists {
get {
return ResourceManager.GetString("EditEnzymeDlg_OnClosing_The_enzyme__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must contain at least one amino acid..
/// </summary>
public static string EditEnzymeDlg_ValidateAATextBox__0__must_contain_at_least_one_amino_acid {
get {
return ResourceManager.GetString("EditEnzymeDlg_ValidateAATextBox__0__must_contain_at_least_one_amino_acid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The character '{0}' is not a valid amino acid..
/// </summary>
public static string EditEnzymeDlg_ValidateAATextBox_The_character__0__is_not_a_valid_amino_acid {
get {
return ResourceManager.GetString("EditEnzymeDlg_ValidateAATextBox_The_character__0__is_not_a_valid_amino_acid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must contain a valid regular expression..
/// </summary>
public static string EditExclusionDlg_OkDialog__0__must_contain_a_valid_regular_expression_ {
get {
return ResourceManager.GetString("EditExclusionDlg_OkDialog__0__must_contain_a_valid_regular_expression_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide exclusion '{0}' already exists..
/// </summary>
public static string EditExclusionDlg_OkDialog_The_peptide_exclusion__0__already_exists {
get {
return ResourceManager.GetString("EditExclusionDlg_OkDialog_The_peptide_exclusion__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The text '{0}' is not a valid regular expression..
/// </summary>
public static string EditExclusionDlg_OkDialog_The_text__0__is_not_a_valid_regular_expression {
get {
return ResourceManager.GetString("EditExclusionDlg_OkDialog_The_text__0__is_not_a_valid_regular_expression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Monoisotopic loss:.
/// </summary>
public static string EditFragmentLossDlg_EditFragmentLossDlg__Monoisotopic_loss_ {
get {
return ResourceManager.GetString("EditFragmentLossDlg_EditFragmentLossDlg__Monoisotopic_loss_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A&verage loss:.
/// </summary>
public static string EditFragmentLossDlg_EditFragmentLossDlg_A_verage_loss_ {
get {
return ResourceManager.GetString("EditFragmentLossDlg_EditFragmentLossDlg_A_verage_loss_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loss &chemical formula:.
/// </summary>
public static string EditFragmentLossDlg_EditFragmentLossDlg_Loss__chemical_formula_ {
get {
return ResourceManager.GetString("EditFragmentLossDlg_EditFragmentLossDlg_Loss__chemical_formula_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Neutral loss masses must be greater than or equal to {0}..
/// </summary>
public static string EditFragmentLossDlg_OkDialog_Neutral_loss_masses_must_be_greater_than_or_equal_to__0__ {
get {
return ResourceManager.GetString("EditFragmentLossDlg_OkDialog_Neutral_loss_masses_must_be_greater_than_or_equal_to" +
"__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Neutral loss masses must be less than or equal to {0}..
/// </summary>
public static string EditFragmentLossDlg_OkDialog_Neutral_loss_masses_must_be_less_than_or_equal_to__0__ {
get {
return ResourceManager.GetString("EditFragmentLossDlg_OkDialog_Neutral_loss_masses_must_be_less_than_or_equal_to__0" +
"__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please specify a formula or constant masses..
/// </summary>
public static string EditFragmentLossDlg_OkDialog_Please_specify_a_formula_or_constant_masses {
get {
return ResourceManager.GetString("EditFragmentLossDlg_OkDialog_Please_specify_a_formula_or_constant_masses", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The loss '{0}' already exists.
/// </summary>
public static string EditFragmentLossDlg_OkDialog_The_loss__0__already_exists {
get {
return ResourceManager.GetString("EditFragmentLossDlg_OkDialog_The_loss__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to open a new ion mobility library file? Any changes to the current library will be lost..
/// </summary>
public static string EditIonMobilityLibraryDlg_btnBrowseDb_Click_Are_you_sure_you_want_to_open_a_new_ion_mobility_library_file___Any_changes_to_the_current_library_will_be_lost_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_btnBrowseDb_Click_Are_you_sure_you_want_to_open_a_new_i" +
"on_mobility_library_file___Any_changes_to_the_current_library_will_be_lost_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Open Ion Mobility Library.
/// </summary>
public static string EditIonMobilityLibraryDlg_btnBrowseDb_Click_Open_Ion_Mobility_Library {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_btnBrowseDb_Click_Open_Ion_Mobility_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to create a new ion mobility library file? Any changes to the current library will be lost..
/// </summary>
public static string EditIonMobilityLibraryDlg_btnCreateDb_Click_Are_you_sure_you_want_to_create_a_new_ion_mobility_library_file___Any_changes_to_the_current_library_will_be_lost_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_btnCreateDb_Click_Are_you_sure_you_want_to_create_a_new" +
"_ion_mobility_library_file___Any_changes_to_the_current_library_will_be_lost_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Create Ion Mobility Library.
/// </summary>
public static string EditIonMobilityLibraryDlg_btnCreateDb_Click_Create_Ion_Mobility_Library {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_btnCreateDb_Click_Create_Ion_Mobility_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The ion mobility library file {0} could not be created..
/// </summary>
public static string EditIonMobilityLibraryDlg_CreateDatabase_The_ion_mobility_library_file__0__could_not_be_created {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_CreateDatabase_The_ion_mobility_library_file__0__could_" +
"not_be_created", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adduct.
/// </summary>
public static string EditIonMobilityLibraryDlg_EditIonMobilityLibraryDlg_Adduct {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_EditIonMobilityLibraryDlg_Adduct", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule.
/// </summary>
public static string EditIonMobilityLibraryDlg_EditIonMobilityLibraryDlg_Molecule {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_EditIonMobilityLibraryDlg_Molecule", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Finding ion mobility values for peaks.
/// </summary>
public static string EditIonMobilityLibraryDlg_GetDriftTimesFromResults_Finding_ion_mobility_values_for_peaks {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_GetDriftTimesFromResults_Finding_ion_mobility_values_fo" +
"r_peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An ion mobility library with the name {0} already exists. Do you want to overwrite it?.
/// </summary>
public static string EditIonMobilityLibraryDlg_OkDialog_An_ion_mobility_library_with_the_name__0__already_exists__Do_you_want_to_overwrite_it_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_OkDialog_An_ion_mobility_library_with_the_name__0__alre" +
"ady_exists__Do_you_want_to_overwrite_it_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Click the Create button to create a new library or the Open button to open an existing library file..
/// </summary>
public static string EditIonMobilityLibraryDlg_OkDialog_Click_the_Create_button_to_create_a_new_library_or_the_Open_button_to_open_an_existing_library_file_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_OkDialog_Click_the_Create_button_to_create_a_new_librar" +
"y_or_the_Open_button_to_open_an_existing_library_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to change it?.
/// </summary>
public static string EditIonMobilityLibraryDlg_OkDialog_Do_you_want_to_change_it_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_OkDialog_Do_you_want_to_change_it_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure updating peptides in the ion mobility library. The library may be out of synch..
/// </summary>
public static string EditIonMobilityLibraryDlg_OkDialog_Failure_updating_peptides_in_the_ion_mobility_library__The_library_may_be_out_of_synch_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_OkDialog_Failure_updating_peptides_in_the_ion_mobility_" +
"library__The_library_may_be_out_of_synch_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please choose a file for the ion mobility library..
/// </summary>
public static string EditIonMobilityLibraryDlg_OkDialog_Please_choose_a_file_for_the_ion_mobility_library {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_OkDialog_Please_choose_a_file_for_the_ion_mobility_libr" +
"ary", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please enter a name for the ion mobility library..
/// </summary>
public static string EditIonMobilityLibraryDlg_OkDialog_Please_enter_a_name_for_the_ion_mobility_library_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_OkDialog_Please_enter_a_name_for_the_ion_mobility_libra" +
"ry_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please use a full path to a file for the ion mobility library..
/// </summary>
public static string EditIonMobilityLibraryDlg_OkDialog_Please_use_a_full_path_to_a_file_for_the_ion_mobility_library_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_OkDialog_Please_use_a_full_path_to_a_file_for_the_ion_m" +
"obility_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not exist. Click the Create button to create a new ion mobility library or click the Open button to find the missing file..
/// </summary>
public static string EditIonMobilityLibraryDlg_OpenDatabase_The_file__0__does_not_exist__Click_the_Create_button_to_create_a_new_ion_mobility_library_or_click_the_Open_button_to_find_the_missing_file_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_OpenDatabase_The_file__0__does_not_exist__Click_the_Cre" +
"ate_button_to_create_a_new_ion_mobility_library_or_click_the_Open_button_to_find" +
"_the_missing_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Peptide.
/// </summary>
public static string EditIonMobilityLibraryDlg_UpdateNumPeptides__0__Peptide {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_UpdateNumPeptides__0__Peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Peptides.
/// </summary>
public static string EditIonMobilityLibraryDlg_UpdateNumPeptides__0__Peptides {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_UpdateNumPeptides__0__Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Precursor Ion.
/// </summary>
public static string EditIonMobilityLibraryDlg_UpdateNumPrecursorIons__0__Precursor_Ion {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_UpdateNumPrecursorIons__0__Precursor_Ion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Precursor Ions.
/// </summary>
public static string EditIonMobilityLibraryDlg_UpdateNumPrecursorIons__0__Precursor_Ions {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_UpdateNumPrecursorIons__0__Precursor_Ions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A value is required..
/// </summary>
public static string EditIonMobilityLibraryDlg_ValidateCell_A_value_is_required_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_ValidateCell_A_value_is_required_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The entry {0} is not valid..
/// </summary>
public static string EditIonMobilityLibraryDlg_ValidateCell_The_entry__0__is_not_valid_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_ValidateCell_The_entry__0__is_not_valid_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value {0} is not a valid modified peptide sequence..
/// </summary>
public static string EditIonMobilityLibraryDlg_ValidatePeptideList_The_value__0__is_not_a_valid_modified_peptide_sequence_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_ValidatePeptideList_The_value__0__is_not_a_valid_modifi" +
"ed_peptide_sequence_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to On line {0} {1}.
/// </summary>
public static string EditIonMobilityLibraryDlg_ValidateRegressionCellValues_On_line__0___1_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_ValidateRegressionCellValues_On_line__0___1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to the value {0} is not a valid charge. Charges must be integer values between 1 and {1}..
/// </summary>
public static string EditIonMobilityLibraryDlg_ValidateRegressionCellValues_the_value__0__is_not_a_valid_charge__Charges_must_be_integer_values_between_1_and__1__ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_ValidateRegressionCellValues_the_value__0__is_not_a_val" +
"id_charge__Charges_must_be_integer_values_between_1_and__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to the value {0} is not a valid intercept..
/// </summary>
public static string EditIonMobilityLibraryDlg_ValidateRegressionCellValues_the_value__0__is_not_a_valid_intercept_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_ValidateRegressionCellValues_the_value__0__is_not_a_val" +
"id_intercept_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to the value {0} is not a valid slope..
/// </summary>
public static string EditIonMobilityLibraryDlg_ValidateRegressionCellValues_the_value__0__is_not_a_valid_slope_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_ValidateRegressionCellValues_the_value__0__is_not_a_val" +
"id_slope_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Resolving power must be greater than 0..
/// </summary>
public static string EditIonMobilityLibraryDlg_ValidateResolvingPower_Resolving_power_must_be_greater_than_0_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_ValidateResolvingPower_Resolving_power_must_be_greater_" +
"than_0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following ions have multiple ion mobility values. Skyline supports multiple conformers, so this may be intentional..
/// </summary>
public static string EditIonMobilityLibraryDlg_ValidateUniquePrecursors_The_following_ions_have_multiple_ion_mobility_values__Skyline_supports_multiple_conformers__so_this_may_be_intentional_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_ValidateUniquePrecursors_The_following_ions_have_multip" +
"le_ion_mobility_values__Skyline_supports_multiple_conformers__so_this_may_be_int" +
"entional_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The ion {0} has multiple ion mobility values. Skyline supports multiple conformers, so this may be intentional..
/// </summary>
public static string EditIonMobilityLibraryDlg_ValidateUniquePrecursors_The_ion__0__has_multiple_ion_mobility_values__Skyline_supports_multiple_conformers__so_this_may_be_intentional_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_ValidateUniquePrecursors_The_ion__0__has_multiple_ion_m" +
"obility_values__Skyline_supports_multiple_conformers__so_this_may_be_intentional" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This list contains {0} ions with multiple ion mobility values. Skyline supports multiple conformers, so this may be intentional..
/// </summary>
public static string EditIonMobilityLibraryDlg_ValidateUniquePrecursors_This_list_contains__0__ions_with_multiple_ion_mobility_values__Skyline_supports_multiple_conformers__so_this_may_be_intentional_ {
get {
return ResourceManager.GetString("EditIonMobilityLibraryDlg_ValidateUniquePrecursors_This_list_contains__0__ions_wi" +
"th_multiple_ion_mobility_values__Skyline_supports_multiple_conformers__so_this_m" +
"ay_be_intentional_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to open a new database file? Any changes to the current calculator will be lost..
/// </summary>
public static string EditIrtCalcDlg_btnBrowseDb_Click_Are_you_sure_you_want_to_open_a_new_database_file_Any_changes_to_the_current_calculator_will_be_lost {
get {
return ResourceManager.GetString("EditIrtCalcDlg_btnBrowseDb_Click_Are_you_sure_you_want_to_open_a_new_database_fil" +
"e_Any_changes_to_the_current_calculator_will_be_lost", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Open iRT Database.
/// </summary>
public static string EditIrtCalcDlg_btnBrowseDb_Click_Open_iRT_Database {
get {
return ResourceManager.GetString("EditIrtCalcDlg_btnBrowseDb_Click_Open_iRT_Database", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to create a new database file? Any changes to the current calculator will be lost..
/// </summary>
public static string EditIrtCalcDlg_btnCreateDb_Click_Are_you_sure_you_want_to_create_a_new_database_file_Any_changes_to_the_current_calculator_will_be_lost {
get {
return ResourceManager.GetString("EditIrtCalcDlg_btnCreateDb_Click_Are_you_sure_you_want_to_create_a_new_database_f" +
"ile_Any_changes_to_the_current_calculator_will_be_lost", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Create iRT Database.
/// </summary>
public static string EditIrtCalcDlg_btnCreateDb_Click_Create_iRT_Database {
get {
return ResourceManager.GetString("EditIrtCalcDlg_btnCreateDb_Click_Create_iRT_Database", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removed peptides on iRT standard protein.
/// </summary>
public static string EditIrtCalcDlg_ChangeStandardPeptides_Removed_peptides_on_iRT_standard_protein {
get {
return ResourceManager.GetString("EditIrtCalcDlg_ChangeStandardPeptides_Removed_peptides_on_iRT_standard_protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The list of standard peptides must contain only recognized iRT-C18 standards to switch to a predefined set of iRT-C18 standards..
/// </summary>
public static string EditIrtCalcDlg_comboStandards_SelectedIndexChanged_The_list_of_standard_peptides_must_contain_only_recognized_iRT_C18_standards_to_switch_to_a_predefined_set_of_iRT_C18_standards_ {
get {
return ResourceManager.GetString("EditIrtCalcDlg_comboStandards_SelectedIndexChanged_The_list_of_standard_peptides_" +
"must_contain_only_recognized_iRT_C18_standards_to_switch_to_a_predefined_set_of_" +
"iRT_C18_standards_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} could not be created..
/// </summary>
public static string EditIrtCalcDlg_CreateDatabase_The_file__0__could_not_be_created {
get {
return ResourceManager.GetString("EditIrtCalcDlg_CreateDatabase_The_file__0__could_not_be_created", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A calculator with the name {0} already exists. Do you want to overwrite it?.
/// </summary>
public static string EditIrtCalcDlg_OkDialog_A_calculator_with_the_name__0__already_exists_Do_you_want_to_overwrite_it {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OkDialog_A_calculator_with_the_name__0__already_exists_Do_you_want" +
"_to_overwrite_it", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Chromatogram libraries cannot be modified. You must save this iRT calculator as a new file..
/// </summary>
public static string EditIrtCalcDlg_OkDialog_Chromatogram_libraries_cannot_be_modified__You_must_save_this_iRT_calculator_as_a_new_file_ {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OkDialog_Chromatogram_libraries_cannot_be_modified__You_must_save_" +
"this_iRT_calculator_as_a_new_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Click the Create button to create a new database or the Open button to open an existing database file..
/// </summary>
public static string EditIrtCalcDlg_OkDialog_Click_the_Create_button_to_create_a_new_database_or_the_Open_button_to_open_an_existing_database_file {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OkDialog_Click_the_Create_button_to_create_a_new_database_or_the_O" +
"pen_button_to_open_an_existing_database_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure updating peptides in the iRT database. The database may be out of synch..
/// </summary>
public static string EditIrtCalcDlg_OkDialog_Failure_updating_peptides_in_the_iRT_database___The_database_may_be_out_of_synch_ {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OkDialog_Failure_updating_peptides_in_the_iRT_database___The_datab" +
"ase_may_be_out_of_synch_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to library.
/// </summary>
public static string EditIrtCalcDlg_OkDialog_library_table_name {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OkDialog_library_table_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please choose a database file for the iRT calculator..
/// </summary>
public static string EditIrtCalcDlg_OkDialog_Please_choose_a_database_file_for_the_iRT_calculator {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OkDialog_Please_choose_a_database_file_for_the_iRT_calculator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please enter a name for the iRT calculator..
/// </summary>
public static string EditIrtCalcDlg_OkDialog_Please_enter_a_name_for_the_iRT_calculator {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OkDialog_Please_enter_a_name_for_the_iRT_calculator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please enter at least {0} standard peptides..
/// </summary>
public static string EditIrtCalcDlg_OkDialog_Please_enter_at_least__0__standard_peptides {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OkDialog_Please_enter_at_least__0__standard_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please use a full path to a database file for the iRT calculator..
/// </summary>
public static string EditIrtCalcDlg_OkDialog_Please_use_a_full_path_to_a_database_file_for_the_iRT_calculator {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OkDialog_Please_use_a_full_path_to_a_database_file_for_the_iRT_cal" +
"culator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Spectral libraries cannot be modified. You must save this iRT calculator as a new file..
/// </summary>
public static string EditIrtCalcDlg_OkDialog_Spectral_libraries_cannot_be_modified__You_must_save_this_iRT_calculator_as_a_new_file_ {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OkDialog_Spectral_libraries_cannot_be_modified__You_must_save_this" +
"_iRT_calculator_as_a_new_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to standard.
/// </summary>
public static string EditIrtCalcDlg_OkDialog_standard_table_name {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OkDialog_standard_table_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Using fewer than {0} standard peptides is not recommended. Are you sure you want to continue with only {1}?.
/// </summary>
public static string EditIrtCalcDlg_OkDialog_Using_fewer_than__0__standard_peptides_is_not_recommended_Are_you_sure_you_want_to_continue_with_only__1__ {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OkDialog_Using_fewer_than__0__standard_peptides_is_not_recommended" +
"_Are_you_sure_you_want_to_continue_with_only__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not exist. Click the Create button to create a new database or the Open button to find the missing file..
/// </summary>
public static string EditIrtCalcDlg_OpenDatabase_The_file__0__does_not_exist__Click_the_Create_button_to_create_a_new_database_or_the_Open_button_to_find_the_missing_file_ {
get {
return ResourceManager.GetString("EditIrtCalcDlg_OpenDatabase_The_file__0__does_not_exist__Click_the_Create_button_" +
"to_create_a_new_database_or_the_Open_button_to_find_the_missing_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not get a minimum or maximum standard peptide..
/// </summary>
public static string EditIrtCalcDlg_RecalibrateStandards_Could_not_get_a_minimum_or_maximum_standard_peptide_ {
get {
return ResourceManager.GetString("EditIrtCalcDlg_RecalibrateStandards_Could_not_get_a_minimum_or_maximum_standard_p" +
"eptide_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Peptide.
/// </summary>
public static string EditIrtCalcDlg_UpdateNumPeptides__0__Peptide {
get {
return ResourceManager.GetString("EditIrtCalcDlg_UpdateNumPeptides__0__Peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Peptides.
/// </summary>
public static string EditIrtCalcDlg_UpdateNumPeptides__0__Peptides {
get {
return ResourceManager.GetString("EditIrtCalcDlg_UpdateNumPeptides__0__Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cali&brate....
/// </summary>
public static string EditIrtCalcDlg_UpdateNumPeptides_Calibrate {
get {
return ResourceManager.GetString("EditIrtCalcDlg_UpdateNumPeptides_Calibrate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Recali&brate....
/// </summary>
public static string EditIrtCalcDlg_UpdateNumPeptides_Recalibrate {
get {
return ResourceManager.GetString("EditIrtCalcDlg_UpdateNumPeptides_Recalibrate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Standard peptide ({1} required).
/// </summary>
public static string EditIrtCalcDlg_UpdateNumStandards__0__Standard_peptide___1__required_ {
get {
return ResourceManager.GetString("EditIrtCalcDlg_UpdateNumStandards__0__Standard_peptide___1__required_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Standard peptides ({1} required).
/// </summary>
public static string EditIrtCalcDlg_UpdateNumStandards__0__Standard_peptides___1__required_ {
get {
return ResourceManager.GetString("EditIrtCalcDlg_UpdateNumStandards__0__Standard_peptides___1__required_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide {0} appears in the {1} table more than once..
/// </summary>
public static string EditIrtCalcDlg_ValidatePeptideList_The_peptide__0__appears_in_the__1__table_more_than_once {
get {
return ResourceManager.GetString("EditIrtCalcDlg_ValidatePeptideList_The_peptide__0__appears_in_the__1__table_more_" +
"than_once", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value {0} is not a valid modified peptide sequence..
/// </summary>
public static string EditIrtCalcDlg_ValidatePeptideList_The_value__0__is_not_a_valid_modified_peptide_sequence {
get {
return ResourceManager.GetString("EditIrtCalcDlg_ValidatePeptideList_The_value__0__is_not_a_valid_modified_peptide_" +
"sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Margin.
/// </summary>
public static string EditIsolationSchemeDlg_comboMargins_SelectedIndexChanged_Margin {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_comboMargins_SelectedIndexChanged_Margin", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Start margin.
/// </summary>
public static string EditIsolationSchemeDlg_comboMargins_SelectedIndexChanged_Start_margin {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_comboMargins_SelectedIndexChanged_Start_margin", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overlap requires an even number of windows..
/// </summary>
public static string EditIsolationSchemeDlg_GetIsolationWindows_Overlap_requires_an_even_number_of_windows_ {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_GetIsolationWindows_Overlap_requires_an_even_number_of_win" +
"dows_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed reading isolation scheme..
/// </summary>
public static string EditIsolationSchemeDlg_ImportRangesFromFiles_Failed_reading_isolation_scheme_ {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_ImportRangesFromFiles_Failed_reading_isolation_scheme_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reading isolation scheme....
/// </summary>
public static string EditIsolationSchemeDlg_ImportRangesFromFiles_Reading_isolation_scheme___ {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_ImportRangesFromFiles_Reading_isolation_scheme___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Specify {0} for isolation window..
/// </summary>
public static string EditIsolationSchemeDlg_OkDialog_Specify__0__for_isolation_window {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_OkDialog_Specify__0__for_isolation_window", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Specify Start and End values for at least one isolation window..
/// </summary>
public static string EditIsolationSchemeDlg_OkDialog_Specify_Start_and_End_values_for_at_least_one_isolation_window {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_OkDialog_Specify_Start_and_End_values_for_at_least_one_iso" +
"lation_window", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The isolation scheme named '{0}' already exists..
/// </summary>
public static string EditIsolationSchemeDlg_OkDialog_The_isolation_scheme_named__0__already_exists {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_OkDialog_The_isolation_scheme_named__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The selected target is not unique..
/// </summary>
public static string EditIsolationSchemeDlg_OkDialog_The_selected_target_is_not_unique {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_OkDialog_The_selected_target_is_not_unique", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There are gaps in a single cycle of your extraction windows. Are you sure you want to continue?.
/// </summary>
public static string EditIsolationSchemeDlg_OkDialog_There_are_gaps_in_a_single_cycle_of_your_extraction_windows__Do_you_want_to_continue_ {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_OkDialog_There_are_gaps_in_a_single_cycle_of_your_extracti" +
"on_windows__Do_you_want_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Multiplex graphing is not supported..
/// </summary>
public static string EditIsolationSchemeDlg_OpenGraph_Graphing_multiplexing_is_not_supported_ {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_OpenGraph_Graphing_multiplexing_is_not_supported_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing isolation range for the isolation target {0} m/z in the file {1}.
/// </summary>
public static string EditIsolationSchemeDlg_ReadIsolationRanges_Missing_isolation_range_for_the_isolation_target__0__m_z_in_the_file__1_ {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_ReadIsolationRanges_Missing_isolation_range_for_the_isolat" +
"ion_target__0__m_z_in_the_file__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No repeating isolation scheme found in {0}.
/// </summary>
public static string EditIsolationSchemeDlg_ReadIsolationRanges_No_repeating_isolation_scheme_found_in__0_ {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_ReadIsolationRanges_No_repeating_isolation_scheme_found_in" +
"__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation &width:.
/// </summary>
public static string EditIsolationSchemeDlg_UpdateIsolationWidths_Isolation_width {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_UpdateIsolationWidths_Isolation_width", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation &widths:.
/// </summary>
public static string EditIsolationSchemeDlg_UpdateIsolationWidths_Isolation_widths {
get {
return ResourceManager.GetString("EditIsolationSchemeDlg_UpdateIsolationWidths_Isolation_widths", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There are overlaps in a single cycle of your extraction windows. Are you sure you want to continue?.
/// </summary>
public static string EditIsolationSchemeDlgOkDialogThereAreOverlapsContinue {
get {
return ResourceManager.GetString("EditIsolationSchemeDlgOkDialogThereAreOverlapsContinue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The isotope enrichments named '{0}' already exist..
/// </summary>
public static string EditIsotopeEnrichmentDlg_OkDialog_The_isotope_enrichments_named__0__already_exist {
get {
return ResourceManager.GetString("EditIsotopeEnrichmentDlg_OkDialog_The_isotope_enrichments_named__0__already_exist" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The entry {0} is not valid..
/// </summary>
public static string EditIsotopeEnrichmentDlg_ValidateCell_The_entry__0__is_not_valid {
get {
return ResourceManager.GetString("EditIsotopeEnrichmentDlg_ValidateCell_The_entry__0__is_not_valid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The enrichment {0} must be between {1} and {2}..
/// </summary>
public static string EditIsotopeEnrichmentDlg_ValidateEnrichment_The_enrichment__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("EditIsotopeEnrichmentDlg_ValidateEnrichment_The_enrichment__0__must_be_between__1" +
"__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The label name '{0}' may not be used more than once..
/// </summary>
public static string EditLabelTypeListDlg_OkDialog_The_label_name__0__may_not_be_used_more_than_once {
get {
return ResourceManager.GetString("EditLabelTypeListDlg_OkDialog_The_label_name__0__may_not_be_used_more_than_once", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The label names '{0}' and '{1}' conflict. Use more unique names..
/// </summary>
public static string EditLabelTypeListDlg_OkDialog_The_label_names__0__and__1__conflict_Use_more_unique_names {
get {
return ResourceManager.GetString("EditLabelTypeListDlg_OkDialog_The_label_names__0__and__1__conflict_Use_more_uniqu" +
"e_names", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The name '{0}' conflicts with the default light isotope label type..
/// </summary>
public static string EditLabelTypeListDlg_OkDialog_The_name__0__conflicts_with_the_default_light_isotope_label_type {
get {
return ResourceManager.GetString("EditLabelTypeListDlg_OkDialog_The_name__0__conflicts_with_the_default_light_isoto" +
"pe_label_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Legacy Libraries.
/// </summary>
public static string EditLibraryDlg_GetLibraryPath_Legacy_Libraries {
get {
return ResourceManager.GetString("EditLibraryDlg_GetLibraryPath_Legacy_Libraries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Spectral Libraries.
/// </summary>
public static string EditLibraryDlg_GetLibraryPath_Spectral_Libraries {
get {
return ResourceManager.GetString("EditLibraryDlg_GetLibraryPath_Spectral_Libraries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading chromatogram library.
/// </summary>
public static string EditLibraryDlg_OkDialog_Loading_chromatogram_library {
get {
return ResourceManager.GetString("EditLibraryDlg_OkDialog_Loading_chromatogram_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please choose a non-redundant library..
/// </summary>
public static string EditLibraryDlg_OkDialog_Please_choose_a_non_redundant_library {
get {
return ResourceManager.GetString("EditLibraryDlg_OkDialog_Please_choose_a_non_redundant_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} appears to be a redundant library..
/// </summary>
public static string EditLibraryDlg_OkDialog_The_file__0__appears_to_be_a_redundant_library {
get {
return ResourceManager.GetString("EditLibraryDlg_OkDialog_The_file__0__appears_to_be_a_redundant_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not exist..
/// </summary>
public static string EditLibraryDlg_OkDialog_The_file__0__does_not_exist {
get {
return ResourceManager.GetString("EditLibraryDlg_OkDialog_The_file__0__does_not_exist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} is not a supported spectral library file format..
/// </summary>
public static string EditLibraryDlg_OkDialog_The_file__0__is_not_a_supported_spectral_library_file_format {
get {
return ResourceManager.GetString("EditLibraryDlg_OkDialog_The_file__0__is_not_a_supported_spectral_library_file_for" +
"mat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The library '{0}' already exists..
/// </summary>
public static string EditLibraryDlg_OkDialog_The_library__0__already_exists {
get {
return ResourceManager.GetString("EditLibraryDlg_OkDialog_The_library__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The path {0} is a directory..
/// </summary>
public static string EditLibraryDlg_OkDialog_The_path__0__is_a_directory {
get {
return ResourceManager.GetString("EditLibraryDlg_OkDialog_The_path__0__is_a_directory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap EditLink {
get {
object obj = ResourceManager.GetObject("EditLink", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to The crosslinker '{0}' cannot attach to the amino acid '{1}'..
/// </summary>
public static string EditLinkedPeptideDlg_TryMakeLinkedPeptide_The_crosslinker___0___cannot_attach_to_the_amino_acid___1___ {
get {
return ResourceManager.GetString("EditLinkedPeptideDlg_TryMakeLinkedPeptide_The_crosslinker___0___cannot_attach_to_" +
"the_amino_acid___1___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Modifications.
/// </summary>
public static string EditLinkedPeptidesDlg_dataGridViewLinkedPeptides_CellToolTipTextNeeded_Edit_Modifications {
get {
return ResourceManager.GetString("EditLinkedPeptidesDlg_dataGridViewLinkedPeptides_CellToolTipTextNeeded_Edit_Modif" +
"ications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Both ends of this crosslink cannot be the same..
/// </summary>
public static string EditLinkedPeptidesDlg_MakeCrosslink_Both_ends_of_this_crosslink_cannot_be_the_same_ {
get {
return ResourceManager.GetString("EditLinkedPeptidesDlg_MakeCrosslink_Both_ends_of_this_crosslink_cannot_be_the_sam" +
"e_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid crosslinker.
/// </summary>
public static string EditLinkedPeptidesDlg_MakeCrosslink_Invalid_crosslinker {
get {
return ResourceManager.GetString("EditLinkedPeptidesDlg_MakeCrosslink_Invalid_crosslinker", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The crosslinker '{0}' cannot attach to this amino acid position..
/// </summary>
public static string EditLinkedPeptidesDlg_MakeCrosslink_The_crosslinker___0___cannot_attach_to_this_amino_acid_position_ {
get {
return ResourceManager.GetString("EditLinkedPeptidesDlg_MakeCrosslink_The_crosslinker___0___cannot_attach_to_this_a" +
"mino_acid_position_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This amino acid position cannot be blank..
/// </summary>
public static string EditLinkedPeptidesDlg_MakeCrosslink_This_amino_acid_position_cannot_be_blank_ {
get {
return ResourceManager.GetString("EditLinkedPeptidesDlg_MakeCrosslink_This_amino_acid_position_cannot_be_blank_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This amino acid position in this peptide is already being used by another crosslink..
/// </summary>
public static string EditLinkedPeptidesDlg_MakeCrosslink_This_amino_acid_position_in_this_peptide_is_already_being_used_by_another_crosslink_ {
get {
return ResourceManager.GetString("EditLinkedPeptidesDlg_MakeCrosslink_This_amino_acid_position_in_this_peptide_is_a" +
"lready_being_used_by_another_crosslink_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This is not a valid amino acid position in this peptide..
/// </summary>
public static string EditLinkedPeptidesDlg_MakeCrosslink_This_is_not_a_valid_amino_acid_position_in_this_peptide_ {
get {
return ResourceManager.GetString("EditLinkedPeptidesDlg_MakeCrosslink_This_is_not_a_valid_amino_acid_position_in_th" +
"is_peptide_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This peptide is not valid..
/// </summary>
public static string EditLinkedPeptidesDlg_MakeCrosslink_This_peptide_is_not_valid_ {
get {
return ResourceManager.GetString("EditLinkedPeptidesDlg_MakeCrosslink_This_peptide_is_not_valid_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Some crosslinked peptides are not connected..
/// </summary>
public static string EditLinkedPeptidesDlg_OkDialog_Some_crosslinked_peptides_are_not_connected_ {
get {
return ResourceManager.GetString("EditLinkedPeptidesDlg_OkDialog_Some_crosslinked_peptides_are_not_connected_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This will reset the list to its default values. Continue?.
/// </summary>
public static string EditListDlg_btnReset_Click_This_will_reset_the_list_to_its_default_values_Continue {
get {
return ResourceManager.GetString("EditListDlg_btnReset_Click_This_will_reset_the_list_to_its_default_values_Continu" +
"e", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Monoisotopic mass:.
/// </summary>
public static string EditMeasuredIonDlg_EditMeasuredIonDlg__Monoisotopic_mass_ {
get {
return ResourceManager.GetString("EditMeasuredIonDlg_EditMeasuredIonDlg__Monoisotopic_mass_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A&verage mass:.
/// </summary>
public static string EditMeasuredIonDlg_EditMeasuredIonDlg_A_verage_mass_ {
get {
return ResourceManager.GetString("EditMeasuredIonDlg_EditMeasuredIonDlg_A_verage_mass_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ion &chemical formula:.
/// </summary>
public static string EditMeasuredIonDlg_EditMeasuredIonDlg_Ion__chemical_formula_ {
get {
return ResourceManager.GetString("EditMeasuredIonDlg_EditMeasuredIonDlg_Ion__chemical_formula_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please specify a formula or constant masses..
/// </summary>
public static string EditMeasuredIonDlg_OkDialog_Please_specify_a_formula_or_constant_masses {
get {
return ResourceManager.GetString("EditMeasuredIonDlg_OkDialog_Please_specify_a_formula_or_constant_masses", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reporter ion masses must be greater than or equal to {0}..
/// </summary>
public static string EditMeasuredIonDlg_OkDialog_Reporter_ion_masses_must_be_greater_than_or_equal_to__0__ {
get {
return ResourceManager.GetString("EditMeasuredIonDlg_OkDialog_Reporter_ion_masses_must_be_greater_than_or_equal_to_" +
"_0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reporter ion masses must be less than or equal to {0}..
/// </summary>
public static string EditMeasuredIonDlg_OkDialog_Reporter_ion_masses_must_be_less_than_or_equal_to__0__ {
get {
return ResourceManager.GetString("EditMeasuredIonDlg_OkDialog_Reporter_ion_masses_must_be_less_than_or_equal_to__0_" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The special ion '{0}' already exists..
/// </summary>
public static string EditMeasuredIonDlg_OkDialog_The_special_ion__0__already_exists {
get {
return ResourceManager.GetString("EditMeasuredIonDlg_OkDialog_The_special_ion__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must contain at least one amino acid..
/// </summary>
public static string EditMeasuredIonDlg_ValidateAATextBox__0__must_contain_at_least_one_amino_acid {
get {
return ResourceManager.GetString("EditMeasuredIonDlg_ValidateAATextBox__0__must_contain_at_least_one_amino_acid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The character '{0}' is not a valid amino acid..
/// </summary>
public static string EditMeasuredIonDlg_ValidateAATextBox_The_character__0__is_not_a_valid_amino_acid {
get {
return ResourceManager.GetString("EditMeasuredIonDlg_ValidateAATextBox_The_character__0__is_not_a_valid_amino_acid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to create a new optimization library file? Any changes to the current library will be lost..
/// </summary>
public static string EditOptimizationLibraryDlg_btnCreate_Click_Are_you_sure_you_want_to_create_a_new_optimization_library_file__Any_changes_to_the_current_library_will_be_lost_ {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_btnCreate_Click_Are_you_sure_you_want_to_create_a_new_" +
"optimization_library_file__Any_changes_to_the_current_library_will_be_lost_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Create Optimization Library.
/// </summary>
public static string EditOptimizationLibraryDlg_btnCreate_Click_Create_Optimization_Library {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_btnCreate_Click_Create_Optimization_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to open a new optimization library file? Any changes to the current library will be lost..
/// </summary>
public static string EditOptimizationLibraryDlg_btnOpen_Click_Are_you_sure_you_want_to_open_a_new_optimization_library_file__Any_changes_to_the_current_library_will_be_lost_ {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_btnOpen_Click_Are_you_sure_you_want_to_open_a_new_opti" +
"mization_library_file__Any_changes_to_the_current_library_will_be_lost_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Open Optimization Library.
/// </summary>
public static string EditOptimizationLibraryDlg_btnOpen_Click_Open_Optimization_Library {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_btnOpen_Click_Open_Optimization_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} could not be created..
/// </summary>
public static string EditOptimizationLibraryDlg_CreateDatabase_The_file__0__could_not_be_created_ {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_CreateDatabase_The_file__0__could_not_be_created_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A library with the name {0} already exists. Do you want to overwrite it?.
/// </summary>
public static string EditOptimizationLibraryDlg_OkDialog_A_library_with_the_name__0__already_exists__Do_you_want_to_overwrite_it_ {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_OkDialog_A_library_with_the_name__0__already_exists__D" +
"o_you_want_to_overwrite_it_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Click the Create button to create a new library or the Open button to open an existing library file..
/// </summary>
public static string EditOptimizationLibraryDlg_OkDialog_Click_the_Create_button_to_create_a_new_library_or_the_Open_button_to_open_an_existing_library_file_ {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_OkDialog_Click_the_Create_button_to_create_a_new_libra" +
"ry_or_the_Open_button_to_open_an_existing_library_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure updating optimizations in the optimization library. The database may be out of synch..
/// </summary>
public static string EditOptimizationLibraryDlg_OkDialog_Failure_updating_optimizations_in_the_optimization_library__The_database_may_be_out_of_synch_ {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_OkDialog_Failure_updating_optimizations_in_the_optimiz" +
"ation_library__The_database_may_be_out_of_synch_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to library.
/// </summary>
public static string EditOptimizationLibraryDlg_OkDialog_library {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_OkDialog_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please choose a library file for the optimization library..
/// </summary>
public static string EditOptimizationLibraryDlg_OkDialog_Please_choose_a_library_file_for_the_optimization_library_ {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_OkDialog_Please_choose_a_library_file_for_the_optimiza" +
"tion_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please enter a name for the optimization library..
/// </summary>
public static string EditOptimizationLibraryDlg_OkDialog_Please_enter_a_name_for_the_optimization_library_ {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_OkDialog_Please_enter_a_name_for_the_optimization_libr" +
"ary_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please use a full path to a library file for the optimization library..
/// </summary>
public static string EditOptimizationLibraryDlg_OkDialog_Please_use_a_full_path_to_a_library_file_for_the_optimization_library_ {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_OkDialog_Please_use_a_full_path_to_a_library_file_for_" +
"the_optimization_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not exist. Click the Create button to create a new library or the Open button to find the missing file..
/// </summary>
public static string EditOptimizationLibraryDlg_OpenDatabase_The_file__0__does_not_exist__Click_the_Create_button_to_create_a_new_library_or_the_Open_button_to_find_the_missing_file_ {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_OpenDatabase_The_file__0__does_not_exist__Click_the_Cr" +
"eate_button_to_create_a_new_library_or_the_Open_button_to_find_the_missing_file_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} optimized collision energies.
/// </summary>
public static string EditOptimizationLibraryDlg_UpdateNumOptimizations__0__optimized_collision_energies {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_UpdateNumOptimizations__0__optimized_collision_energie" +
"s", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} optimized collision energy.
/// </summary>
public static string EditOptimizationLibraryDlg_UpdateNumOptimizations__0__optimized_collision_energy {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_UpdateNumOptimizations__0__optimized_collision_energy", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} optimized compensation voltage.
/// </summary>
public static string EditOptimizationLibraryDlg_UpdateNumOptimizations__0__optimized_compensation_voltage {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_UpdateNumOptimizations__0__optimized_compensation_volt" +
"age", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} optimized compensation voltages.
/// </summary>
public static string EditOptimizationLibraryDlg_UpdateNumOptimizations__0__optimized_compensation_voltages {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_UpdateNumOptimizations__0__optimized_compensation_volt" +
"ages", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} optimized declustering potential.
/// </summary>
public static string EditOptimizationLibraryDlg_UpdateNumOptimizations__0__optimized_declustering_potential {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_UpdateNumOptimizations__0__optimized_declustering_pote" +
"ntial", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} optimized declustering potentials.
/// </summary>
public static string EditOptimizationLibraryDlg_UpdateNumOptimizations__0__optimized_declustering_potentials {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_UpdateNumOptimizations__0__optimized_declustering_pote" +
"ntials", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collision Energy.
/// </summary>
public static string EditOptimizationLibraryDlg_UpdateValueHeader_Collision_Energy {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_UpdateValueHeader_Collision_Energy", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Declustering Potential.
/// </summary>
public static string EditOptimizationLibraryDlg_UpdateValueHeader_Declustering_Potential {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_UpdateValueHeader_Declustering_Potential", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The optimization with sequence {0}, charge {1}, fragment ion {2}, and product charge {3} appears in the {4} table more than once..
/// </summary>
public static string EditOptimizationLibraryDlg_ValidateOptimizationList_The_optimization_with_sequence__0___charge__1___fragment_ion__2__and_product_charge__3__appears_in_the__4__table_more_than_once_ {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_ValidateOptimizationList_The_optimization_with_sequenc" +
"e__0___charge__1___fragment_ion__2__and_product_charge__3__appears_in_the__4__ta" +
"ble_more_than_once_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value {0} is not a valid modified peptide sequence..
/// </summary>
public static string EditOptimizationLibraryDlg_ValidateOptimizationList_The_value__0__is_not_a_valid_modified_peptide_sequence_ {
get {
return ResourceManager.GetString("EditOptimizationLibraryDlg_ValidateOptimizationList_The_value__0__is_not_a_valid_" +
"modified_peptide_sequence_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot train model without either decoys or second best peaks included..
/// </summary>
public static string EditPeakScoringModelDlg_btnTrainModel_Click_Cannot_train_model_without_either_decoys_or_second_best_peaks_included_ {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_btnTrainModel_Click_Cannot_train_model_without_either_dec" +
"oys_or_second_best_peaks_included_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed training the model:.
/// </summary>
public static string EditPeakScoringModelDlg_btnTrainModel_Click_Failed_training_the_model_ {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_btnTrainModel_Click_Failed_training_the_model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Composite Score (Normalized).
/// </summary>
public static string EditPeakScoringModelDlg_EditPeakScoringModelDlg_Composite_Score__Normalized_ {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_EditPeakScoringModelDlg_Composite_Score__Normalized_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to P Value.
/// </summary>
public static string EditPeakScoringModelDlg_EditPeakScoringModelDlg_P_Value {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_EditPeakScoringModelDlg_P_Value", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Q value.
/// </summary>
public static string EditPeakScoringModelDlg_EditPeakScoringModelDlg_Q_value {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_EditPeakScoringModelDlg_Q_value", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Train a model to see composite score.
/// </summary>
public static string EditPeakScoringModelDlg_EditPeakScoringModelDlg_Train_a_model_to_see_composite_score {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_EditPeakScoringModelDlg_Train_a_model_to_see_composite_sc" +
"ore", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Train a model to see P value distribution.
/// </summary>
public static string EditPeakScoringModelDlg_EditPeakScoringModelDlg_Train_a_model_to_see_P_value_distribution {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_EditPeakScoringModelDlg_Train_a_model_to_see_P_value_dist" +
"ribution", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Train a model to see Q value distribution.
/// </summary>
public static string EditPeakScoringModelDlg_EditPeakScoringModelDlg_Train_a_model_to_see_Q_value_distribution {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_EditPeakScoringModelDlg_Train_a_model_to_see_Q_value_dist" +
"ribution", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak count.
/// </summary>
public static string EditPeakScoringModelDlg_InitGraphPane_Peak_count {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_InitGraphPane_Peak_count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Score.
/// </summary>
public static string EditPeakScoringModelDlg_InitGraphPane_Score {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_InitGraphPane_Score", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peak scoring model {0} already exists.
/// </summary>
public static string EditPeakScoringModelDlg_OkDialog_The_peak_scoring_model__0__already_exists {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_OkDialog_The_peak_scoring_model__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected Coefficient Sign.
/// </summary>
public static string EditPeakScoringModelDlg_OnDataBindingComplete_Unexpected_Coefficient_Sign {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_OnDataBindingComplete_Unexpected_Coefficient_Sign", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid model selection..
/// </summary>
public static string EditPeakScoringModelDlg_SelectedModelItem_Invalid_Model_Selection {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_SelectedModelItem_Invalid_Model_Selection", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculating.
/// </summary>
public static string EditPeakScoringModelDlg_TrainModel_Calculating {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_TrainModel_Calculating", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculating score contributions.
/// </summary>
public static string EditPeakScoringModelDlg_TrainModel_Calculating_score_contributions {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_TrainModel_Calculating_score_contributions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There are no decoy peptides in the current document. Uncheck the Use Decoys Box..
/// </summary>
public static string EditPeakScoringModelDlg_TrainModel_There_are_no_decoy_peptides_in_the_current_document__Uncheck_the_Use_Decoys_Box_ {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_TrainModel_There_are_no_decoy_peptides_in_the_current_doc" +
"ument__Uncheck_the_Use_Decoys_Box_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Training.
/// </summary>
public static string EditPeakScoringModelDlg_TrainModel_Training {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_TrainModel_Training", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scoring.
/// </summary>
public static string EditPeakScoringModelDlg_TrainModelClick_Scoring {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_TrainModelClick_Scoring", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to unknown.
/// </summary>
public static string EditPeakScoringModelDlg_UpdateCalculatorGraph_unknown {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_UpdateCalculatorGraph_unknown", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Combined normal distribution.
/// </summary>
public static string EditPeakScoringModelDlg_UpdateModelGraph_Combined_normal_distribution {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_UpdateModelGraph_Combined_normal_distribution", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Decoy normal distribution.
/// </summary>
public static string EditPeakScoringModelDlg_UpdateModelGraph_Decoy_normal_distribution {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_UpdateModelGraph_Decoy_normal_distribution", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Decoys.
/// </summary>
public static string EditPeakScoringModelDlg_UpdateModelGraph_Decoys {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_UpdateModelGraph_Decoys", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to P values of target peptides.
/// </summary>
public static string EditPeakScoringModelDlg_UpdateModelGraph_P_values_of_target_peptides {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_UpdateModelGraph_P_values_of_target_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Pi zero (expected nulls).
/// </summary>
public static string EditPeakScoringModelDlg_UpdateModelGraph_Pi_zero__expected_nulls_ {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_UpdateModelGraph_Pi_zero__expected_nulls_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Second best peaks.
/// </summary>
public static string EditPeakScoringModelDlg_UpdateModelGraph_Second_best_peaks {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_UpdateModelGraph_Second_best_peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Second best peaks normal distribution.
/// </summary>
public static string EditPeakScoringModelDlg_UpdateModelGraph_Second_best_peaks_normal_distribution {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_UpdateModelGraph_Second_best_peaks_normal_distribution", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Targets.
/// </summary>
public static string EditPeakScoringModelDlg_UpdateModelGraph_Targets {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_UpdateModelGraph_Targets", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Trained model is not applicable to current dataset..
/// </summary>
public static string EditPeakScoringModelDlg_UpdateModelGraph_Trained_model_is_not_applicable_to_current_dataset_ {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_UpdateModelGraph_Trained_model_is_not_applicable_to_curre" +
"nt_dataset_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Q values of target peptides.
/// </summary>
public static string EditPeakScoringModelDlg_UpdateQValueGraph_Q_values_of_target_peptides {
get {
return ResourceManager.GetString("EditPeakScoringModelDlg_UpdateQValueGraph_Q_values_of_target_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Discard.
/// </summary>
public static string EditPepModsDlg_EnsureLinkedPeptide_ButtonText_Discard {
get {
return ResourceManager.GetString("EditPepModsDlg_EnsureLinkedPeptide_ButtonText_Discard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Crosslinks.
/// </summary>
public static string EditPepModsDlg_EnsureLinkedPeptide_ButtonText_Edit_Crosslinks {
get {
return ResourceManager.GetString("EditPepModsDlg_EnsureLinkedPeptide_ButtonText_Edit_Crosslinks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removing the crosslink on this amino acid will result in a crosslinked peptide no longer being connected. Would you like to edit the crosslinks now or discard the disconnected peptides?.
/// </summary>
public static string EditPepModsDlg_EnsureLinkedPeptide_Discard_or_edit_disconnected_crosslinks {
get {
return ResourceManager.GetString("EditPepModsDlg_EnsureLinkedPeptide_Discard_or_edit_disconnected_crosslinks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isotope {0}:.
/// </summary>
public static string EditPepModsDlg_GetIsotopeLabelText_Isotope__0__ {
get {
return ResourceManager.GetString("EditPepModsDlg_GetIsotopeLabelText_Isotope__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Crosslink to {0}: {1} [{2}].
/// </summary>
public static string EditPepModsDlg_GetTooltip_Crosslink_to__0____1____2__ {
get {
return ResourceManager.GetString("EditPepModsDlg_GetTooltip_Crosslink_to__0____1____2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid crosslink: {0}.
/// </summary>
public static string EditPepModsDlg_GetTooltip_Invalid_crosslink___0_ {
get {
return ResourceManager.GetString("EditPepModsDlg_GetTooltip_Invalid_crosslink___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Looplink: {0} [{1}].
/// </summary>
public static string EditPepModsDlg_GetTooltip_Looplink___0____1__ {
get {
return ResourceManager.GetString("EditPepModsDlg_GetTooltip_Looplink___0____1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to One or more of the crosslinked peptides are no longer attached to this peptide. .
/// </summary>
public static string EditPepModsDlg_OkDialog_One_or_more_of_the_crosslinked_peptides_are_no_longer_attached_to_this_peptide__ {
get {
return ResourceManager.GetString("EditPepModsDlg_OkDialog_One_or_more_of_the_crosslinked_peptides_are_no_longer_att" +
"ached_to_this_peptide__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error connecting to server: .
/// </summary>
public static string EditRemoteAccountDlg_TestSettings_Error_connecting_to_server__ {
get {
return ResourceManager.GetString("EditRemoteAccountDlg_TestSettings_Error_connecting_to_server__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Settings are correct.
/// </summary>
public static string EditRemoteAccountDlg_TestSettings_Settings_are_correct {
get {
return ResourceManager.GetString("EditRemoteAccountDlg_TestSettings_Settings_are_correct", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while trying to authenticate..
/// </summary>
public static string EditRemoteAccountDlg_TestUnifiAccount_An_error_occurred_while_trying_to_authenticate_ {
get {
return ResourceManager.GetString("EditRemoteAccountDlg_TestUnifiAccount_An_error_occurred_while_trying_to_authentic" +
"ate_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An exception occurred while trying to fetch the directory listing..
/// </summary>
public static string EditRemoteAccountDlg_TestUnifiAccount_An_exception_occurred_while_trying_to_fetch_the_directory_listing_ {
get {
return ResourceManager.GetString("EditRemoteAccountDlg_TestUnifiAccount_An_exception_occurred_while_trying_to_fetch" +
"_the_directory_listing_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid server URL..
/// </summary>
public static string EditRemoteAccountDlg_ValidateValues_Invalid_server_URL_ {
get {
return ResourceManager.GetString("EditRemoteAccountDlg_ValidateValues_Invalid_server_URL_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Server cannot be blank.
/// </summary>
public static string EditRemoteAccountDlg_ValidateValues_Server_cannot_be_blank {
get {
return ResourceManager.GetString("EditRemoteAccountDlg_ValidateValues_Server_cannot_be_blank", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Server URL must start with https:// or http://.
/// </summary>
public static string EditRemoteAccountDlg_ValidateValues_Server_URL_must_start_with_https____or_http___ {
get {
return ResourceManager.GetString("EditRemoteAccountDlg_ValidateValues_Server_URL_must_start_with_https____or_http__" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is already an account defined for the user {0} on the server {1}.
/// </summary>
public static string EditRemoteAccountDlg_ValidateValues_There_is_already_an_account_defined_for_the_user__0__on_the_server__1_ {
get {
return ResourceManager.GetString("EditRemoteAccountDlg_ValidateValues_There_is_already_an_account_defined_for_the_u" +
"ser__0__on_the_server__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Username cannot be blank.
/// </summary>
public static string EditRemoteAccountDlg_ValidateValues_Username_cannot_be_blank {
get {
return ResourceManager.GetString("EditRemoteAccountDlg_ValidateValues_Username_cannot_be_blank", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must be greater than 0..
/// </summary>
public static string EditRTDlg_OkDialog__0__must_be_greater_than_0 {
get {
return ResourceManager.GetString("EditRTDlg_OkDialog__0__must_be_greater_than_0", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention time prediction requires a calculator algorithm..
/// </summary>
public static string EditRTDlg_OkDialog_Retention_time_prediction_requires_a_calculator_algorithm {
get {
return ResourceManager.GetString("EditRTDlg_OkDialog_Retention_time_prediction_requires_a_calculator_algorithm", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The retention time regression '{0}' already exists..
/// </summary>
public static string EditRTDlg_OkDialog_The_retention_time_regression__0__already_exists {
get {
return ResourceManager.GetString("EditRTDlg_OkDialog_The_retention_time_regression__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ({0} peptides, R = {1}).
/// </summary>
public static string EditRTDlg_RecalcRegression__0__peptides_R__1__ {
get {
return ResourceManager.GetString("EditRTDlg_RecalcRegression__0__peptides_R__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to initialize the calculator {0}..
/// </summary>
public static string EditRTDlg_ShowGraph_An_error_occurred_attempting_to_initialize_the_calculator__0__ {
get {
return ResourceManager.GetString("EditRTDlg_ShowGraph_An_error_occurred_attempting_to_initialize_the_calculator__0_" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Initializing.
/// </summary>
public static string EditRTDlg_ShowGraph_Initializing {
get {
return ResourceManager.GetString("EditRTDlg_ShowGraph_Initializing", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Initializing {0} calculator.
/// </summary>
public static string EditRTDlg_ShowGraph_Initializing__0__calculator {
get {
return ResourceManager.GetString("EditRTDlg_ShowGraph_Initializing__0__calculator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measured Time.
/// </summary>
public static string EditRTDlg_ShowGraph_Measured_Time {
get {
return ResourceManager.GetString("EditRTDlg_ShowGraph_Measured_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention Times by Score.
/// </summary>
public static string EditRTDlg_ShowGraph_Retention_Times_by_Score {
get {
return ResourceManager.GetString("EditRTDlg_ShowGraph_Retention_Times_by_Score", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Calculate <<.
/// </summary>
public static string EditRTDlg_ShowPeptides_Calculate_Left {
get {
return ResourceManager.GetString("EditRTDlg_ShowPeptides_Calculate_Left", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Calculate >>.
/// </summary>
public static string EditRTDlg_ShowPeptides_Calculate_Right {
get {
return ResourceManager.GetString("EditRTDlg_ShowPeptides_Calculate_Right", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The {0} calculator cannot score any of the peptides..
/// </summary>
public static string EditRTDlg_UpdateCalculator_The__0__calculator_cannot_score_any_of_the_peptides {
get {
return ResourceManager.GetString("EditRTDlg_UpdateCalculator_The__0__calculator_cannot_score_any_of_the_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The calculator cannot be used to score peptides. Please check its settings..
/// </summary>
public static string EditRTDlg_UpdateCalculator_The_calculator_cannot_be_used_to_score_peptides_Please_check_its_settings {
get {
return ResourceManager.GetString("EditRTDlg_UpdateCalculator_The_calculator_cannot_be_used_to_score_peptides_Please" +
"_check_its_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The server '{0}' already exists..
/// </summary>
public static string EditServerDlg_OkDialog_The_server__0__already_exists_ {
get {
return ResourceManager.GetString("EditServerDlg_OkDialog_The_server__0__already_exists_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The server {0} is not a Panorama server..
/// </summary>
public static string EditServerDlg_OkDialog_The_server__0__is_not_a_Panorama_server {
get {
return ResourceManager.GetString("EditServerDlg_OkDialog_The_server__0__is_not_a_Panorama_server", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The text '{0}' is not a valid server name..
/// </summary>
public static string EditServerDlg_OkDialog_The_text__0__is_not_a_valid_server_name_ {
get {
return ResourceManager.GetString("EditServerDlg_OkDialog_The_text__0__is_not_a_valid_server_name_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The username and password could not be authenticated with the panorama server..
/// </summary>
public static string EditServerDlg_OkDialog_The_username_and_password_could_not_be_authenticated_with_the_panorama_server {
get {
return ResourceManager.GetString("EditServerDlg_OkDialog_The_username_and_password_could_not_be_authenticated_with_" +
"the_panorama_server", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown error connecting to the server {0}..
/// </summary>
public static string EditServerDlg_OkDialog_Unknown_error_connecting_to_the_server__0__ {
get {
return ResourceManager.GetString("EditServerDlg_OkDialog_Unknown_error_connecting_to_the_server__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Verifying server information..
/// </summary>
public static string EditServerDlg_OkDialog_Verifying_server_information {
get {
return ResourceManager.GetString("EditServerDlg_OkDialog_Verifying_server_information", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The server {0} does not exist..
/// </summary>
public static string EditServerDlg_VerifyServerInformation_The_server__0__does_not_exist {
get {
return ResourceManager.GetString("EditServerDlg_VerifyServerInformation_The_server__0__does_not_exist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Chemical formula:.
/// </summary>
public static string EditStaticModDlg_EditStaticModDlg_Chemical_formula_ {
get {
return ResourceManager.GetString("EditStaticModDlg_EditStaticModDlg_Chemical_formula_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Click 'Custom' to use the name '{0}'..
/// </summary>
public static string EditStaticModDlg_OkDialog_Click__Custom__to_use_the_name___0___ {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_Click__Custom__to_use_the_name___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Click 'Unimod' to use the name '{0}'..
/// </summary>
public static string EditStaticModDlg_OkDialog_Click__Unimod__to_use_the_name___0___ {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_Click__Unimod__to_use_the_name___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Continue?.
/// </summary>
public static string EditStaticModDlg_OkDialog_Continue {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_Continue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Custom.
/// </summary>
public static string EditStaticModDlg_OkDialog_Custom {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_Custom", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Labeled atoms on terminal modification are not valid..
/// </summary>
public static string EditStaticModDlg_OkDialog_Labeled_atoms_on_terminal_modification_are_not_valid {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_Labeled_atoms_on_terminal_modification_are_not_valid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The modification '{0}' already exists..
/// </summary>
public static string EditStaticModDlg_OkDialog_The_modification__0__already_exists {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_The_modification__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The variable checkbox only applies to precursor modification. Product ion losses are inherently variable..
/// </summary>
public static string EditStaticModDlg_OkDialog_The_variable_checkbox_only_applies_to_precursor_modification_Product_ion_losses_are_inherently_variable {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_The_variable_checkbox_only_applies_to_precursor_modific" +
"ation_Product_ion_losses_are_inherently_variable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is a Unimod modification with the same settings..
/// </summary>
public static string EditStaticModDlg_OkDialog_There_is_a_Unimod_modification_with_the_same_settings {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_There_is_a_Unimod_modification_with_the_same_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is an existing modification with the same settings:.
/// </summary>
public static string EditStaticModDlg_OkDialog_There_is_an_existing_modification_with_the_same_settings {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_There_is_an_existing_modification_with_the_same_setting" +
"s", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This modification does not match the Unimod specifications for '{0}'..
/// </summary>
public static string EditStaticModDlg_OkDialog_This_modification_does_not_match_the_Unimod_specifications_for___0___ {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_This_modification_does_not_match_the_Unimod_specificati" +
"ons_for___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unimod.
/// </summary>
public static string EditStaticModDlg_OkDialog_Unimod {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_Unimod", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use non-standard settings for this name?.
/// </summary>
public static string EditStaticModDlg_OkDialog_Use_non_standard_settings_for_this_name {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_Use_non_standard_settings_for_this_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Variable modifications must specify amino acid or terminus..
/// </summary>
public static string EditStaticModDlg_OkDialog_Variable_modifications_must_specify_amino_acid_or_terminus {
get {
return ResourceManager.GetString("EditStaticModDlg_OkDialog_Variable_modifications_must_specify_amino_acid_or_termi" +
"nus", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to '{0}' is not a recognized Unimod name..
/// </summary>
public static string EditStaticModDlg_SetModification___0___is_not_a_recognized_Unimod_name_ {
get {
return ResourceManager.GetString("EditStaticModDlg_SetModification___0___is_not_a_recognized_Unimod_name_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <Show all...>.
/// </summary>
public static string EditStaticModDlg_UpdateListAvailableMods_Show_all {
get {
return ResourceManager.GetString("EditStaticModDlg_UpdateListAvailableMods_Show_all", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <Show common...>.
/// </summary>
public static string EditStaticModDlg_UpdateListAvailableMods_Show_common {
get {
return ResourceManager.GetString("EditStaticModDlg_UpdateListAvailableMods_Show_common", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} is not a valid element locator..
/// </summary>
public static string ElementLocator_Parse__0__is_not_a_valid_element_locator_ {
get {
return ResourceManager.GetString("ElementLocator_Parse__0__is_not_a_valid_element_locator_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to End of text.
/// </summary>
public static string ElementLocator_ReadQuotedString_End_of_text {
get {
return ResourceManager.GetString("ElementLocator_ReadQuotedString_End_of_text", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} was unexpected in '{1}' at position {2}..
/// </summary>
public static string ElementLocator_UnexpectedException__0__was_unexpected_in___1___at_position__2__ {
get {
return ResourceManager.GetString("ElementLocator_UnexpectedException__0__was_unexpected_in___1___at_position__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap EmptyList {
get {
object obj = ResourceManager.GetObject("EmptyList", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to {0} new proteins.
/// </summary>
public static string EmptyProteinsDlg_EmptyProteinsDlg__0__new_proteins {
get {
return ResourceManager.GetString("EmptyProteinsDlg_EmptyProteinsDlg__0__new_proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 new protein.
/// </summary>
public static string EmptyProteinsDlg_EmptyProteinsDlg_1_new_protein {
get {
return ResourceManager.GetString("EmptyProteinsDlg_EmptyProteinsDlg_1_new_protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to EncyclopeDIA Libraries.
/// </summary>
public static string EncyclopediaLibrary_FILTER_ELIB_EncyclopeDIA_Libraries {
get {
return ResourceManager.GetString("EncyclopediaLibrary_FILTER_ELIB_EncyclopeDIA_Libraries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to EncyclopeDIA Library.
/// </summary>
public static string EncyclopediaSpec_FILTER_ELIB_EncyclopeDIA_Library {
get {
return ResourceManager.GetString("EncyclopediaSpec_FILTER_ELIB_EncyclopeDIA_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enzyme must have C-terminal cleavage to have C-terminal restrictions..
/// </summary>
public static string Enzyme_Validate_Enzyme_must_have_C_terminal_cleavage_to_have_C_terminal_restrictions_ {
get {
return ResourceManager.GetString("Enzyme_Validate_Enzyme_must_have_C_terminal_cleavage_to_have_C_terminal_restricti" +
"ons_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enzyme must have N-terminal cleavage to have N-terminal restrictions..
/// </summary>
public static string Enzyme_Validate_Enzyme_must_have_N_terminal_cleavage_to_have_N_terminal_restrictions_ {
get {
return ResourceManager.GetString("Enzyme_Validate_Enzyme_must_have_N_terminal_cleavage_to_have_N_terminal_restricti" +
"ons_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enzymes must have at least one cleavage point..
/// </summary>
public static string Enzyme_Validate_Enzymes_must_have_at_least_one_cleavage_point {
get {
return ResourceManager.GetString("Enzyme_Validate_Enzymes_must_have_at_least_one_cleavage_point", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to En&zymes:.
/// </summary>
public static string EnzymeList_Label_Enzymes {
get {
return ResourceManager.GetString("EnzymeList_Label_Enzymes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Enzymes.
/// </summary>
public static string EnzymeList_Title_Edit_Enzymes {
get {
return ResourceManager.GetString("EnzymeList_Title_Edit_Enzymes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Caused by --->.
/// </summary>
public static string ExceptionDialog_Caused_by_____ {
get {
return ResourceManager.GetString("ExceptionDialog_Caused_by_____", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Expand {
get {
object obj = ResourceManager.GetObject("Expand", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Invalid extended peptide format {0}.
/// </summary>
public static string ExPeptideRowReader_CalcTransitionInfo_Invalid_extended_peptide_format__0__ {
get {
return ResourceManager.GetString("ExPeptideRowReader_CalcTransitionInfo_Invalid_extended_peptide_format__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isotope labeled entry found without matching settings..
/// </summary>
public static string ExPeptideRowReader_Create_Isotope_labeled_entry_found_without_matching_settings {
get {
return ResourceManager.GetString("ExPeptideRowReader_Create_Isotope_labeled_entry_found_without_matching_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check the Modifications tab in Transition Settings..
/// </summary>
public static string ExPeptideRowReaderCreateCheck_the_Modifications_tab_in_Transition_Settings {
get {
return ResourceManager.GetString("ExPeptideRowReaderCreateCheck_the_Modifications_tab_in_Transition_Settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modification type {0} not found..
/// </summary>
public static string ExplicitMods_ChangeModifications_Modification_type__0__not_found {
get {
return ResourceManager.GetString("ExplicitMods_ChangeModifications_Modification_type__0__not_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to At least one chromatogram type must be selected..
/// </summary>
public static string ExportChromatogramDlg_OkDialog_At_least_one_chromatogram_type_must_be_selected {
get {
return ResourceManager.GetString("ExportChromatogramDlg_OkDialog_At_least_one_chromatogram_type_must_be_selected", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to At least one file must be selected.
/// </summary>
public static string ExportChromatogramDlg_OkDialog_At_least_one_file_must_be_selected {
get {
return ResourceManager.GetString("ExportChromatogramDlg_OkDialog_At_least_one_file_must_be_selected", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Chromatogram Export Files.
/// </summary>
public static string ExportChromatogramDlg_OkDialog_Chromatogram_Export_Files {
get {
return ResourceManager.GetString("ExportChromatogramDlg_OkDialog_Chromatogram_Export_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Export Chromatograms.
/// </summary>
public static string ExportChromatogramDlg_OkDialog_Export_Chromatogram {
get {
return ResourceManager.GetString("ExportChromatogramDlg_OkDialog_Export_Chromatogram", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting Chromatograms.
/// </summary>
public static string ExportChromatogramDlg_OkDialog_Exporting_Chromatograms {
get {
return ResourceManager.GetString("ExportChromatogramDlg_OkDialog_Exporting_Chromatograms", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed attempting to save chromatograms to {0}..
/// </summary>
public static string ExportChromatogramDlg_OkDialog_Failed_attempting_to_save_chromatograms_to__0__ {
get {
return ResourceManager.GetString("ExportChromatogramDlg_OkDialog_Failed_attempting_to_save_chromatograms_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to export..
/// </summary>
public static string ExportDlgProperties_PerformLongExport_An_error_occurred_attempting_to_export {
get {
return ResourceManager.GetString("ExportDlgProperties_PerformLongExport_An_error_occurred_attempting_to_export", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting Methods.
/// </summary>
public static string ExportDlgProperties_PerformLongExport_Exporting_Methods {
get {
return ResourceManager.GetString("ExportDlgProperties_PerformLongExport_Exporting_Methods", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to IsolationList.
/// </summary>
public static string ExportFileTypeExtension_LOCALIZED_VALUES_IsolationList {
get {
return ResourceManager.GetString("ExportFileTypeExtension_LOCALIZED_VALUES_IsolationList", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to List.
/// </summary>
public static string ExportFileTypeExtension_LOCALIZED_VALUES_List {
get {
return ResourceManager.GetString("ExportFileTypeExtension_LOCALIZED_VALUES_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Method.
/// </summary>
public static string ExportFileTypeExtension_LOCALIZED_VALUES_Method {
get {
return ResourceManager.GetString("ExportFileTypeExtension_LOCALIZED_VALUES_Method", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invariant.
/// </summary>
public static string ExportLiveReportDlg_ExportLiveReportDlg_Invariant {
get {
return ResourceManager.GetString("ExportLiveReportDlg_ExportLiveReportDlg_Invariant", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Preview: .
/// </summary>
public static string ExportLiveReportDlg_ShowPreview_Preview__ {
get {
return ResourceManager.GetString("ExportLiveReportDlg_ShowPreview_Preview__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Method.
/// </summary>
public static string ExportMethodDlg_btnBrowseTemplate_Click__0__Method {
get {
return ResourceManager.GetString("ExportMethodDlg_btnBrowseTemplate_Click__0__Method", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Method Template.
/// </summary>
public static string ExportMethodDlg_btnBrowseTemplate_Click_Method_Template {
get {
return ResourceManager.GetString("ExportMethodDlg_btnBrowseTemplate_Click_Method_Template", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The chosen folder does not appear to contain a Bruker TOF method template. The folder is expected to have a .m extension, and contain the file submethods.xml..
/// </summary>
public static string ExportMethodDlg_btnBrowseTemplate_Click_The_chosen_folder_does_not_appear_to_contain_a_Bruker_TOF_method_template___The_folder_is_expected_to_have_a__m_extension__and_contain_the_file_submethods_xml_ {
get {
return ResourceManager.GetString("ExportMethodDlg_btnBrowseTemplate_Click_The_chosen_folder_does_not_appear_to_cont" +
"ain_a_Bruker_TOF_method_template___The_folder_is_expected_to_have_a__m_extension" +
"__and_contain_the_file_submethods_xml_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The chosen folder does not appear to contain an Agilent QQQ method template. The folder is expected to have a .m extension, and contain the file qqqacqmethod.xsd..
/// </summary>
public static string ExportMethodDlg_btnBrowseTemplate_Click_The_chosen_folder_does_not_appear_to_contain_an_Agilent_QQQ_method_template_The_folder_is_expected_to_have_a_m_extension_and_contain_the_file_qqqacqmethod_xsd {
get {
return ResourceManager.GetString("ExportMethodDlg_btnBrowseTemplate_Click_The_chosen_folder_does_not_appear_to_cont" +
"ain_an_Agilent_QQQ_method_template_The_folder_is_expected_to_have_a_m_extension_" +
"and_contain_the_file_qqqacqmethod_xsd", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred..
/// </summary>
public static string ExportMethodDlg_btnGraph_Click_An_error_occurred_ {
get {
return ResourceManager.GetString("ExportMethodDlg_btnGraph_Click_An_error_occurred_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Grouping peptides by protein has not yet been implemented for scheduled methods..
/// </summary>
public static string ExportMethodDlg_cbIgnoreProteins_CheckedChanged_Grouping_peptides_by_protein_has_not_yet_been_implemented_for_scheduled_methods_ {
get {
return ResourceManager.GetString("ExportMethodDlg_cbIgnoreProteins_CheckedChanged_Grouping_peptides_by_protein_has_" +
"not_yet_been_implemented_for_scheduled_methods_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Export of DIA isolation lists is not yet supported for {0}..
/// </summary>
public static string ExportMethodDlg_comboInstrument_SelectedIndexChanged_Export_of_DIA_isolation_lists_is_not_yet_supported_for__0__ {
get {
return ResourceManager.GetString("ExportMethodDlg_comboInstrument_SelectedIndexChanged_Export_of_DIA_isolation_list" +
"s_is_not_yet_supported_for__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Export a method with extra transitions for finding an optimal value..
/// </summary>
public static string ExportMethodDlg_comboOptimizing_SelectedIndexChanged_Export_a_method_with_extra_transitions_for_finding_an_optimal_value_ {
get {
return ResourceManager.GetString("ExportMethodDlg_comboOptimizing_SelectedIndexChanged_Export_a_method_with_extra_t" +
"ransitions_for_finding_an_optimal_value_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Optimizing for {0} will produce an additional {1} transitions per transition..
/// </summary>
public static string ExportMethodDlg_comboOptimizing_SelectedIndexChanged_Optimizing_for__0__will_produce_an_additional__1__transitions_per_transition_ {
get {
return ResourceManager.GetString("ExportMethodDlg_comboOptimizing_SelectedIndexChanged_Optimizing_for__0__will_prod" +
"uce_an_additional__1__transitions_per_transition_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check the calculator settings..
/// </summary>
public static string ExportMethodDlg_comboTargetType_SelectedIndexChanged_Check_the_calculator_settings {
get {
return ResourceManager.GetString("ExportMethodDlg_comboTargetType_SelectedIndexChanged_Check_the_calculator_setting" +
"s", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check to make sure the document contains times for all of the required standard peptides..
/// </summary>
public static string ExportMethodDlg_comboTargetType_SelectedIndexChanged_Check_to_make_sure_the_document_contains_times_for_all_of_the_required_standard_peptides {
get {
return ResourceManager.GetString("ExportMethodDlg_comboTargetType_SelectedIndexChanged_Check_to_make_sure_the_docum" +
"ent_contains_times_for_all_of_the_required_standard_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention time prediction calculator is unable to score..
/// </summary>
public static string ExportMethodDlg_comboTargetType_SelectedIndexChanged_Retention_time_prediction_calculator_is_unable_to_score {
get {
return ResourceManager.GetString("ExportMethodDlg_comboTargetType_SelectedIndexChanged_Retention_time_prediction_ca" +
"lculator_is_unable_to_score", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention time predictor is unable to auto-calculate a regression..
/// </summary>
public static string ExportMethodDlg_comboTargetType_SelectedIndexChanged_Retention_time_predictor_is_unable_to_auto_calculate_a_regression {
get {
return ResourceManager.GetString("ExportMethodDlg_comboTargetType_SelectedIndexChanged_Retention_time_predictor_is_" +
"unable_to_auto_calculate_a_regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scheduled methods are not supported for the selected instrument..
/// </summary>
public static string ExportMethodDlg_comboTargetType_SelectedIndexChanged_Sched_Not_Supported_Err_Text {
get {
return ResourceManager.GetString("ExportMethodDlg_comboTargetType_SelectedIndexChanged_Sched_Not_Supported_Err_Text" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scheduled methods are not yet supported for DIA acquisition..
/// </summary>
public static string ExportMethodDlg_comboTargetType_SelectedIndexChanged_Scheduled_methods_are_not_yet_supported_for_DIA_acquisition {
get {
return ResourceManager.GetString("ExportMethodDlg_comboTargetType_SelectedIndexChanged_Scheduled_methods_are_not_ye" +
"t_supported_for_DIA_acquisition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to To export a scheduled method, you must first choose a retention time predictor in Peptide Settings / Prediction..
/// </summary>
public static string ExportMethodDlg_comboTargetType_SelectedIndexChanged_To_export_a_scheduled_list_you_must_first_choose_a_retention_time_predictor_in_Peptide_Settings_Prediction {
get {
return ResourceManager.GetString("ExportMethodDlg_comboTargetType_SelectedIndexChanged_To_export_a_scheduled_list_y" +
"ou_must_first_choose_a_retention_time_predictor_in_Peptide_Settings_Prediction", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to To export a scheduled method, you must first choose a retention time predictor in Peptide Settings / Prediction, or import results for all peptides in the document..
/// </summary>
public static string ExportMethodDlg_comboTargetType_SelectedIndexChanged_To_export_a_scheduled_list_you_must_first_choose_a_retention_time_predictor_in_Peptide_Settings_Prediction_or_import_results_for_all_peptides_in_the_document {
get {
return ResourceManager.GetString("ExportMethodDlg_comboTargetType_SelectedIndexChanged_To_export_a_scheduled_list_y" +
"ou_must_first_choose_a_retention_time_predictor_in_Peptide_Settings_Prediction_o" +
"r_import_results_for_all_peptides_in_the_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to To export a scheduled method, you must first import results for all peptides in the document..
/// </summary>
public static string ExportMethodDlg_comboTargetType_SelectedIndexChanged_To_export_a_scheduled_list_you_must_first_import_results_for_all_peptides_in_the_document {
get {
return ResourceManager.GetString("ExportMethodDlg_comboTargetType_SelectedIndexChanged_To_export_a_scheduled_list_y" +
"ou_must_first_import_results_for_all_peptides_in_the_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ma&x concurrent precursors:.
/// </summary>
public static string ExportMethodDlg_CONCUR_PREC_TXT {
get {
return ResourceManager.GetString("ExportMethodDlg_CONCUR_PREC_TXT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ma&x concurrent transitions:.
/// </summary>
public static string ExportMethodDlg_CONCUR_TRANS_TXT {
get {
return ResourceManager.GetString("ExportMethodDlg_CONCUR_TRANS_TXT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Dwell time (ms):.
/// </summary>
public static string ExportMethodDlg_DWELL_TIME_TXT {
get {
return ResourceManager.GetString("ExportMethodDlg_DWELL_TIME_TXT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Export Isolation List.
/// </summary>
public static string ExportMethodDlg_ExportMethodDlg_Export_Isolation_List {
get {
return ResourceManager.GetString("ExportMethodDlg_ExportMethodDlg_Export_Isolation_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Export Transition List.
/// </summary>
public static string ExportMethodDlg_ExportMethodDlg_Export_Transition_List {
get {
return ResourceManager.GetString("ExportMethodDlg_ExportMethodDlg_Export_Transition_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A template file is required to export a method..
/// </summary>
public static string ExportMethodDlg_OkDialog_A_template_file_is_required_to_export_a_method {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_A_template_file_is_required_to_export_a_method", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All targets must have an ion mobility value. These can be set explicitly or contained in an ion mobility library or spectral library. The following ion mobility values are missing:.
/// </summary>
public static string ExportMethodDlg_OkDialog_All_targets_must_have_an_ion_mobility_value__These_can_be_set_explicitly_or_contained_in_an_ion_mobility_library_or_spectral_library__The_following_ion_mobility_values_are_missing_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_All_targets_must_have_an_ion_mobility_value__These_can_b" +
"e_set_explicitly_or_contained_in_an_ion_mobility_library_or_spectral_library__Th" +
"e_following_ion_mobility_values_are_missing_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to continue?.
/// </summary>
public static string ExportMethodDlg_OkDialog_Are_you_sure_you_want_to_continue {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Are_you_sure_you_want_to_continue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to continue?.
/// </summary>
public static string ExportMethodDlg_OkDialog_Are_you_sure_you_want_to_continue_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Are_you_sure_you_want_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collision Energy:.
/// </summary>
public static string ExportMethodDlg_OkDialog_Collision_Energy {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Collision_Energy", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Compensation Voltage:.
/// </summary>
public static string ExportMethodDlg_OkDialog_Compensation_Voltage_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Compensation_Voltage_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Compensation voltage optimization should be run on one transition per precursor. The best transition could not be determined for the following precursors:.
/// </summary>
public static string ExportMethodDlg_OkDialog_Compensation_voltage_optimization_should_be_run_on_one_transition_per_peptide__and_the_best_transition_cannot_be_determined_for_the_following_precursors_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Compensation_voltage_optimization_should_be_run_on_one_t" +
"ransition_per_peptide__and_the_best_transition_cannot_be_determined_for_the_foll" +
"owing_precursors_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Decluster Potential:.
/// </summary>
public static string ExportMethodDlg_OkDialog_Declustering_Potential {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Declustering_Potential", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Export {0} Method.
/// </summary>
public static string ExportMethodDlg_OkDialog_Export__0__Method {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Export__0__Method", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Export of DIA method is not supported for {0}..
/// </summary>
public static string ExportMethodDlg_OkDialog_Export_of_DIA_method_is_not_supported_for__0__ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Export_of_DIA_method_is_not_supported_for__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation List.
/// </summary>
public static string ExportMethodDlg_OkDialog_Isolation_List {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Isolation_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Method File.
/// </summary>
public static string ExportMethodDlg_OkDialog_Method_File {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Method_File", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None.
/// </summary>
public static string ExportMethodDlg_OkDialog_None {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_None", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to OK.
/// </summary>
public static string ExportMethodDlg_OkDialog_OK {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_OK", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Orbitrap.
/// </summary>
public static string ExportMethodDlg_OkDialog_Orbitrap {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Orbitrap", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Provide transition ranking information through imported results, a spectral library, or choose only one target transition per precursor..
/// </summary>
public static string ExportMethodDlg_OkDialog_Provide_transition_ranking_information_through_imported_results__a_spectral_library__or_choose_only_one_target_transition_per_precursor_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Provide_transition_ranking_information_through_imported_" +
"results__a_spectral_library__or_choose_only_one_target_transition_per_precursor_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The DIA isolation list must have prespecified windows..
/// </summary>
public static string ExportMethodDlg_OkDialog_The_DIA_isolation_list_must_have_prespecified_windows_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_The_DIA_isolation_list_must_have_prespecified_windows_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document does not contain all of the retention time standard peptides..
/// </summary>
public static string ExportMethodDlg_OkDialog_The_document_does_not_contain_all_of_the_retention_time_standard_peptides {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_The_document_does_not_contain_all_of_the_retention_time_" +
"standard_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The folder {0} does not appear to contain a Bruker TOF method template. The folder is expected to have a .m extension, and contain the file submethods.xml..
/// </summary>
public static string ExportMethodDlg_OkDialog_The_folder__0__does_not_appear_to_contain_a_Bruker_TOF_method_template___The_folder_is_expected_to_have_a__m_extension__and_contain_the_file_submethods_xml_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_The_folder__0__does_not_appear_to_contain_a_Bruker_TOF_m" +
"ethod_template___The_folder_is_expected_to_have_a__m_extension__and_contain_the_" +
"file_submethods_xml_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The folder {0} does not appear to contain an Agilent QQQ method template. The folder is expected to have a .m extension, and contain the file qqqacqmethod.xsd..
/// </summary>
public static string ExportMethodDlg_OkDialog_The_folder__0__does_not_appear_to_contain_an_Agilent_QQQ_method_template_The_folder_is_expected_to_have_a_m_extension_and_contain_the_file_qqqacqmethod_xsd {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_The_folder__0__does_not_appear_to_contain_an_Agilent_QQQ" +
"_method_template_The_folder_is_expected_to_have_a_m_extension_and_contain_the_fi" +
"le_qqqacqmethod_xsd", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor mass analyzer type is not set to {0} in Transition Settings (under the Full Scan tab)..
/// </summary>
public static string ExportMethodDlg_OkDialog_The_precursor_mass_analyzer_type_is_not_set_to__0__in_Transition_Settings_under_the_Full_Scan_tab {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_The_precursor_mass_analyzer_type_is_not_set_to__0__in_Tr" +
"ansition_Settings_under_the_Full_Scan_tab", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The product mass analyzer type is not set to {0} in Transition Settings (under the Full Scan tab)..
/// </summary>
public static string ExportMethodDlg_OkDialog_The_product_mass_analyzer_type_is_not_set_to__0__in_Transition_Settings_under_the_Full_Scan_tab {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_The_product_mass_analyzer_type_is_not_set_to__0__in_Tran" +
"sition_Settings_under_the_Full_Scan_tab", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The settings for this document do not match the instrument type {0}:.
/// </summary>
public static string ExportMethodDlg_OkDialog_The_settings_for_this_document_do_not_match_the_instrument_type__0__ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_The_settings_for_this_document_do_not_match_the_instrume" +
"nt_type__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The template file {0} does not exist..
/// </summary>
public static string ExportMethodDlg_OkDialog_The_template_file__0__does_not_exist {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_The_template_file__0__does_not_exist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to TOF.
/// </summary>
public static string ExportMethodDlg_OkDialog_TOF {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_TOF", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition List.
/// </summary>
public static string ExportMethodDlg_OkDialog_Transition_List {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Transition_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Would you like to use the defaults instead?.
/// </summary>
public static string ExportMethodDlg_OkDialog_Would_you_like_to_use_the_defaults_instead {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Would_you_like_to_use_the_defaults_instead", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You are missing any optimized compensation voltages for the following:.
/// </summary>
public static string ExportMethodDlg_OkDialog_You_are_missing_any_optimized_compensation_voltages_for_the_following_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_You_are_missing_any_optimized_compensation_voltages_for_" +
"the_following_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You are missing compensation voltages for the following:.
/// </summary>
public static string ExportMethodDlg_OkDialog_You_are_missing_compensation_voltages_for_the_following_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_You_are_missing_compensation_voltages_for_the_following_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You are missing fine tune optimized compensation voltages..
/// </summary>
public static string ExportMethodDlg_OkDialog_You_are_missing_fine_tune_optimized_compensation_voltages_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_You_are_missing_fine_tune_optimized_compensation_voltage" +
"s_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You are missing fine tune optimized compensation voltages for the following:.
/// </summary>
public static string ExportMethodDlg_OkDialog_You_are_missing_fine_tune_optimized_compensation_voltages_for_the_following_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_You_are_missing_fine_tune_optimized_compensation_voltage" +
"s_for_the_following_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You are missing medium tune optimized compensation voltages for the following:.
/// </summary>
public static string ExportMethodDlg_OkDialog_You_are_missing_medium_tune_optimized_compensation_voltages_for_the_following_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_You_are_missing_medium_tune_optimized_compensation_volta" +
"ges_for_the_following_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You can set explicit compensation voltages for these, or add their values to a document optimization library in Transition Settings under the Prediction tab..
/// </summary>
public static string ExportMethodDlg_OkDialog_You_can_set_explicit_compensation_voltages_for_these__or_add_their_values_to_a_document_optimization_library_in_Transition_Settings_under_the_Prediction_tab_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_You_can_set_explicit_compensation_voltages_for_these__or" +
"_add_their_values_to_a_document_optimization_library_in_Transition_Settings_unde" +
"r_the_Prediction_tab_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You have only rough tune optimized compensation voltages..
/// </summary>
public static string ExportMethodDlg_OkDialog_You_have_only_rough_tune_optimized_compensation_voltages_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_You_have_only_rough_tune_optimized_compensation_voltages" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You will not be able to use retention time prediction with acquired results..
/// </summary>
public static string ExportMethodDlg_OkDialog_You_will_not_be_able_to_use_retention_time_prediction_with_acquired_results {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_You_will_not_be_able_to_use_retention_time_prediction_wi" +
"th_acquired_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Your document does not contain compensation voltage results, but compensation voltage is set under transition settings..
/// </summary>
public static string ExportMethodDlg_OkDialog_Your_document_does_not_contain_compensation_voltage_results__but_compensation_voltage_is_set_under_transition_settings_ {
get {
return ResourceManager.GetString("ExportMethodDlg_OkDialog_Your_document_does_not_contain_compensation_voltage_resu" +
"lts__but_compensation_voltage_is_set_under_transition_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ma&x precursors per sample injection:.
/// </summary>
public static string ExportMethodDlg_PREC_PER_SAMPLE_INJ_TXT {
get {
return ResourceManager.GetString("ExportMethodDlg_PREC_PER_SAMPLE_INJ_TXT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Run &duration (min):.
/// </summary>
public static string ExportMethodDlg_RUN_DURATION_TXT {
get {
return ResourceManager.GetString("ExportMethodDlg_RUN_DURATION_TXT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scheduled.
/// </summary>
public static string ExportMethodDlg_SetMethodType_Scheduled {
get {
return ResourceManager.GetString("ExportMethodDlg_SetMethodType_Scheduled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Standard.
/// </summary>
public static string ExportMethodDlg_SetMethodType_Standard {
get {
return ResourceManager.GetString("ExportMethodDlg_SetMethodType_Standard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Multiple methods is not yet supported for {0}..
/// </summary>
public static string ExportMethodDlg_StrategyCheckChanged_Multiple_methods_is_not_yet_supported_for__0__ {
get {
return ResourceManager.GetString("ExportMethodDlg_StrategyCheckChanged_Multiple_methods_is_not_yet_supported_for__0" +
"__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only one method can be exported in DIA mode..
/// </summary>
public static string ExportMethodDlg_StrategyCheckChanged_Only_one_method_can_be_exported_in_DIA_mode {
get {
return ResourceManager.GetString("ExportMethodDlg_StrategyCheckChanged_Only_one_method_can_be_exported_in_DIA_mode", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ma&x transitions per sample injection:.
/// </summary>
public static string ExportMethodDlg_TRANS_PER_SAMPLE_INJ_TXT {
get {
return ResourceManager.GetString("ExportMethodDlg_TRANS_PER_SAMPLE_INJ_TXT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor {0} for {1} has {2} transitions, which exceeds the current maximum {3}..
/// </summary>
public static string ExportMethodDlg_ValidatePrecursorFit_The_precursor__0__for__1__has__2__transitions__which_exceeds_the_current_maximum__3__ {
get {
return ResourceManager.GetString("ExportMethodDlg_ValidatePrecursorFit_The_precursor__0__for__1__has__2__transition" +
"s__which_exceeds_the_current_maximum__3__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor {0} for {1} requires {2} transitions to optimize, which exceeds the current maximum {3}..
/// </summary>
public static string ExportMethodDlg_ValidatePrecursorFit_The_precursor__0__for__1__requires__2__transitions_to_optimize__which_exceeds_the_current_maximum__3__ {
get {
return ResourceManager.GetString("ExportMethodDlg_ValidatePrecursorFit_The_precursor__0__for__1__requires__2__trans" +
"itions_to_optimize__which_exceeds_the_current_maximum__3__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must contain a value..
/// </summary>
public static string ExportMethodDlg_ValidateSettings__0__must_contain_a_value {
get {
return ResourceManager.GetString("ExportMethodDlg_ValidateSettings__0__must_contain_a_value", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot export fine tune transition list. The following precursors are missing medium tune results:.
/// </summary>
public static string ExportMethodDlg_ValidateSettings_Cannot_export_fine_tune_transition_list__The_following_precursors_are_missing_medium_tune_results_ {
get {
return ResourceManager.GetString("ExportMethodDlg_ValidateSettings_Cannot_export_fine_tune_transition_list__The_fol" +
"lowing_precursors_are_missing_medium_tune_results_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot export medium tune transition list. The following precursors are missing rough tune results:.
/// </summary>
public static string ExportMethodDlg_ValidateSettings_Cannot_export_medium_tune_transition_list__The_following_precursors_are_missing_rough_tune_results_ {
get {
return ResourceManager.GetString("ExportMethodDlg_ValidateSettings_Cannot_export_medium_tune_transition_list__The_f" +
"ollowing_precursors_are_missing_rough_tune_results_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The {0} instrument lacks support for direct method export for triggered acquisition..
/// </summary>
public static string ExportMethodDlg_VerifySchedulingAllowed_The__0__instrument_lacks_support_for_direct_method_export_for_triggered_acquisition_ {
get {
return ResourceManager.GetString("ExportMethodDlg_VerifySchedulingAllowed_The__0__instrument_lacks_support_for_dire" +
"ct_method_export_for_triggered_acquisition_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The current document contains peptides without enough information to rank transitions for triggered acquisition..
/// </summary>
public static string ExportMethodDlg_VerifySchedulingAllowed_The_current_document_contains_peptides_without_enough_information_to_rank_transitions_for_triggered_acquisition_ {
get {
return ResourceManager.GetString("ExportMethodDlg_VerifySchedulingAllowed_The_current_document_contains_peptides_wi" +
"thout_enough_information_to_rank_transitions_for_triggered_acquisition_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The instrument type {0} does not support triggered acquisition..
/// </summary>
public static string ExportMethodDlg_VerifySchedulingAllowed_The_instrument_type__0__does_not_support_triggered_acquisition_ {
get {
return ResourceManager.GetString("ExportMethodDlg_VerifySchedulingAllowed_The_instrument_type__0__does_not_support_" +
"triggered_acquisition_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Triggered acquistion requires a spectral library or imported results in order to rank transitions..
/// </summary>
public static string ExportMethodDlg_VerifySchedulingAllowed_Triggered_acquistion_requires_a_spectral_library_or_imported_results_in_order_to_rank_transitions_ {
get {
return ResourceManager.GetString("ExportMethodDlg_VerifySchedulingAllowed_Triggered_acquistion_requires_a_spectral_" +
"library_or_imported_results_in_order_to_rank_transitions_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must export a {0} transition list and manually import it into a method file using vendor software..
/// </summary>
public static string ExportMethodDlg_VerifySchedulingAllowed_You_must_export_a__0__transition_list_and_manually_import_it_into_a_method_file_using_vendor_software_ {
get {
return ResourceManager.GetString("ExportMethodDlg_VerifySchedulingAllowed_You_must_export_a__0__transition_list_and" +
"_manually_import_it_into_a_method_file_using_vendor_software_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Concurrent frames.
/// </summary>
public static string ExportMethodScheduleGraph_ExportMethodScheduleGraph_Concurrent_frames {
get {
return ResourceManager.GetString("ExportMethodScheduleGraph_ExportMethodScheduleGraph_Concurrent_frames", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Max sampling times.
/// </summary>
public static string ExportMethodScheduleGraph_ExportMethodScheduleGraph_Max_sampling_times {
get {
return ResourceManager.GetString("ExportMethodScheduleGraph_ExportMethodScheduleGraph_Max_sampling_times", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mean sampling times.
/// </summary>
public static string ExportMethodScheduleGraph_ExportMethodScheduleGraph_Mean_sampling_times {
get {
return ResourceManager.GetString("ExportMethodScheduleGraph_ExportMethodScheduleGraph_Mean_sampling_times", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Redundancy of targets.
/// </summary>
public static string ExportMethodScheduleGraph_ExportMethodScheduleGraph_Redundancy_of_targets {
get {
return ResourceManager.GetString("ExportMethodScheduleGraph_ExportMethodScheduleGraph_Redundancy_of_targets", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Target table.
/// </summary>
public static string ExportMethodScheduleGraph_ExportMethodScheduleGraph_Target_table {
get {
return ResourceManager.GetString("ExportMethodScheduleGraph_ExportMethodScheduleGraph_Target_table", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Targets per frame.
/// </summary>
public static string ExportMethodScheduleGraph_ExportMethodScheduleGraph_Targets_per_frame {
get {
return ResourceManager.GetString("ExportMethodScheduleGraph_ExportMethodScheduleGraph_Targets_per_frame", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scheduled.
/// </summary>
public static string ExportMethodTypeExtension_LOCALIZED_VALUES_Scheduled {
get {
return ResourceManager.GetString("ExportMethodTypeExtension_LOCALIZED_VALUES_Scheduled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Standard.
/// </summary>
public static string ExportMethodTypeExtension_LOCALIZED_VALUES_Standard {
get {
return ResourceManager.GetString("ExportMethodTypeExtension_LOCALIZED_VALUES_Standard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Triggered.
/// </summary>
public static string ExportMethodTypeExtension_LOCALIZED_VALUES_Triggered {
get {
return ResourceManager.GetString("ExportMethodTypeExtension_LOCALIZED_VALUES_Triggered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collision Energy.
/// </summary>
public static string ExportOptimize_CE_Collision_Energy {
get {
return ResourceManager.GetString("ExportOptimize_CE_Collision_Energy", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Compensation Voltage.
/// </summary>
public static string ExportOptimize_COV_Compensation_Voltage {
get {
return ResourceManager.GetString("ExportOptimize_COV_Compensation_Voltage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fine Tune.
/// </summary>
public static string ExportOptimize_COV_FINE_Fine_Tune {
get {
return ResourceManager.GetString("ExportOptimize_COV_FINE_Fine_Tune", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Medium Tune.
/// </summary>
public static string ExportOptimize_COV_MEDIUM_Medium_Tune {
get {
return ResourceManager.GetString("ExportOptimize_COV_MEDIUM_Medium_Tune", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Rough Tune.
/// </summary>
public static string ExportOptimize_COV_ROUGH_Rough_Tune {
get {
return ResourceManager.GetString("ExportOptimize_COV_ROUGH_Rough_Tune", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Declustering Potential.
/// </summary>
public static string ExportOptimize_DP_Declustering_Potential {
get {
return ResourceManager.GetString("ExportOptimize_DP_Declustering_Potential", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None.
/// </summary>
public static string ExportOptimize_NONE_None {
get {
return ResourceManager.GetString("ExportOptimize_NONE_None", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unrecognized instrument type {0}..
/// </summary>
public static string ExportProperties_ExportFile_Unrecognized_instrument_type__0__ {
get {
return ResourceManager.GetString("ExportProperties_ExportFile_Unrecognized_instrument_type__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Building report....
/// </summary>
public static string ExportReportDlg_ExportReport_Building_report {
get {
return ResourceManager.GetString("ExportReportDlg_ExportReport_Building_report", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed exporting to {0}.
///{1}.
/// </summary>
public static string ExportReportDlg_ExportReport_Failed_exporting_to {
get {
return ResourceManager.GetString("ExportReportDlg_ExportReport_Failed_exporting_to", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Generating Report.
/// </summary>
public static string ExportReportDlg_ExportReport_Generating_Report {
get {
return ResourceManager.GetString("ExportReportDlg_ExportReport_Generating_Report", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Writing report....
/// </summary>
public static string ExportReportDlg_ExportReport_Writing_report {
get {
return ResourceManager.GetString("ExportReportDlg_ExportReport_Writing_report", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Analyzing document....
/// </summary>
public static string ExportReportDlg_GetDatabase_Analyzing_document {
get {
return ResourceManager.GetString("ExportReportDlg_GetDatabase_Analyzing_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Generating Report Data.
/// </summary>
public static string ExportReportDlg_GetDatabase_Generating_Report_Data {
get {
return ResourceManager.GetString("ExportReportDlg_GetDatabase_Generating_Report_Data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The field {0} does not exist in this document..
/// </summary>
public static string ExportReportDlg_GetExceptionDisplayMessage_The_field__0__does_not_exist_in_this_document {
get {
return ResourceManager.GetString("ExportReportDlg_GetExceptionDisplayMessage_The_field__0__does_not_exist_in_this_d" +
"ocument", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Export Report.
/// </summary>
public static string ExportReportDlg_OkDialog_Export_Report {
get {
return ResourceManager.GetString("ExportReportDlg_OkDialog_Export_Report", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An unexpected error occurred attempting to display the report '{0}'..
/// </summary>
public static string ExportReportDlg_ShowPreview_An_unexpected_error_occurred_attempting_to_display_the_report___0___ {
get {
return ResourceManager.GetString("ExportReportDlg_ShowPreview_An_unexpected_error_occurred_attempting_to_display_th" +
"e_report___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Report Definitions.
/// </summary>
public static string ExportReportDlg_ShowShare_Report_Definitions {
get {
return ResourceManager.GetString("ExportReportDlg_ShowShare_Report_Definitions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline Reports.
/// </summary>
public static string ExportReportDlg_ShowShare_Skyline_Reports {
get {
return ResourceManager.GetString("ExportReportDlg_ShowShare_Skyline_Reports", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Average.
/// </summary>
public static string ExportSchedulingAlgorithmExtension_LOCALIZED_VALUES_Average {
get {
return ResourceManager.GetString("ExportSchedulingAlgorithmExtension_LOCALIZED_VALUES_Average", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Single.
/// </summary>
public static string ExportSchedulingAlgorithmExtension_LOCALIZED_VALUES_Single {
get {
return ResourceManager.GetString("ExportSchedulingAlgorithmExtension_LOCALIZED_VALUES_Single", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Trends.
/// </summary>
public static string ExportSchedulingAlgorithmExtension_LOCALIZED_VALUES_Trends {
get {
return ResourceManager.GetString("ExportSchedulingAlgorithmExtension_LOCALIZED_VALUES_Trends", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Average.
/// </summary>
public static string ExportStrategyExtension_LOCALIZED_VALUES_Average {
get {
return ResourceManager.GetString("ExportStrategyExtension_LOCALIZED_VALUES_Average", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Buckets.
/// </summary>
public static string ExportStrategyExtension_LOCALIZED_VALUES_Buckets {
get {
return ResourceManager.GetString("ExportStrategyExtension_LOCALIZED_VALUES_Buckets", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Monoisotopic.
/// </summary>
public static string ExportStrategyExtension_LOCALIZED_VALUES_Monoisotopic {
get {
return ResourceManager.GetString("ExportStrategyExtension_LOCALIZED_VALUES_Monoisotopic", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Protein.
/// </summary>
public static string ExportStrategyExtension_LOCALIZED_VALUES_Protein {
get {
return ResourceManager.GetString("ExportStrategyExtension_LOCALIZED_VALUES_Protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Single.
/// </summary>
public static string ExportStrategyExtension_LOCALIZED_VALUES_Single {
get {
return ResourceManager.GetString("ExportStrategyExtension_LOCALIZED_VALUES_Single", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 2D Histogram.
/// </summary>
public static string Extensions_CustomToString__2D_Histogram {
get {
return ResourceManager.GetString("Extensions_CustomToString__2D_Histogram", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Histogram.
/// </summary>
public static string Extensions_CustomToString_Detections_Histogram {
get {
return ResourceManager.GetString("Extensions_CustomToString_Detections_Histogram", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicates.
/// </summary>
public static string Extensions_CustomToString_Detections_Replicates {
get {
return ResourceManager.GetString("Extensions_CustomToString_Detections_Replicates", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Histogram.
/// </summary>
public static string Extensions_CustomToString_Histogram {
get {
return ResourceManager.GetString("Extensions_CustomToString_Histogram", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide Comparison.
/// </summary>
public static string Extensions_CustomToString_Peptide_Comparison {
get {
return ResourceManager.GetString("Extensions_CustomToString_Peptide_Comparison", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicate Comparison.
/// </summary>
public static string Extensions_CustomToString_Replicate_Comparison {
get {
return ResourceManager.GetString("Extensions_CustomToString_Replicate_Comparison", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Run To Run Regression.
/// </summary>
public static string Extensions_CustomToString_Run_To_Run_Regression {
get {
return ResourceManager.GetString("Extensions_CustomToString_Run_To_Run_Regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scheduling.
/// </summary>
public static string Extensions_CustomToString_Scheduling {
get {
return ResourceManager.GetString("Extensions_CustomToString_Scheduling", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Score To Run Regression.
/// </summary>
public static string Extensions_CustomToString_Score_To_Run_Regression {
get {
return ResourceManager.GetString("Extensions_CustomToString_Score_To_Run_Regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap ExternalTool {
get {
object obj = ResourceManager.GetObject("ExternalTool", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to {0} (load failed: {1}).
/// </summary>
public static string FailedChromGraphItem_FailedChromGraphItem__0__load_failed__1__ {
get {
return ResourceManager.GetString("FailedChromGraphItem_FailedChromGraphItem__0__load_failed__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} proteins and {1} peptides added.
/// </summary>
public static string FastaImporter_Import__0__proteins_and__1__peptides_added {
get {
return ResourceManager.GetString("FastaImporter_Import__0__proteins_and__1__peptides_added", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding protein {0}.
/// </summary>
public static string FastaImporter_Import_Adding_protein__0__ {
get {
return ResourceManager.GetString("FastaImporter_Import_Adding_protein__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check your settings to make sure you are using a library..
/// </summary>
public static string FastaImporter_Import_Check_your_settings_to_make_sure_you_are_using_a_library_ {
get {
return ResourceManager.GetString("FastaImporter_Import_Check_your_settings_to_make_sure_you_are_using_a_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check your settings to make sure you are using a library and restrictive enough transition selection..
/// </summary>
public static string FastaImporter_Import_Check_your_settings_to_make_sure_you_are_using_a_library_and_restrictive_enough_transition_selection_ {
get {
return ResourceManager.GetString("FastaImporter_Import_Check_your_settings_to_make_sure_you_are_using_a_library_and" +
"_restrictive_enough_transition_selection_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error at or around line {0}: {1}.
/// </summary>
public static string FastaImporter_Import_Error_at_or_around_line__0____1_ {
get {
return ResourceManager.GetString("FastaImporter_Import_Error_at_or_around_line__0____1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This import causes the document to contain more than {0:n0} peptides at line {1:n0}..
/// </summary>
public static string FastaImporter_Import_This_import_causes_the_document_to_contain_more_than__0_n0__peptides_at_line__1_n0__ {
get {
return ResourceManager.GetString("FastaImporter_Import_This_import_causes_the_document_to_contain_more_than__0_n0__" +
"peptides_at_line__1_n0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This import causes the document to contain more than {0:n0} transitions in {1:n0} peptides at line {2:n0}..
/// </summary>
public static string FastaImporter_Import_This_import_causes_the_document_to_contain_more_than__0_n0__transitions_in__1_n0__peptides_at_line__2_n0__ {
get {
return ResourceManager.GetString("FastaImporter_Import_This_import_causes_the_document_to_contain_more_than__0_n0__" +
"transitions_in__1_n0__peptides_at_line__2_n0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Last column does not contain a valid protein sequence.
/// </summary>
public static string FastaImporter_ToFasta_Last_column_does_not_contain_a_valid_protein_sequence {
get {
return ResourceManager.GetString("FastaImporter_ToFasta_Last_column_does_not_contain_a_valid_protein_sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Too few columns found.
/// </summary>
public static string FastaImporter_ToFasta_Too_few_columns_found {
get {
return ResourceManager.GetString("FastaImporter_ToFasta_Too_few_columns_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides in different FASTA sequences may not be compared..
/// </summary>
public static string FastaSequence_ComparePeptides_Peptides_in_different_FASTA_sequences_may_not_be_compared {
get {
return ResourceManager.GetString("FastaSequence_ComparePeptides_Peptides_in_different_FASTA_sequences_may_not_be_co" +
"mpared", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides without FASTA sequence information may not be compared..
/// </summary>
public static string FastaSequence_ComparePeptides_Peptides_without_FASTA_sequence_information_may_not_be_compared {
get {
return ResourceManager.GetString("FastaSequence_ComparePeptides_Peptides_without_FASTA_sequence_information_may_not" +
"_be_compared", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A protein sequence may not be empty..
/// </summary>
public static string FastaSequence_ValidateSequence_A_protein_sequence_may_not_be_empty {
get {
return ResourceManager.GetString("FastaSequence_ValidateSequence_A_protein_sequence_may_not_be_empty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A protein sequence may not contain the character '{0}' at {1}..
/// </summary>
public static string FastaSequence_ValidateSequence_A_protein_sequence_may_not_contain_the_character__0__at__1__ {
get {
return ResourceManager.GetString("FastaSequence_ValidateSequence_A_protein_sequence_may_not_contain_the_character__" +
"0__at__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempt to get peptide list from uncleaved FASTA sequence..
/// </summary>
public static string FastaSeqV01_GetPeptideList_Attempt_to_get_peptide_list_from_uncleaved_FASTA_sequence {
get {
return ResourceManager.GetString("FastaSeqV01_GetPeptideList_Attempt_to_get_peptide_list_from_uncleaved_FASTA_seque" +
"nce", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap File {
get {
object obj = ResourceManager.GetObject("File", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Directory could not be found: {0}.
/// </summary>
public static string FileEx_SafeDelete_Directory_could_not_be_found___0_ {
get {
return ResourceManager.GetString("FileEx_SafeDelete_Directory_could_not_be_found___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File path is invalid: {0}.
/// </summary>
public static string FileEx_SafeDelete_File_path_is_invalid___0_ {
get {
return ResourceManager.GetString("FileEx_SafeDelete_File_path_is_invalid___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File path is too long: {0}.
/// </summary>
public static string FileEx_SafeDelete_File_path_is_too_long___0_ {
get {
return ResourceManager.GetString("FileEx_SafeDelete_File_path_is_too_long___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insufficient permission to delete file: {0}.
/// </summary>
public static string FileEx_SafeDelete_Insufficient_permission_to_delete_file___0_ {
get {
return ResourceManager.GetString("FileEx_SafeDelete_Insufficient_permission_to_delete_file___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Path contains invalid characters: {0}.
/// </summary>
public static string FileEx_SafeDelete_Path_contains_invalid_characters___0_ {
get {
return ResourceManager.GetString("FileEx_SafeDelete_Path_contains_invalid_characters___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Path is empty.
/// </summary>
public static string FileEx_SafeDelete_Path_is_empty {
get {
return ResourceManager.GetString("FileEx_SafeDelete_Path_is_empty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to delete directory: {0}.
/// </summary>
public static string FileEx_SafeDelete_Unable_to_delete_directory___0_ {
get {
return ResourceManager.GetString("FileEx_SafeDelete_Unable_to_delete_directory___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to delete file which is in use: {0}.
/// </summary>
public static string FileEx_SafeDelete_Unable_to_delete_file_which_is_in_use___0_ {
get {
return ResourceManager.GetString("FileEx_SafeDelete_Unable_to_delete_file_which_is_in_use___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to delete read-only file: {0}.
/// </summary>
public static string FileEx_SafeDelete_Unable_to_delete_read_only_file___0_ {
get {
return ResourceManager.GetString("FileEx_SafeDelete_Unable_to_delete_read_only_file___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot save to {0}..
/// </summary>
public static string FileIterator_Init_Cannot_save_to__0__ {
get {
return ResourceManager.GetString("FileIterator_Init_Cannot_save_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected failure writing transitions..
/// </summary>
public static string FileIterator_WriteTransition_Unexpected_failure_writing_transitions {
get {
return ResourceManager.GetString("FileIterator_WriteTransition_Unexpected_failure_writing_transitions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Graph.
/// </summary>
public static string FileProgressControl_btnRetry_Click_Graph {
get {
return ResourceManager.GetString("FileProgressControl_btnRetry_Click_Graph", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Log.
/// </summary>
public static string FileProgressControl_btnRetry_Click_Log {
get {
return ResourceManager.GetString("FileProgressControl_btnRetry_Click_Log", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to imported.
/// </summary>
public static string FileProgressControl_Finish_imported {
get {
return ResourceManager.GetString("FileProgressControl_Finish_imported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There were {0} failed import attempts.
///.
/// </summary>
public static string FileProgressControl_GetErrorLog_ {
get {
return ResourceManager.GetString("FileProgressControl_GetErrorLog_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to
///Here are the last 3 errors:
///.
/// </summary>
public static string FileProgressControl_GetErrorLog_2 {
get {
return ResourceManager.GetString("FileProgressControl_GetErrorLog_2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}. {1}.
/// </summary>
public static string FileProgressControl_Number__0____1_ {
get {
return ResourceManager.GetString("FileProgressControl_Number__0____1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to At {0}:
///{1}
///.
/// </summary>
public static string FileProgressControl_SetStatus_ {
get {
return ResourceManager.GetString("FileProgressControl_SetStatus_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cancel.
/// </summary>
public static string FileProgressControl_SetStatus_Cancel {
get {
return ResourceManager.GetString("FileProgressControl_SetStatus_Cancel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to canceled.
/// </summary>
public static string FileProgressControl_SetStatus_canceled {
get {
return ResourceManager.GetString("FileProgressControl_SetStatus_canceled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to failed.
/// </summary>
public static string FileProgressControl_SetStatus_failed {
get {
return ResourceManager.GetString("FileProgressControl_SetStatus_failed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retry.
/// </summary>
public static string FileProgressControl_SetStatus_Retry {
get {
return ResourceManager.GetString("FileProgressControl_SetStatus_Retry", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to warning.
/// </summary>
public static string FileProgressControl_SetStatus_warning {
get {
return ResourceManager.GetString("FileProgressControl_SetStatus_warning", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot save to {0}. Check the path to make sure the directory exists..
/// </summary>
public static string FileSaver_CanSave_Cannot_save_to__0__Check_the_path_to_make_sure_the_directory_exists {
get {
return ResourceManager.GetString("FileSaver_CanSave_Cannot_save_to__0__Check_the_path_to_make_sure_the_directory_ex" +
"ists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot save to {0}. The file is read-only..
/// </summary>
public static string FileSaver_CanSave_Cannot_save_to__0__The_file_is_read_only {
get {
return ResourceManager.GetString("FileSaver_CanSave_Cannot_save_to__0__The_file_is_read_only", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not replace file .
/// </summary>
public static string FileStreamManager_Commit_Could_not_replace_file_ {
get {
return ResourceManager.GetString("FileStreamManager_Commit_Could_not_replace_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected error opening {0}.
/// </summary>
public static string FileStreamManager_CreateStream_Unexpected_error_opening__0__ {
get {
return ResourceManager.GetString("FileStreamManager_CreateStream_Unexpected_error_opening__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Access Denied: unable to create a file in the folder "{0}". Adjust the folder write permissions or retry the operation after moving or copying files to a different folder..
/// </summary>
public static string FileStreamManager_GetTempFileName_Access_Denied__unable_to_create_a_file_in_the_folder___0____Adjust_the_folder_write_permissions_or_retry_the_operation_after_moving_or_copying_files_to_a_different_folder_ {
get {
return ResourceManager.GetString("FileStreamManager_GetTempFileName_Access_Denied__unable_to_create_a_file_in_the_f" +
"older___0____Adjust_the_folder_write_permissions_or_retry_the_operation_after_mo" +
"ving_or_copying_files_to_a_different_folder_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed attempting to create a temporary file in the folder {0} with the following error:.
/// </summary>
public static string FileStreamManager_GetTempFileName_Failed_attempting_to_create_a_temporary_file_in_the_folder__0__with_the_following_error_ {
get {
return ResourceManager.GetString("FileStreamManager_GetTempFileName_Failed_attempting_to_create_a_temporary_file_in" +
"_the_folder__0__with_the_following_error_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Win32 Error: {0}.
/// </summary>
public static string FileStreamManager_GetTempFileName_Win32_Error__0__ {
get {
return ResourceManager.GetString("FileStreamManager_GetTempFileName_Win32_Error__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Filter {
get {
object obj = ResourceManager.GetObject("Filter", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to {0} molecules not matching the current filter settings..
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg__0__molecules_not_matching_the_current_filter_settings {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg__0__molecules_not_matching_the_" +
"current_filter_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} peptides matching multiple proteins..
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg__0__peptides_matching_multiple_proteins {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg__0__peptides_matching_multiple_" +
"proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} peptides not matching the current filter settings..
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg__0__peptides_not_matching_the_current_filter_settings {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg__0__peptides_not_matching_the_c" +
"urrent_filter_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} peptides without matching proteins..
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg__0__peptides_without_matching_proteins {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg__0__peptides_without_matching_p" +
"roteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 molecule not matching the current filter settings..
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_1_molecule_not_matching_the_current_filter_settings {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_1_molecule_not_matching_the_cur" +
"rent_filter_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 peptide matching multiple proteins..
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_1_peptide_matching_multiple_proteins {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_1_peptide_matching_multiple_pro" +
"teins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 peptide not matching the current filter settings..
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_1_peptide_not_matching_the_current_filter_settings {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_1_peptide_not_matching_the_curr" +
"ent_filter_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 peptide without a matching protein..
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_1_peptide_without_a_matching_protein {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_1_peptide_without_a_matching_pr" +
"otein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Filter Molecules.
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_Filter_Molecules {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_Filter_Molecules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Include all molecules.
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_Include_all_molecules {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_Include_all_molecules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This molecule does not match the current filter settings..
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_This_molecule_does_not_match_the_current_filter_settings {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_This_molecule_does_not_match_th" +
"e_current_filter_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This peptide does not have a matching protein..
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_This_peptide_does_not_have_a_matching_protein {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_This_peptide_does_not_have_a_ma" +
"tching_protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This peptide does not match the current filter settings..
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_This_peptide_does_not_match_the_current_filter_settings {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_This_peptide_does_not_match_the" +
"_current_filter_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This peptide matches multiple proteins..
/// </summary>
public static string FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_This_peptide_matches_multiple_proteins {
get {
return ResourceManager.GetString("FilterMatchedPeptidesDlg_FilterMatchedPeptidesDlg_This_peptide_matches_multiple_p" +
"roteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Export Filtered MIDAS Library.
/// </summary>
public static string FilterMidasLibraryDlg_btnBrowse_Click_Export_Filtered_MIDAS_Library {
get {
return ResourceManager.GetString("FilterMidasLibraryDlg_btnBrowse_Click_Export_Filtered_MIDAS_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A library with this name already exists..
/// </summary>
public static string FilterMidasLibraryDlg_OkDialog_A_library_with_this_name_already_exists_ {
get {
return ResourceManager.GetString("FilterMidasLibraryDlg_OkDialog_A_library_with_this_name_already_exists_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must enter a name for the filtered library..
/// </summary>
public static string FilterMidasLibraryDlg_OkDialog_You_must_enter_a_name_for_the_filtered_library_ {
get {
return ResourceManager.GetString("FilterMidasLibraryDlg_OkDialog_You_must_enter_a_name_for_the_filtered_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must enter a path for the filtered library..
/// </summary>
public static string FilterMidasLibraryDlg_OkDialog_You_must_enter_a_path_for_the_filtered_library_ {
get {
return ResourceManager.GetString("FilterMidasLibraryDlg_OkDialog_You_must_enter_a_path_for_the_filtered_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Find {
get {
object obj = ResourceManager.GetObject("Find", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap FindNext {
get {
object obj = ResourceManager.GetObject("FindNext", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to << Hide Ad&vanced.
/// </summary>
public static string FindNodeDlg_AdvancedVisible_Hide_Advanced {
get {
return ResourceManager.GetString("FindNodeDlg_AdvancedVisible_Hide_Advanced", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Ad&vanced >>.
/// </summary>
public static string FindNodeDlg_AdvancedVisible_Show_Advanced {
get {
return ResourceManager.GetString("FindNodeDlg_AdvancedVisible_Show_Advanced", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not find {0}..
/// </summary>
public static string FindOptions_GetNotFoundMessage_Could_not_find__0__ {
get {
return ResourceManager.GetString("FindOptions_GetNotFoundMessage_Could_not_find__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not find any of {0} items..
/// </summary>
public static string FindOptions_GetNotFoundMessage_Could_not_find_any_of__0__items {
get {
return ResourceManager.GetString("FindOptions_GetNotFoundMessage_Could_not_find_any_of__0__items", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The text '{0}' could not be found..
/// </summary>
public static string FindOptions_GetNotFoundMessage_The_text__0__could_not_be_found {
get {
return ResourceManager.GetString("FindOptions_GetNotFoundMessage_The_text__0__could_not_be_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Found {0} matches.
/// </summary>
public static string FindPredicate_FindAll_Found__0__matches {
get {
return ResourceManager.GetString("FindPredicate_FindAll_Found__0__matches", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Found 0 matches.
/// </summary>
public static string FindPredicate_FindAll_Found_0_matches {
get {
return ResourceManager.GetString("FindPredicate_FindAll_Found_0_matches", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Found 1 match.
/// </summary>
public static string FindPredicate_FindAll_Found_1_match {
get {
return ResourceManager.GetString("FindPredicate_FindAll_Found_1_match", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Searching for {0}.
/// </summary>
public static string FindPredicate_FindAll_Searching_for__0__ {
get {
return ResourceManager.GetString("FindPredicate_FindAll_Searching_for__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Bar Graph.
/// </summary>
public static string FoldChangeForm_BuildContextMenu_Bar_Graph {
get {
return ResourceManager.GetString("FoldChangeForm_BuildContextMenu_Bar_Graph", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Grid.
/// </summary>
public static string FoldChangeForm_BuildContextMenu_Grid {
get {
return ResourceManager.GetString("FoldChangeForm_BuildContextMenu_Grid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Settings.
/// </summary>
public static string FoldChangeForm_BuildContextMenu_Settings {
get {
return ResourceManager.GetString("FoldChangeForm_BuildContextMenu_Settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Volcano Plot.
/// </summary>
public static string FoldChangeForm_BuildContextMenu_Volcano_Plot {
get {
return ResourceManager.GetString("FoldChangeForm_BuildContextMenu_Volcano_Plot", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Folder {
get {
object obj = ResourceManager.GetObject("Folder", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to large.
/// </summary>
public static string FontSize_LARGE_large {
get {
return ResourceManager.GetString("FontSize_LARGE_large", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to normal.
/// </summary>
public static string FontSize_NORMAL_normal {
get {
return ResourceManager.GetString("FontSize_NORMAL_normal", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to small.
/// </summary>
public static string FontSize_SMALL_small {
get {
return ResourceManager.GetString("FontSize_SMALL_small", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to x-large.
/// </summary>
public static string FontSize_XLARGE_x_large {
get {
return ResourceManager.GetString("FontSize_XLARGE_x_large", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to x-small.
/// </summary>
public static string FontSize_XSMALL_x_small {
get {
return ResourceManager.GetString("FontSize_XSMALL_x_small", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Full Precision.
/// </summary>
public static string FormatSuggestion_FullPrecision_Full_Precision {
get {
return ResourceManager.GetString("FormatSuggestion_FullPrecision_Full_Precision", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Integer.
/// </summary>
public static string FormatSuggestion_Integer_Integer {
get {
return ResourceManager.GetString("FormatSuggestion_Integer_Integer", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Percent.
/// </summary>
public static string FormatSuggestion_Percent_Percent {
get {
return ResourceManager.GetString("FormatSuggestion_Percent_Percent", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scientific.
/// </summary>
public static string FormatSuggestion_Scientific_Scientific {
get {
return ResourceManager.GetString("FormatSuggestion_Scientific_Scientific", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Formulas are written in standard chemical notation, e.g. "C2H6O". Heavy isotopes are indicated by a prime (e.g. C' for C13) or double prime for less abundant stable iostopes (e.g. O" for O17, O' for O18)..
/// </summary>
public static string FormulaBox_FormulaHelpText_Formulas_are_written_in_standard_chemical_notation__e_g___C2H6O____Heavy_isotopes_are_indicated_by_a_prime__e_g__C__for_C13__or_double_prime_for_less_abundant_stable_iostopes__e_g__O__for_O17__O__for_O18__ {
get {
return ResourceManager.GetString("FormulaBox_FormulaHelpText_Formulas_are_written_in_standard_chemical_notation__e_" +
"g___C2H6O____Heavy_isotopes_are_indicated_by_a_prime__e_g__C__for_C13__or_double" +
"_prime_for_less_abundant_stable_iostopes__e_g__O__for_O17__O__for_O18__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Formula Help.
/// </summary>
public static string FormulaBox_helpToolStripMenuItem_Click_Formula_Help {
get {
return ResourceManager.GetString("FormulaBox_helpToolStripMenuItem_Click_Formula_Help", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Fragment {
get {
object obj = ResourceManager.GetObject("Fragment", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap FragmentDecoy {
get {
object obj = ResourceManager.GetObject("FragmentDecoy", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap FragmentLib {
get {
object obj = ResourceManager.GetObject("FragmentLib", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap FragmentLibDecoy {
get {
object obj = ResourceManager.GetObject("FragmentLibDecoy", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Neutral losses must be greater than or equal to {0}..
/// </summary>
public static string FragmentLoss_Validate_Neutral_losses_must_be_greater_than_or_equal_to__0__ {
get {
return ResourceManager.GetString("FragmentLoss_Validate_Neutral_losses_must_be_greater_than_or_equal_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Neutral losses must be less than or equal to {0}..
/// </summary>
public static string FragmentLoss_Validate_Neutral_losses_must_be_less_than_or_equal_to__0__ {
get {
return ResourceManager.GetString("FragmentLoss_Validate_Neutral_losses_must_be_less_than_or_equal_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Neutral losses must specify a formula or valid monoisotopic and average masses..
/// </summary>
public static string FragmentLoss_Validate_Neutral_losses_must_specify_a_formula_or_valid_monoisotopic_and_average_masses {
get {
return ResourceManager.GetString("FragmentLoss_Validate_Neutral_losses_must_specify_a_formula_or_valid_monoisotopic" +
"_and_average_masses", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to DIA.
/// </summary>
public static string FullScanAcquisitionExtension_LOCALIZED_VALUES_DIA {
get {
return ResourceManager.GetString("FullScanAcquisitionExtension_LOCALIZED_VALUES_DIA", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None.
/// </summary>
public static string FullScanAcquisitionExtension_LOCALIZED_VALUES_None {
get {
return ResourceManager.GetString("FullScanAcquisitionExtension_LOCALIZED_VALUES_None", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Targeted.
/// </summary>
public static string FullScanAcquisitionExtension_LOCALIZED_VALUES_Targeted {
get {
return ResourceManager.GetString("FullScanAcquisitionExtension_LOCALIZED_VALUES_Targeted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to DDA.
/// </summary>
public static string FullScanAcquisitionMethod_DDA_DDA {
get {
return ResourceManager.GetString("FullScanAcquisitionMethod_DDA_DDA", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} is not a valid Full Scan Acquisition Method.
/// </summary>
public static string FullScanAcquisitionMethod_FromName__0__is_not_a_valid_Full_Scan_Acquisition_Method {
get {
return ResourceManager.GetString("FullScanAcquisitionMethod_FromName__0__is_not_a_valid_Full_Scan_Acquisition_Metho" +
"d", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Count.
/// </summary>
public static string FullScanPrecursorIsotopesExtension_LOCALIZED_VALUES_Count {
get {
return ResourceManager.GetString("FullScanPrecursorIsotopesExtension_LOCALIZED_VALUES_Count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None.
/// </summary>
public static string FullScanPrecursorIsotopesExtension_LOCALIZED_VALUES_None {
get {
return ResourceManager.GetString("FullScanPrecursorIsotopesExtension_LOCALIZED_VALUES_None", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Percent.
/// </summary>
public static string FullScanPrecursorIsotopesExtension_LOCALIZED_VALUES_Percent {
get {
return ResourceManager.GetString("FullScanPrecursorIsotopesExtension_LOCALIZED_VALUES_Percent", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mass &Accuracy:.
/// </summary>
public static string FullScanSettingsControl_SetAnalyzerType_Mass__Accuracy_ {
get {
return ResourceManager.GetString("FullScanSettingsControl_SetAnalyzerType_Mass__Accuracy_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Full gradient chromatograms will take longer to import, consume more disk space, and may make peak picking less effective..
/// </summary>
public static string FullScanSettingsControl_UpdateRetentionTimeFilterUi_Full_gradient_chromatograms_will_take_longer_to_import__consume_more_disk_space__and_may_make_peak_picking_less_effective_ {
get {
return ResourceManager.GetString("FullScanSettingsControl_UpdateRetentionTimeFilterUi_Full_gradient_chromatograms_w" +
"ill_take_longer_to_import__consume_more_disk_space__and_may_make_peak_picking_le" +
"ss_effective_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None of the spectral libraries in this document contain any retention times for any of the peptides in this document..
/// </summary>
public static string FullScanSettingsControl_UpdateRetentionTimeFilterUi_None_of_the_spectral_libraries_in_this_document_contain_any_retention_times_for_any_of_the_peptides_in_this_document_ {
get {
return ResourceManager.GetString("FullScanSettingsControl_UpdateRetentionTimeFilterUi_None_of_the_spectral_librarie" +
"s_in_this_document_contain_any_retention_times_for_any_of_the_peptides_in_this_d" +
"ocument_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This document does not contain any spectral libraries..
/// </summary>
public static string FullScanSettingsControl_UpdateRetentionTimeFilterUi_This_document_does_not_contain_any_spectral_libraries_ {
get {
return ResourceManager.GetString("FullScanSettingsControl_UpdateRetentionTimeFilterUi_This_document_does_not_contai" +
"n_any_spectral_libraries_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No valid precursor m/z column found..
/// </summary>
public static string GeneralRowReader_Create_No_valid_precursor_m_z_column_found {
get {
return ResourceManager.GetString("GeneralRowReader_Create_No_valid_precursor_m_z_column_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No valid product m/z column found..
/// </summary>
public static string GeneralRowReader_Create_No_valid_product_m_z_column_found {
get {
return ResourceManager.GetString("GeneralRowReader_Create_No_valid_product_m_z_column_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap GenerateDecoys {
get {
object obj = ResourceManager.GetObject("GenerateDecoys", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to All.
/// </summary>
public static string GenerateDecoysDlg_GenerateDecoysDlg_All {
get {
return ResourceManager.GetString("GenerateDecoysDlg_GenerateDecoysDlg_All", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The number of peptides {0} must be less than the number of peptide precursor models for decoys {1}, or use the '{2}' decoy generation method..
/// </summary>
public static string GenerateDecoysDlg_OkDialog_The_number_of_peptides__0__must_be_less_than_the_number_of_peptide_precursor_models_for_decoys__1___or_use_the___2___decoy_generation_method_ {
get {
return ResourceManager.GetString("GenerateDecoysDlg_OkDialog_The_number_of_peptides__0__must_be_less_than_the_numbe" +
"r_of_peptide_precursor_models_for_decoys__1___or_use_the___2___decoy_generation_" +
"method_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No peptide precursor models for decoys were found..
/// </summary>
public static string GenerateDecoysError_No_peptide_precursor_models_for_decoys_were_found_ {
get {
return ResourceManager.GetString("GenerateDecoysError_No_peptide_precursor_models_for_decoys_were_found_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No optimization data available..
/// </summary>
public static string GraphChromatogram_DisplayOptimizationTotals_No_optimization_data_available {
get {
return ResourceManager.GetString("GraphChromatogram_DisplayOptimizationTotals_No_optimization_data_available", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All.
/// </summary>
public static string GraphChromatogram_UpdateToolbar_All {
get {
return ResourceManager.GetString("GraphChromatogram_UpdateToolbar_All", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No base peak chromatogram found.
/// </summary>
public static string GraphChromatogram_UpdateUI_No_base_peak_chromatogram_found {
get {
return ResourceManager.GetString("GraphChromatogram_UpdateUI_No_base_peak_chromatogram_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No precursor ion chromatograms found.
/// </summary>
public static string GraphChromatogram_UpdateUI_No_precursor_ion_chromatograms_found {
get {
return ResourceManager.GetString("GraphChromatogram_UpdateUI_No_precursor_ion_chromatograms_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No product ion chromatograms found.
/// </summary>
public static string GraphChromatogram_UpdateUI_No_product_ion_chromatograms_found {
get {
return ResourceManager.GetString("GraphChromatogram_UpdateUI_No_product_ion_chromatograms_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No corresponding QC chromatogram found.
/// </summary>
public static string GraphChromatogram_UpdateUI_No_QC_chromatogram_found {
get {
return ResourceManager.GetString("GraphChromatogram_UpdateUI_No_QC_chromatogram_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No TIC chromatogram found.
/// </summary>
public static string GraphChromatogram_UpdateUI_No_TIC_chromatogram_found {
get {
return ResourceManager.GetString("GraphChromatogram_UpdateUI_No_TIC_chromatogram_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Select a peptide, precursor or transition to view its chromatograms.
/// </summary>
public static string GraphChromatogram_UpdateUI_Select_a_peptide__precursor_or_transition_to_view_its_chromatograms {
get {
return ResourceManager.GetString("GraphChromatogram_UpdateUI_Select_a_peptide__precursor_or_transition_to_view_its_" +
"chromatograms", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to window.
/// </summary>
public static string GraphData_AddRegressionLabel_window {
get {
return ResourceManager.GetString("GraphData_AddRegressionLabel_window", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measured Time ({0}).
/// </summary>
public static string GraphData_CorrelationLabel_Measured_Time___0__ {
get {
return ResourceManager.GetString("GraphData_CorrelationLabel_Measured_Time___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Outliers.
/// </summary>
public static string GraphData_Graph_Outliers {
get {
return ResourceManager.GetString("GraphData_Graph_Outliers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides.
/// </summary>
public static string GraphData_Graph_Peptides {
get {
return ResourceManager.GetString("GraphData_Graph_Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides Refined.
/// </summary>
public static string GraphData_Graph_Peptides_Refined {
get {
return ResourceManager.GetString("GraphData_Graph_Peptides_Refined", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Predictor.
/// </summary>
public static string GraphData_Graph_Predictor {
get {
return ResourceManager.GetString("GraphData_Graph_Predictor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Regression.
/// </summary>
public static string GraphData_Graph_Regression {
get {
return ResourceManager.GetString("GraphData_Graph_Regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Regression Refined.
/// </summary>
public static string GraphData_Graph_Regression_Refined {
get {
return ResourceManager.GetString("GraphData_Graph_Regression_Refined", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The database for the calculator {0} could not be opened. Check that the file {1} was not moved or deleted..
/// </summary>
public static string GraphData_GraphData_The_database_for_the_calculator__0__could_not_be_opened__Check_that_the_file__1__was_not_moved_or_deleted_ {
get {
return ResourceManager.GetString("GraphData_GraphData_The_database_for_the_calculator__0__could_not_be_opened__Chec" +
"k_that_the_file__1__was_not_moved_or_deleted_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Time from Prediction.
/// </summary>
public static string GraphData_GraphResiduals_Time_from_Prediction {
get {
return ResourceManager.GetString("GraphData_GraphResiduals_Time_from_Prediction", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Time from Regression.
/// </summary>
public static string GraphData_GraphResiduals_Time_from_Regression {
get {
return ResourceManager.GetString("GraphData_GraphResiduals_Time_from_Regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Time from Regression ({0}).
/// </summary>
public static string GraphData_ResidualsLabel_Time_from_Regression___0__ {
get {
return ResourceManager.GetString("GraphData_ResidualsLabel_Time_from_Regression___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} ({1:F2} min).
/// </summary>
public static string GraphFullScan_CreateGraph__0_____1_F2__min_ {
get {
return ResourceManager.GetString("GraphFullScan_CreateGraph__0_____1_F2__min_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to IM={0}.
/// </summary>
public static string GraphFullScan_CreateGraph_IM__0_ {
get {
return ResourceManager.GetString("GraphFullScan_CreateGraph_IM__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to IM Scan Range:.
/// </summary>
public static string GraphFullScan_CreateGraph_IM_Scan_Range_ {
get {
return ResourceManager.GetString("GraphFullScan_CreateGraph_IM_Scan_Range_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scan Number:.
/// </summary>
public static string GraphFullScan_CreateGraph_Scan_Number_ {
get {
return ResourceManager.GetString("GraphFullScan_CreateGraph_Scan_Number_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Quadrupole Scan Range (m/z).
/// </summary>
public static string GraphFullScan_CreateIonMobilityHeatmap_Quadrupole_Scan_Range__m_z_ {
get {
return ResourceManager.GetString("GraphFullScan_CreateIonMobilityHeatmap_Quadrupole_Scan_Range__m_z_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Filter Quadrupole Scan Range.
/// </summary>
public static string GraphFullScan_Filter_Button_Tooltip_Filter_Quadrupole_Scan_Range {
get {
return ResourceManager.GetString("GraphFullScan_Filter_Button_Tooltip_Filter_Quadrupole_Scan_Range", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to MS/MS.
/// </summary>
public static string GraphFullScan_GraphFullScan_MS_MS {
get {
return ResourceManager.GetString("GraphFullScan_GraphFullScan_MS_MS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to MS1.
/// </summary>
public static string GraphFullScan_GraphFullScan_MS1 {
get {
return ResourceManager.GetString("GraphFullScan_GraphFullScan_MS1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SIM.
/// </summary>
public static string GraphFullScan_GraphFullScan_SIM {
get {
return ResourceManager.GetString("GraphFullScan_GraphFullScan_SIM", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading....
/// </summary>
public static string GraphFullScan_LoadScan_Loading___ {
get {
return ResourceManager.GetString("GraphFullScan_LoadScan_Loading___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Spectrum unavailable.
/// </summary>
public static string GraphFullScan_LoadScan_Spectrum_unavailable {
get {
return ResourceManager.GetString("GraphFullScan_LoadScan_Spectrum_unavailable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure loading spectrum. Library may be corrupted..
/// </summary>
public static string GraphSpectrum_UpdateUI_Failure_loading_spectrum__Library_may_be_corrupted {
get {
return ResourceManager.GetString("GraphSpectrum_UpdateUI_Failure_loading_spectrum__Library_may_be_corrupted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Multiple charge states with library spectra.
/// </summary>
public static string GraphSpectrum_UpdateUI_Multiple_charge_states_with_library_spectra {
get {
return ResourceManager.GetString("GraphSpectrum_UpdateUI_Multiple_charge_states_with_library_spectra", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All.
/// </summary>
public static string GraphSummary_UpdateToolbar_All {
get {
return ResourceManager.GetString("GraphSummary_UpdateToolbar_All", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Log {0}.
/// </summary>
public static string GraphValues_Log_AxisTitle {
get {
return ResourceManager.GetString("GraphValues_Log_AxisTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap GreenCheck {
get {
object obj = ResourceManager.GetObject("GreenCheck", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to End.
/// </summary>
public static string GridColumnsExtension_getDefaultLanguageValues_End {
get {
return ResourceManager.GetString("GridColumnsExtension_getDefaultLanguageValues_End", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to End margin.
/// </summary>
public static string GridColumnsExtension_getDefaultLanguageValues_End_margin {
get {
return ResourceManager.GetString("GridColumnsExtension_getDefaultLanguageValues_End_margin", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to none.
/// </summary>
public static string GridColumnsExtension_getDefaultLanguageValues_none {
get {
return ResourceManager.GetString("GridColumnsExtension_getDefaultLanguageValues_none", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Start.
/// </summary>
public static string GridColumnsExtension_getDefaultLanguageValues_Start {
get {
return ResourceManager.GetString("GridColumnsExtension_getDefaultLanguageValues_Start", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Start margin.
/// </summary>
public static string GridColumnsExtension_getDefaultLanguageValues_Start_margin {
get {
return ResourceManager.GetString("GridColumnsExtension_getDefaultLanguageValues_Start_margin", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Target.
/// </summary>
public static string GridColumnsExtension_getDefaultLanguageValues_Target {
get {
return ResourceManager.GetString("GridColumnsExtension_getDefaultLanguageValues_Target", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An invalid number ("{0}") was specified for {1} {2}..
/// </summary>
public static string GridViewDriver_GetValue_An_invalid_number__0__was_specified_for__1__2__ {
get {
return ResourceManager.GetString("GridViewDriver_GetValue_An_invalid_number__0__was_specified_for__1__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to on line {0}.
/// </summary>
public static string GridViewDriver_GetValue_on_line__0__ {
get {
return ResourceManager.GetString("GridViewDriver_GetValue_on_line__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must be a valid number..
/// </summary>
public static string GridViewDriver_GridView_DataError__0__must_be_a_valid_number {
get {
return ResourceManager.GetString("GridViewDriver_GridView_DataError__0__must_be_a_valid_number", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to On line {0}, {1}.
/// </summary>
public static string GridViewDriver_ValidateRow_On_line__0__1__ {
get {
return ResourceManager.GetString("GridViewDriver_ValidateRow_On_line__0__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to On line {0}, row has more than 2 columns.
/// </summary>
public static string GridViewDriver_ValidateRow_On_line__0__row_has_more_than_2_columns {
get {
return ResourceManager.GetString("GridViewDriver_ValidateRow_On_line__0__row_has_more_than_2_columns", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Acquired Time.
/// </summary>
public static string GroupGraphsOrderExtension_LOCALIZED_VALUES_Acquired_Time {
get {
return ResourceManager.GetString("GroupGraphsOrderExtension_LOCALIZED_VALUES_Acquired_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document.
/// </summary>
public static string GroupGraphsOrderExtension_LOCALIZED_VALUES_Document {
get {
return ResourceManager.GetString("GroupGraphsOrderExtension_LOCALIZED_VALUES_Document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Position.
/// </summary>
public static string GroupGraphsOrderExtension_LOCALIZED_VALUES_Position {
get {
return ResourceManager.GetString("GroupGraphsOrderExtension_LOCALIZED_VALUES_Position", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Heat Map.
/// </summary>
public static string HeatMapGraph_RefreshData_Heat_Map {
get {
return ResourceManager.GetString("HeatMapGraph_RefreshData_Heat_Map", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Refresh.
/// </summary>
public static string HeatMapGraph_zedGraphControl1_ContextMenuBuilder_Refresh {
get {
return ResourceManager.GetString("HeatMapGraph_zedGraphControl1_ContextMenuBuilder_Refresh", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Isotope Modification.
/// </summary>
public static string HeavyModList_EditItem_Edit_Isotope_Modification {
get {
return ResourceManager.GetString("HeavyModList_EditItem_Edit_Isotope_Modification", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Isotope Modifications.
/// </summary>
public static string HeavyModList_Title_Edit_Isotope_Modifications {
get {
return ResourceManager.GetString("HeavyModList_Title_Edit_Isotope_Modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Nullable was expected to have a value..
/// </summary>
public static string Helpers_AssumeValue_Nullable_was_expected_to_have_a_value {
get {
return ResourceManager.GetString("Helpers_AssumeValue_Nullable_was_expected_to_have_a_value", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure creating XML ID. Input string may not be empty..
/// </summary>
public static string Helpers_MakeXmlId_Failure_creating_XML_ID_Input_string_may_not_be_empty {
get {
return ResourceManager.GetString("Helpers_MakeXmlId_Failure_creating_XML_ID_Input_string_may_not_be_empty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Select.
/// </summary>
public static string HierarchicalClusterGraph_zedGraphControl1_ContextMenuBuilder_Select {
get {
return ResourceManager.GetString("HierarchicalClusterGraph_zedGraphControl1_ContextMenuBuilder_Select", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Selection.
/// </summary>
public static string HierarchicalClusterGraph_zedGraphControl1_ContextMenuBuilder_Show_Selection {
get {
return ResourceManager.GetString("HierarchicalClusterGraph_zedGraphControl1_ContextMenuBuilder_Show_Selection", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to X-Axis Labels.
/// </summary>
public static string HierarchicalClusterGraph_zedGraphControl1_ContextMenuBuilder_X_Axis_Labels {
get {
return ResourceManager.GetString("HierarchicalClusterGraph_zedGraphControl1_ContextMenuBuilder_X_Axis_Labels", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Y-Axis Labels.
/// </summary>
public static string HierarchicalClusterGraph_zedGraphControl1_ContextMenuBuilder_Y_Axis_Labels {
get {
return ResourceManager.GetString("HierarchicalClusterGraph_zedGraphControl1_ContextMenuBuilder_Y_Axis_Labels", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only showing {0}/{1} peptides.
/// </summary>
public static string HistogramHelper_CreateAndShowFindResults_Only_showing__0___1__peptides {
get {
return ResourceManager.GetString("HistogramHelper_CreateAndShowFindResults_Only_showing__0___1__peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap HomeIcon1 {
get {
object obj = ResourceManager.GetObject("HomeIcon1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to From Clipboard.
/// </summary>
public static string HtmlFragment_ClipBoardText_From_Clipboard {
get {
return ResourceManager.GetString("HtmlFragment_ClipBoardText_From_Clipboard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No data specified.
/// </summary>
public static string HtmlFragment_HtmlFragment_No_data_specified {
get {
return ResourceManager.GetString("HtmlFragment_HtmlFragment_No_data_specified", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to StartFragment is already declared.
/// </summary>
public static string HtmlFragment_HtmlFragment_StartFragment_is_already_declared {
get {
return ResourceManager.GetString("HtmlFragment_HtmlFragment_StartFragment_is_already_declared", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to StartFragment must be declared before EndFragment.
/// </summary>
public static string HtmlFragment_HtmlFragment_StartFragment_must_be_declared_before_EndFragment {
get {
return ResourceManager.GetString("HtmlFragment_HtmlFragment_StartFragment_must_be_declared_before_EndFragment", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to StartHtml is already declared.
/// </summary>
public static string HtmlFragment_HtmlFragment_StartHtml_is_already_declared {
get {
return ResourceManager.GetString("HtmlFragment_HtmlFragment_StartHtml_is_already_declared", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to StartHTML must be declared before endHTML.
/// </summary>
public static string HtmlFragment_HtmlFragment_StartHTML_must_be_declared_before_endHTML {
get {
return ResourceManager.GetString("HtmlFragment_HtmlFragment_StartHTML_must_be_declared_before_endHTML", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Icojam_Blueberry_Basic_Arrow_left {
get {
object obj = ResourceManager.GetObject("Icojam-Blueberry-Basic-Arrow-left", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Icojam_Blueberry_Basic_Arrow_right {
get {
object obj = ResourceManager.GetObject("Icojam-Blueberry-Basic-Arrow-right", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Failed to find document node..
/// </summary>
public static string IdentityNotFoundException_IdentityNotFoundException_Failed_to_find_document_node {
get {
return ResourceManager.GetString("IdentityNotFoundException_IdentityNotFoundException_Failed_to_find_document_node", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Index {0} out of range -1 to {1}.
/// </summary>
public static string IdentityPath_GetPathTo_Index__0__out_of_range_1_to__1__ {
get {
return ResourceManager.GetString("IdentityPath_GetPathTo_Index__0__out_of_range_1_to__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid attempt to perform parent operation on leaf node..
/// </summary>
public static string IdentityPathTraversal_Traverse_Invalid_attempt_to_perform_parent_operation_on_leaf_node {
get {
return ResourceManager.GetString("IdentityPathTraversal_Traverse_Invalid_attempt_to_perform_parent_operation_on_lea" +
"f_node", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT.
/// </summary>
public static string IIrtRegression_DisplayEquation_iRT {
get {
return ResourceManager.GetString("IIrtRegression_DisplayEquation_iRT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measured RT.
/// </summary>
public static string IIrtRegression_DisplayEquation_Measured_RT {
get {
return ResourceManager.GetString("IIrtRegression_DisplayEquation_Measured_RT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must be saved before results may be imported..
/// </summary>
public static string ImportDocResultsDlg_OkDialog_The_document_must_be_saved_before_results_may_be_imported {
get {
return ResourceManager.GetString("ImportDocResultsDlg_OkDialog_The_document_must_be_saved_before_results_may_be_imp" +
"orted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Open FASTA.
/// </summary>
public static string ImportFastaControl_browseFastaBtn_Click_Open_FASTA {
get {
return ResourceManager.GetString("ImportFastaControl_browseFastaBtn_Click_Open_FASTA", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot automatically train mProphet model since no results files are being imported. Continue without automatically training an mProphet model, or go back and add at least one results file..
/// </summary>
public static string ImportFastaControl_cbAutoTrain_CheckedChanged_Cannot_automatically_train_mProphet_model_since_no_results_files_are_being_imported__Continue_without_automatically_training_an_mProphet_model__or_go_back_and_add_at_least_one_results_file_ {
get {
return ResourceManager.GetString("ImportFastaControl_cbAutoTrain_CheckedChanged_Cannot_automatically_train_mProphet" +
"_model_since_no_results_files_are_being_imported__Continue_without_automatically" +
"_training_an_mProphet_model__or_go_back_and_add_at_least_one_results_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed reading the file {0}..
/// </summary>
public static string ImportFastaControl_GetFastaFileContent_Failed_reading_the_file__0__ {
get {
return ResourceManager.GetString("ImportFastaControl_GetFastaFileContent_Failed_reading_the_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A maximum of one decoy per target may be generated when using reversed decoys..
/// </summary>
public static string ImportFastaControl_ImportFasta_A_maximum_of_one_decoy_per_target_may_be_generated_when_using_reversed_decoys_ {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_A_maximum_of_one_decoy_per_target_may_be_generated" +
"_when_using_reversed_decoys_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot automatically train mProphet model without decoys, but decoy options resulted in no decoys being generated. Please increase number of decoys per target, or disable automatic training of mProphet model..
/// </summary>
public static string ImportFastaControl_ImportFasta_Cannot_automatically_train_mProphet_model_without_decoys__but_decoy_options_resulted_in_no_decoys_being_generated__Please_increase_number_of_decoys_per_target__or_disable_automatic_training_of_mProphet_model_ {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_Cannot_automatically_train_mProphet_model_without_" +
"decoys__but_decoy_options_resulted_in_no_decoys_being_generated__Please_increase" +
"_number_of_decoys_per_target__or_disable_automatic_training_of_mProphet_model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change digestion settings.
/// </summary>
public static string ImportFastaControl_ImportFasta_Change_digestion_settings {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_Change_digestion_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change settings.
/// </summary>
public static string ImportFastaControl_ImportFasta_Change_settings {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_Change_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change settings to add precursors.
/// </summary>
public static string ImportFastaControl_ImportFasta_Change_settings_to_add_precursors {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_Change_settings_to_add_precursors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Importing the FASTA did not create any target proteins..
/// </summary>
public static string ImportFastaControl_ImportFasta_Importing_the_FASTA_did_not_create_any_target_proteins_ {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_Importing_the_FASTA_did_not_create_any_target_prot" +
"eins_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insert FASTA.
/// </summary>
public static string ImportFastaControl_ImportFasta_Insert_FASTA {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_Insert_FASTA", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT standards.
/// </summary>
public static string ImportFastaControl_ImportFasta_iRT_standards {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_iRT_standards", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please enter a valid number of decoys per target greater than 0..
/// </summary>
public static string ImportFastaControl_ImportFasta_Please_enter_a_valid_number_of_decoys_per_target_greater_than_0_ {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_Please_enter_a_valid_number_of_decoys_per_target_g" +
"reater_than_0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please import FASTA to add peptides to the document..
/// </summary>
public static string ImportFastaControl_ImportFasta_Please_import_FASTA_to_add_peptides_to_the_document_ {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_Please_import_FASTA_to_add_peptides_to_the_documen" +
"t_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document does not contain any peptides..
/// </summary>
public static string ImportFastaControl_ImportFasta_The_document_does_not_contain_any_peptides_ {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_The_document_does_not_contain_any_peptides_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document does not contain any precursor transitions..
/// </summary>
public static string ImportFastaControl_ImportFasta_The_document_does_not_contain_any_precursor_transitions_ {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_The_document_does_not_contain_any_precursor_transi" +
"tions_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Would you like to change the document settings to automatically pick the precursor transitions specified in the full-scan settings?.
/// </summary>
public static string ImportFastaControl_ImportFasta_Would_you_like_to_change_the_document_settings_to_automatically_pick_the_precursor_transitions_specified_in_the_full_scan_settings_ {
get {
return ResourceManager.GetString("ImportFastaControl_ImportFasta_Would_you_like_to_change_the_document_settings_to_" +
"automatically_pick_the_precursor_transitions_specified_in_the_full_scan_settings" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error adding FASTA file {0}..
/// </summary>
public static string ImportFastaControl_SetFastaContent_Error_adding_FASTA_file__0__ {
get {
return ResourceManager.GetString("ImportFastaControl_SetFastaContent_Error_adding_FASTA_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must contain at least one precursor transition in order to proceed..
/// </summary>
public static string ImportFastaControl_VerifyAtLeastOnePrecursorTransition_The_document_must_contain_at_least_one_precursor_transition_in_order_to_proceed_ {
get {
return ResourceManager.GetString("ImportFastaControl_VerifyAtLeastOnePrecursorTransition_The_document_must_contain_" +
"at_least_one_precursor_transition_in_order_to_proceed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to '{0}' is not a capital letter that corresponds to an amino acid..
/// </summary>
public static string ImportFastaHelper_AddFasta___0___is_not_a_capital_letter_that_corresponds_to_an_amino_acid_ {
get {
return ResourceManager.GetString("ImportFastaHelper_AddFasta___0___is_not_a_capital_letter_that_corresponds_to_an_a" +
"mino_acid_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An unexpected error occurred: .
/// </summary>
public static string ImportFastaHelper_AddFasta_An_unexpected_error_occurred__ {
get {
return ResourceManager.GetString("ImportFastaHelper_AddFasta_An_unexpected_error_occurred__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is no name for this protein.
/// </summary>
public static string ImportFastaHelper_AddFasta_There_is_no_name_for_this_protein {
get {
return ResourceManager.GetString("ImportFastaHelper_AddFasta_There_is_no_name_for_this_protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This must start with '>'.
/// </summary>
public static string ImportFastaHelper_AddFasta_This_must_start_with____ {
get {
return ResourceManager.GetString("ImportFastaHelper_AddFasta_This_must_start_with____", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is no sequence for this protein.
/// </summary>
public static string ImportFastaHelper_CheckSequence_There_is_no_sequence_for_this_protein {
get {
return ResourceManager.GetString("ImportFastaHelper_CheckSequence_There_is_no_sequence_for_this_protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please choose the library you would like to add..
/// </summary>
public static string ImportIonMobilityFromSpectralLibrary_OkDialog_Please_choose_the_library_you_would_like_to_add_ {
get {
return ResourceManager.GetString("ImportIonMobilityFromSpectralLibrary_OkDialog_Please_choose_the_library_you_would" +
"_like_to_add_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only BiblioSpec libraries contain enough ion mobility information to support this operation..
/// </summary>
public static string ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_Only_BiblioSpec_libraries_contain_enough_ion_mobility_information_to_support_this_operation_ {
get {
return ResourceManager.GetString("ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_Only_BiblioSpec_" +
"libraries_contain_enough_ion_mobility_information_to_support_this_operation_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please choose a non redundant library..
/// </summary>
public static string ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_Please_choose_a_non_redundant_library_ {
get {
return ResourceManager.GetString("ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_Please_choose_a_" +
"non_redundant_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please specify a path to an existing spectral library..
/// </summary>
public static string ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_Please_specify_a_path_to_an_existing_spectral_library {
get {
return ResourceManager.GetString("ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_Please_specify_a" +
"_path_to_an_existing_spectral_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please specify a path to an existing spectral library..
/// </summary>
public static string ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_Please_specify_a_path_to_an_existing_spectral_library_ {
get {
return ResourceManager.GetString("ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_Please_specify_a" +
"_path_to_an_existing_spectral_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} appears to be a redundant library..
/// </summary>
public static string ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_The_file__0__appears_to_be_a_redundant_library_ {
get {
return ResourceManager.GetString("ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_The_file__0__app" +
"ears_to_be_a_redundant_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not exist..
/// </summary>
public static string ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_The_file__0__does_not_exist_ {
get {
return ResourceManager.GetString("ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_The_file__0__doe" +
"s_not_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} is not a BiblioSpec library..
/// </summary>
public static string ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_The_file__0__is_not_a_BiblioSpec_library_ {
get {
return ResourceManager.GetString("ImportIonMobilityFromSpectralLibrary_ValidateSpectralLibraryPath_The_file__0__is_" +
"not_a_BiblioSpec_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to MS/MS full-scan settings were configured, please verify or change your current full-scan settings..
/// </summary>
public static string ImportPeptideSearchDlg_ImportPeptideSearchDlg_MS_MS_full_scan_settings_were_configured__please_verify_or_change_your_current_full_scan_settings_ {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_ImportPeptideSearchDlg_MS_MS_full_scan_settings_were_confi" +
"gured__please_verify_or_change_your_current_full_scan_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Next >.
/// </summary>
public static string ImportPeptideSearchDlg_ImportPeptideSearchDlg_Next {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_ImportPeptideSearchDlg_Next", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot build library from OpenSWATH results mixed with results from other tools..
/// </summary>
public static string ImportPeptideSearchDlg_NextPage_Cannot_build_library_from_OpenSWATH_results_mixed_with_results_from_other_tools_ {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_NextPage_Cannot_build_library_from_OpenSWATH_results_mixed" +
"_with_results_from_other_tools_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A FASTA file is required for the DDA search..
/// </summary>
public static string ImportPeptideSearchDlg_NextPage_FastFileMissing_DDASearch {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_NextPage_FastFileMissing_DDASearch", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Finish.
/// </summary>
public static string ImportPeptideSearchDlg_NextPage_Finish {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_NextPage_Finish", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import FASTA (optional).
/// </summary>
public static string ImportPeptideSearchDlg_NextPage_Import_FASTA__optional_ {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_NextPage_Import_FASTA__optional_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import FASTA (required).
/// </summary>
public static string ImportPeptideSearchDlg_NextPage_Import_FASTA__required_ {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_NextPage_Import_FASTA__required_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No isolation windows are configured, but are required for deconvoluting DIA raw files by DIA-Umpire in preparation for DDA search. Go back to full scan settings to configure the isolation scheme..
/// </summary>
public static string ImportPeptideSearchDlg_NextPage_No_isolation_windows_are_configured__ {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_NextPage_No_isolation_windows_are_configured__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No results files were specified. Are you sure you want to continue? Continuing will create a template document with no imported results..
/// </summary>
public static string ImportPeptideSearchDlg_NextPage_No_results_files_were_specified__Are_you_sure_you_want_to_continue__Continuing_will_create_a_template_document_with_no_imported_results_ {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_NextPage_No_results_files_were_specified__Are_you_sure_you" +
"_want_to_continue__Continuing_will_create_a_template_document_with_no_imported_r" +
"esults_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please check your peptide search pipeline or contact Skyline support to ensure retention times appear in your spectral libraries..
/// </summary>
public static string ImportPeptideSearchDlg_NextPage_Please_check_your_peptide_search_pipeline_or_contact_Skyline_support_to_ensure_retention_times_appear_in_your_spectral_libraries_ {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_NextPage_Please_check_your_peptide_search_pipeline_or_cont" +
"act_Skyline_support_to_ensure_retention_times_appear_in_your_spectral_libraries_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Some results files are still missing. Are you sure you want to continue?.
/// </summary>
public static string ImportPeptideSearchDlg_NextPage_Some_results_files_are_still_missing__Are_you_sure_you_want_to_continue_ {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_NextPage_Some_results_files_are_still_missing__Are_you_sur" +
"e_you_want_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document specific spectral library does not have valid retention times..
/// </summary>
public static string ImportPeptideSearchDlg_NextPage_The_document_specific_spectral_library_does_not_have_valid_retention_times_ {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_NextPage_The_document_specific_spectral_library_does_not_h" +
"ave_valid_retention_times_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Full-scan MS1 filtering must be enabled in order to import a peptide search..
/// </summary>
public static string ImportPeptideSearchDlg_UpdateFullScanSettings_Full_scan_MS1_filtering_must_be_enabled_in_order_to_import_a_peptide_search_ {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_UpdateFullScanSettings_Full_scan_MS1_filtering_must_be_ena" +
"bled_in_order_to_import_a_peptide_search_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Full-scan MS1 or MS/MS filtering must be enabled in order to import a peptide search..
/// </summary>
public static string ImportPeptideSearchDlg_UpdateFullScanSettings_Full_scan_MS1_or_MS_MS_filtering_must_be_enabled_in_order_to_import_a_peptide_search_ {
get {
return ResourceManager.GetString("ImportPeptideSearchDlg_UpdateFullScanSettings_Full_scan_MS1_or_MS_MS_filtering_mu" +
"st_be_enabled_in_order_to_import_a_peptide_search_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The current peak scoring model is incompatible with one or more peptides in the document..
/// </summary>
public static string ImportPeptideSearchManager_LoadBackground_The_current_peak_scoring_model_is_incompatible_with_one_or_more_peptides_in_the_document_ {
get {
return ResourceManager.GetString("ImportPeptideSearchManager_LoadBackground_The_current_peak_scoring_model_is_incom" +
"patible_with_one_or_more_peptides_in_the_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Peptide Search.
/// </summary>
public static string ImportResultsControl_browseToResultsFileButton_Click_Import_Peptide_Search {
get {
return ResourceManager.GetString("ImportResultsControl_browseToResultsFileButton_Click_Import_Peptide_Search", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to find missing result files in {0}..
/// </summary>
public static string ImportResultsControl_FindDataFiles_An_error_occurred_attempting_to_find_missing_result_files_in__0__ {
get {
return ResourceManager.GetString("ImportResultsControl_FindDataFiles_An_error_occurred_attempting_to_find_missing_r" +
"esult_files_in__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Searching for missing result files in {0}..
/// </summary>
public static string ImportResultsControl_FindDataFiles_Searching_for_missing_result_files_in__0__ {
get {
return ResourceManager.GetString("ImportResultsControl_FindDataFiles_Searching_for_missing_result_files_in__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to find results files..
/// </summary>
public static string ImportResultsControl_FindResultsFiles_An_error_occurred_attempting_to_find_results_files_ {
get {
return ResourceManager.GetString("ImportResultsControl_FindResultsFiles_An_error_occurred_attempting_to_find_result" +
"s_files_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Searching for matching results files in {0}..
/// </summary>
public static string ImportResultsControl_FindResultsFiles_Searching_for_matching_results_files_in__0__ {
get {
return ResourceManager.GetString("ImportResultsControl_FindResultsFiles_Searching_for_matching_results_files_in__0_" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Searching for Results Files.
/// </summary>
public static string ImportResultsControl_FindResultsFiles_Searching_for_Results_Files {
get {
return ResourceManager.GetString("ImportResultsControl_FindResultsFiles_Searching_for_Results_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not find all the missing results files..
/// </summary>
public static string ImportResultsControl_findResultsFilesButton_Click_Could_not_find_all_the_missing_results_files_ {
get {
return ResourceManager.GetString("ImportResultsControl_findResultsFilesButton_Click_Could_not_find_all_the_missing_" +
"results_files_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results Directory.
/// </summary>
public static string ImportResultsControl_findResultsFilesButton_Click_Results_Directory {
get {
return ResourceManager.GetString("ImportResultsControl_findResultsFilesButton_Click_Results_Directory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import results.
/// </summary>
public static string ImportResultsControl_GetPeptideSearchChromatograms_Import_results {
get {
return ResourceManager.GetString("ImportResultsControl_GetPeptideSearchChromatograms_Import_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Browse for Results Files.
/// </summary>
public static string ImportResultsDIAControl_btnBrowse_Click_Browse_for_Results_Files {
get {
return ResourceManager.GetString("ImportResultsDIAControl_btnBrowse_Click_Browse_for_Results_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The current document does not appear to have enough transitions to require multiple injections.
///Are you sure you want to continue?.
/// </summary>
public static string ImportResultsDlg_CanCreateMultiInjectionMethods_The_current_document_does_not_appear_to_have_enough_transitions_to_require_multiple_injections {
get {
return ResourceManager.GetString("ImportResultsDlg_CanCreateMultiInjectionMethods_The_current_document_does_not_app" +
"ear_to_have_enough_transitions_to_require_multiple_injections", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Chromatograms.
/// </summary>
public static string ImportResultsDlg_DefaultNewName_Default_Name {
get {
return ResourceManager.GetString("ImportResultsDlg_DefaultNewName_Default_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No results found in the folder {0}..
/// </summary>
public static string ImportResultsDlg_GetDataSourcePathsDir_No_results_found_in_the_folder__0__ {
get {
return ResourceManager.GetString("ImportResultsDlg_GetDataSourcePathsDir_No_results_found_in_the_folder__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results Directory.
/// </summary>
public static string ImportResultsDlg_GetDataSourcePathsDir_Results_Directory {
get {
return ResourceManager.GetString("ImportResultsDlg_GetDataSourcePathsDir_Results_Directory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Results Files.
/// </summary>
public static string ImportResultsDlg_GetDataSourcePathsFile_Import_Results_Files {
get {
return ResourceManager.GetString("ImportResultsDlg_GetDataSourcePathsFile_Import_Results_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No results files chosen..
/// </summary>
public static string ImportResultsDlg_GetDataSourcePathsFile_No_results_files_chosen {
get {
return ResourceManager.GetString("ImportResultsDlg_GetDataSourcePathsFile_No_results_files_chosen", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to read sample information from the file {0}..
/// </summary>
public static string ImportResultsDlg_GetWiffSubPaths_An_error_occurred_attempting_to_read_sample_information_from_the_file__0__ {
get {
return ResourceManager.GetString("ImportResultsDlg_GetWiffSubPaths_An_error_occurred_attempting_to_read_sample_info" +
"rmation_from_the_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reading sample names from {0}.
/// </summary>
public static string ImportResultsDlg_GetWiffSubPaths_Reading_sample_names_from__0__ {
get {
return ResourceManager.GetString("ImportResultsDlg_GetWiffSubPaths_Reading_sample_names_from__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sample Names.
/// </summary>
public static string ImportResultsDlg_GetWiffSubPaths_Sample_Names {
get {
return ResourceManager.GetString("ImportResultsDlg_GetWiffSubPaths_Sample_Names", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file may be corrupted, missing, or the correct libraries may not be installed..
/// </summary>
public static string ImportResultsDlg_GetWiffSubPaths_The_file_may_be_corrupted_missing_or_the_correct_libraries_may_not_be_installed {
get {
return ResourceManager.GetString("ImportResultsDlg_GetWiffSubPaths_The_file_may_be_corrupted_missing_or_the_correct" +
"_libraries_may_not_be_installed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A result name may not contain any of the characters '{0}'..
/// </summary>
public static string ImportResultsDlg_OkDialog_A_result_name_may_not_contain_any_of_the_characters___0___ {
get {
return ResourceManager.GetString("ImportResultsDlg_OkDialog_A_result_name_may_not_contain_any_of_the_characters___0" +
"___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The specified name already exists for this document..
/// </summary>
public static string ImportResultsDlg_OkDialog_The_specified_name_already_exists_for_this_document {
get {
return ResourceManager.GetString("ImportResultsDlg_OkDialog_The_specified_name_already_exists_for_this_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must select an existing set of results to which to append new data..
/// </summary>
public static string ImportResultsDlg_OkDialog_You_must_select_an_existing_set_of_results_to_which_to_append_new_data {
get {
return ResourceManager.GetString("ImportResultsDlg_OkDialog_You_must_select_an_existing_set_of_results_to_which_to_" +
"append_new_data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The files you have chosen have a common prefix and suffix.
///Would you like to remove some or all of the prefix or suffix to shorten the names used in Skyline?.
/// </summary>
public static string ImportResultsNameDlg_CommonPrefix_and_Suffix {
get {
return ResourceManager.GetString("ImportResultsNameDlg_CommonPrefix_and_Suffix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The files you have chosen have a common suffix.
///Would you like to remove some or all of this suffix to shorten the names used in Skyline?.
/// </summary>
public static string ImportResultsNameDlg_CommonSuffix {
get {
return ResourceManager.GetString("ImportResultsNameDlg_CommonSuffix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The text '{0}' is not a prefix of the files chosen..
/// </summary>
public static string ImportResultsNameDlg_OkDialog_The_text__0__is_not_a_prefix_of_the_files_chosen {
get {
return ResourceManager.GetString("ImportResultsNameDlg_OkDialog_The_text__0__is_not_a_prefix_of_the_files_chosen", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The text '{0}' is not a suffix of the files chosen..
/// </summary>
public static string ImportResultsNameDlg_OkDialog_The_text__0__is_not_a_suffix_of_the_files_chosen {
get {
return ResourceManager.GetString("ImportResultsNameDlg_OkDialog_The_text__0__is_not_a_suffix_of_the_files_chosen", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following names already exist:
///
///{0}
///
///.
/// </summary>
public static string ImportSkyrHelper_ResolveImportConflicts_ {
get {
return ResourceManager.GetString("ImportSkyrHelper_ResolveImportConflicts_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Resolving conflicts by overwriting..
/// </summary>
public static string ImportSkyrHelper_ResolveImportConflicts_Resolving_conflicts_by_overwriting_ {
get {
return ResourceManager.GetString("ImportSkyrHelper_ResolveImportConflicts_Resolving_conflicts_by_overwriting_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Resolving conflicts by skipping..
/// </summary>
public static string ImportSkyrHelper_ResolveImportConflicts_Resolving_conflicts_by_skipping_ {
get {
return ResourceManager.GetString("ImportSkyrHelper_ResolveImportConflicts_Resolving_conflicts_by_skipping_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The name '{0}' already exists..
/// </summary>
public static string ImportSkyrHelper_ResolveImportConflicts_The_name___0___already_exists_ {
get {
return ResourceManager.GetString("ImportSkyrHelper_ResolveImportConflicts_The_name___0___already_exists_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Please specify a way to resolve conflicts. Use command --report-conflict-resolution=< overwrite | skip >..
/// </summary>
public static string ImportSkyrHelper_ResolveImportConflicts_Use_command {
get {
return ResourceManager.GetString("ImportSkyrHelper_ResolveImportConflicts_Use_command", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Checking for errors....
/// </summary>
public static string ImportTransitionListColumnSelectDlg_CheckForErrors_Checking_for_errors___ {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_CheckForErrors_Checking_for_errors___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Column {0}.
/// </summary>
public static string ImportTransitionListColumnSelectDlg_DisplayData_Column__0_ {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_DisplayData_Column__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The input text did not appear to contain column headers. Use the dropdown control to assign column meanings for import..
/// </summary>
public static string ImportTransitionListColumnSelectDlg_DisplayData_The_input_text_did_not_appear_to_contain_column_headers__Use_the_dropdown_control_to_assign_column_meanings_for_import_ {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_DisplayData_The_input_text_did_not_appear_to_" +
"contain_column_headers__Use_the_dropdown_control_to_assign_column_meanings_for_i" +
"mport_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This column is labeled with the header '{0}' in the input text. Use the dropdown control to assign its meaning for import..
/// </summary>
public static string ImportTransitionListColumnSelectDlg_DisplayData_This_column_is_labeled_with_the_header___0___in_the_input_text__Use_the_dropdown_control_to_assign_its_meaning_for_import_ {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_DisplayData_This_column_is_labeled_with_the_h" +
"eader___0___in_the_input_text__Use_the_dropdown_control_to_assign_its_meaning_fo" +
"r_import_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Decoy.
/// </summary>
public static string ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Decoy {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Decoy", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fragment Name.
/// </summary>
public static string ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Fragment_Name {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Fragment_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ignore Column.
/// </summary>
public static string ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Ignore_Column {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Ignore_Column", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT.
/// </summary>
public static string ImportTransitionListColumnSelectDlg_PopulateComboBoxes_iRT {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_PopulateComboBoxes_iRT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Label Type.
/// </summary>
public static string ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Label_Type {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Label_Type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library Intensity.
/// </summary>
public static string ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Library_Intensity {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Library_Intensity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide Modified Sequence.
/// </summary>
public static string ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Peptide_Modified_Sequence {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Peptide_Modified_Sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor Charge.
/// </summary>
public static string ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Precursor_Charge {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Precursor_Charge", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor m/z.
/// </summary>
public static string ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Precursor_m_z {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Precursor_m_z", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product m/z.
/// </summary>
public static string ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Product_m_z {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Product_m_z", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Protein Name.
/// </summary>
public static string ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Protein_Name {
get {
return ResourceManager.GetString("ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Protein_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A transition contained an error..
/// </summary>
public static string ImportTransitionListErrorDlg_ImportTransitionListErrorDlg_A_transition_contained_an_error_ {
get {
return ResourceManager.GetString("ImportTransitionListErrorDlg_ImportTransitionListErrorDlg_A_transition_contained_" +
"an_error_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A transition contained an error. Skip this transition and import the rest?.
/// </summary>
public static string ImportTransitionListErrorDlg_ImportTransitionListErrorDlg_A_transition_contained_an_error__Skip_this_transition_and_import_the_rest_ {
get {
return ResourceManager.GetString("ImportTransitionListErrorDlg_ImportTransitionListErrorDlg_A_transition_contained_" +
"an_error__Skip_this_transition_and_import_the_rest_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All {0} transitions contained errors. Please check the transition list for errors and try importing again..
/// </summary>
public static string ImportTransitionListErrorDlg_ImportTransitionListErrorDlg_All__0__transitions_contained_errors___Please_check_the_transition_list_for_errors_and_try_importing_again_ {
get {
return ResourceManager.GetString("ImportTransitionListErrorDlg_ImportTransitionListErrorDlg_All__0__transitions_con" +
"tained_errors___Please_check_the_transition_list_for_errors_and_try_importing_ag" +
"ain_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The imported transition contains an error. Please check the transition list and the Skyline settings and try importing again..
/// </summary>
public static string ImportTransitionListErrorDlg_ImportTransitionListErrorDlg_The_imported_transition_contains_an_error__Please_check_the_transition_list_and_the_Skyline_settings_and_try_importing_again_ {
get {
return ResourceManager.GetString("ImportTransitionListErrorDlg_ImportTransitionListErrorDlg_The_imported_transition" +
"_contains_an_error__Please_check_the_transition_list_and_the_Skyline_settings_an" +
"d_try_importing_again_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This transition list cannot be imported as it does not provide values for:.
/// </summary>
public static string ImportTransitionListErrorDlg_ImportTransitionListErrorDlg_This_transition_list_cannot_be_imported_as_it_does_not_provide_values_for_ {
get {
return ResourceManager.GetString("ImportTransitionListErrorDlg_ImportTransitionListErrorDlg_This_transition_list_ca" +
"nnot_be_imported_as_it_does_not_provide_values_for_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The calculator {0} requires all of its standard peptides in order to determine a regression..
/// </summary>
public static string IncompleteStandardException_ERROR_The_calculator__0__requires_all_of_its_standard_peptides_in_order_to_determine_a_regression_ {
get {
return ResourceManager.GetString("IncompleteStandardException_ERROR_The_calculator__0__requires_all_of_its_standard" +
"_peptides_in_order_to_determine_a_regression_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The calculator {0} requires all of its standard peptides in order to determine a regression..
/// </summary>
public static string IncompleteStandardException_IncompleteStandardException_The_calculator__0__requires_all_of_its_standard_peptides_in_order_to_determine_a_regression {
get {
return ResourceManager.GetString("IncompleteStandardException_IncompleteStandardException_The_calculator__0__requir" +
"es_all_of_its_standard_peptides_in_order_to_determine_a_regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error on line {0}, column{1}: {2}.
/// </summary>
public static string InsertSmallMoleculeTransitionList_InsertSmallMoleculeTransitionList_Error_on_line__0___column_1____2_ {
get {
return ResourceManager.GetString("InsertSmallMoleculeTransitionList_InsertSmallMoleculeTransitionList_Error_on_line" +
"__0___column_1____2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error on line {0}: {1}.
/// </summary>
public static string InsertSmallMoleculeTransitionList_InsertSmallMoleculeTransitionList_Error_on_line__0__1_ {
get {
return ResourceManager.GetString("InsertSmallMoleculeTransitionList_InsertSmallMoleculeTransitionList_Error_on_line" +
"__0__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected line in instrument config: {0}.
/// </summary>
public static string InstrumentInfoUtil_ReadInstrumentConfig_Unexpected_line_in_instrument_config__0__ {
get {
return ResourceManager.GetString("InstrumentInfoUtil_ReadInstrumentConfig_Unexpected_line_in_instrument_config__0__" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adducts:
///
///Ion formulas may contain an adduct description using the defacto standard notation as seen at http://fiehnlab.ucdavis.edu/staff/kind/Metabolomics/MS-Adduct-Calculator (e.g. "C47H51NO14[M+IsoProp+H]").
///
///When only the ion charge is known (often the case with fragments) charge-only adducts such as "[M+]" (z=1), "[M-]" (z=-1), "[M+3]" (z=3), etc., may be used.
///
///Multipliers (e.g. the "2" in "[2M+K]") and isotope labels (e.g. the "2Cl37" in "[M2Cl37+H]") are supported.
///
///Recognized adduct components [rest of string was truncated]";.
/// </summary>
public static string IonInfo_AdductTips_ {
get {
return ResourceManager.GetString("IonInfo_AdductTips_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ion Mobility Library Files.
/// </summary>
public static string IonMobilityDb_FILTER_IONMOBILITYLIBRARY_Ion_Mobility_Library_Files {
get {
return ResourceManager.GetString("IonMobilityDb_FILTER_IONMOBILITYLIBRARY_Ion_Mobility_Library_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading ion mobility library {0}.
/// </summary>
public static string IonMobilityDb_GetIonMobilityDb_Loading_ion_mobility_library__0_ {
get {
return ResourceManager.GetString("IonMobilityDb_GetIonMobilityDb_Loading_ion_mobility_library__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please provide a path to an existing ion mobility library..
/// </summary>
public static string IonMobilityDb_GetIonMobilityDb_Please_provide_a_path_to_an_existing_ion_mobility_library_ {
get {
return ResourceManager.GetString("IonMobilityDb_GetIonMobilityDb_Please_provide_a_path_to_an_existing_ion_mobility_" +
"library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} is not a valid ion mobility library file..
/// </summary>
public static string IonMobilityDb_GetIonMobilityDb_The_file__0__is_not_a_valid_ion_mobility_library_file_ {
get {
return ResourceManager.GetString("IonMobilityDb_GetIonMobilityDb_The_file__0__is_not_a_valid_ion_mobility_library_f" +
"ile_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The ion mobility library file {0} could not be found. Perhaps you did not have sufficient privileges to create it?.
/// </summary>
public static string IonMobilityDb_GetIonMobilityDb_The_ion_mobility_library_file__0__could_not_be_found__Perhaps_you_did_not_have_sufficient_privileges_to_create_it_ {
get {
return ResourceManager.GetString("IonMobilityDb_GetIonMobilityDb_The_ion_mobility_library_file__0__could_not_be_fou" +
"nd__Perhaps_you_did_not_have_sufficient_privileges_to_create_it_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The path containing ion mobility library {0} does not exist..
/// </summary>
public static string IonMobilityDb_GetIonMobilityDb_The_path_containing_ion_mobility_library__0__does_not_exist_ {
get {
return ResourceManager.GetString("IonMobilityDb_GetIonMobilityDb_The_path_containing_ion_mobility_library__0__does_" +
"not_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You do not have privileges to access the ion mobility library file {0}.
/// </summary>
public static string IonMobilityDb_GetIonMobilityDb_You_do_not_have_privileges_to_access_the_ion_mobility_library_file__0_ {
get {
return ResourceManager.GetString("IonMobilityDb_GetIonMobilityDb_You_do_not_have_privileges_to_access_the_ion_mobil" +
"ity_library_file__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None.
/// </summary>
public static string IonMobilityFilter_IonMobilityUnitsL10NString_None {
get {
return ResourceManager.GetString("IonMobilityFilter_IonMobilityUnitsL10NString_None", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1/K0 (Vs/cm^2).
/// </summary>
public static string IonMobilityFilter_IonMobilityUnitsString__1_K0__Vs_cm_2_ {
get {
return ResourceManager.GetString("IonMobilityFilter_IonMobilityUnitsString__1_K0__Vs_cm_2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Compensation Voltage (V).
/// </summary>
public static string IonMobilityFilter_IonMobilityUnitsString_Compensation_Voltage__V_ {
get {
return ResourceManager.GetString("IonMobilityFilter_IonMobilityUnitsString_Compensation_Voltage__V_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Drift Time (ms).
/// </summary>
public static string IonMobilityFilter_IonMobilityUnitsString_Drift_Time__ms_ {
get {
return ResourceManager.GetString("IonMobilityFilter_IonMobilityUnitsString_Drift_Time__ms_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fixed window size must be greater than 0..
/// </summary>
public static string IonMobilityFilteringUserControl_ValidateFixedWindow_Fixed_window_size_must_be_greater_than_0_ {
get {
return ResourceManager.GetString("IonMobilityFilteringUserControl_ValidateFixedWindow_Fixed_window_size_must_be_gre" +
"ater_than_0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed using results to populate ion mobility library:.
/// </summary>
public static string IonMobilityFinder_ProcessMSLevel_Failed_using_results_to_populate_ion_mobility_library_ {
get {
return ResourceManager.GetString("IonMobilityFinder_ProcessMSLevel_Failed_using_results_to_populate_ion_mobility_li" +
"brary_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to will be deleted because the libraries they depend on have changed. Do you want to continue?.
/// </summary>
public static string IonMobilityLibraryList_AcceptList_will_be_deleted_because_the_libraries_they_depend_on_have_changed__Do_you_want_to_continue_ {
get {
return ResourceManager.GetString("IonMobilityLibraryList_AcceptList_will_be_deleted_because_the_libraries_they_depe" +
"nd_on_have_changed__Do_you_want_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ion Mobility Libraries:.
/// </summary>
public static string IonMobilityLibraryList_Label_Ion_Mobility_Libraries_ {
get {
return ResourceManager.GetString("IonMobilityLibraryList_Label_Ion_Mobility_Libraries_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Ion Mobility Libraries.
/// </summary>
public static string IonMobilityLibraryList_Title_Edit_Ion_Mobility_Libraries {
get {
return ResourceManager.GetString("IonMobilityLibraryList_Title_Edit_Ion_Mobility_Libraries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CCS:.
/// </summary>
public static string IonMobilityObject_ToString_CCS_ {
get {
return ResourceManager.GetString("IonMobilityObject_ToString_CCS_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to HEO:.
/// </summary>
public static string IonMobilityObject_ToString_HEO_ {
get {
return ResourceManager.GetString("IonMobilityObject_ToString_HEO_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ion mobility predictors using an ion mobility library must include per-charge regression values..
/// </summary>
public static string IonMobilityPredictor_Validate_Ion_mobility_predictors_using_an_ion_mobility_library_must_include_per_charge_regression_values_ {
get {
return ResourceManager.GetString("IonMobilityPredictor_Validate_Ion_mobility_predictors_using_an_ion_mobility_libra" +
"ry_must_include_per_charge_regression_values_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The ion mobility library file {0} could not be found. Perhaps you did not have sufficient privileges to create it?.
/// </summary>
public static string IonMobilityTest_TestGetIonMobilityDBErrorHandling_The_ion_mobility_library_file__0__could_not_be_found__Perhaps_you_did_not_have_sufficient_privileges_to_create_it_ {
get {
return ResourceManager.GetString("IonMobilityTest_TestGetIonMobilityDBErrorHandling_The_ion_mobility_library_file__" +
"0__could_not_be_found__Perhaps_you_did_not_have_sufficient_privileges_to_create_" +
"it_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Ions_1 {
get {
object obj = ResourceManager.GetObject("Ions_1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Ions_2 {
get {
object obj = ResourceManager.GetObject("Ions_2", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Ions_A {
get {
object obj = ResourceManager.GetObject("Ions_A", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Ions_B {
get {
object obj = ResourceManager.GetObject("Ions_B", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Ions_C {
get {
object obj = ResourceManager.GetObject("Ions_C", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Ions_fragments {
get {
object obj = ResourceManager.GetObject("Ions_fragments", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Ions_X {
get {
object obj = ResourceManager.GetObject("Ions_X", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Ions_Y {
get {
object obj = ResourceManager.GetObject("Ions_Y", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Ions_Z {
get {
object obj = ResourceManager.GetObject("Ions_Z", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to custom.
/// </summary>
public static string IonTypeExtension_LOCALIZED_VALUES_custom {
get {
return ResourceManager.GetString("IonTypeExtension_LOCALIZED_VALUES_custom", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to precursor.
/// </summary>
public static string IonTypeExtension_LOCALIZED_VALUES_precursor {
get {
return ResourceManager.GetString("IonTypeExtension_LOCALIZED_VALUES_precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding peptides.
/// </summary>
public static string IrtDb_AddPeptides_Adding_peptides {
get {
return ResourceManager.GetString("IrtDb_AddPeptides_Adding_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT Database Files.
/// </summary>
public static string IrtDb_FILTER_IRTDB_iRT_Database_Files {
get {
return ResourceManager.GetString("IrtDb_FILTER_IRTDB_iRT_Database_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Database path cannot be null.
/// </summary>
public static string IrtDb_GetIrtDb_Database_path_cannot_be_null {
get {
return ResourceManager.GetString("IrtDb_GetIrtDb_Database_path_cannot_be_null", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading iRT database {0}.
/// </summary>
public static string IrtDb_GetIrtDb_Loading_iRT_database__0_ {
get {
return ResourceManager.GetString("IrtDb_GetIrtDb_Loading_iRT_database__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} could not be created. Perhaps you do not have sufficient privileges..
/// </summary>
public static string IrtDb_GetIrtDb_The_file__0__could_not_be_created_Perhaps_you_do_not_have_sufficient_privileges {
get {
return ResourceManager.GetString("IrtDb_GetIrtDb_The_file__0__could_not_be_created_Perhaps_you_do_not_have_sufficie" +
"nt_privileges", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} could not be opened..
/// </summary>
public static string IrtDb_GetIrtDb_The_file__0__could_not_be_opened {
get {
return ResourceManager.GetString("IrtDb_GetIrtDb_The_file__0__could_not_be_opened", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not exist..
/// </summary>
public static string IrtDb_GetIrtDb_The_file__0__does_not_exist_ {
get {
return ResourceManager.GetString("IrtDb_GetIrtDb_The_file__0__does_not_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} is not a valid iRT database file..
/// </summary>
public static string IrtDb_GetIrtDb_The_file__0__is_not_a_valid_iRT_database_file {
get {
return ResourceManager.GetString("IrtDb_GetIrtDb_The_file__0__is_not_a_valid_iRT_database_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The path containing {0} does not exist.
/// </summary>
public static string IrtDb_GetIrtDb_The_path_containing__0__does_not_exist {
get {
return ResourceManager.GetString("IrtDb_GetIrtDb_The_path_containing__0__does_not_exist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You do not have privileges to access the file {0}.
/// </summary>
public static string IrtDb_GetIrtDb_You_do_not_have_privileges_to_access_the_file__0_ {
get {
return ResourceManager.GetString("IrtDb_GetIrtDb_You_do_not_have_privileges_to_access_the_file__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT standards.
/// </summary>
public static string IrtDb_MakeDocumentXml_iRT_standards {
get {
return ResourceManager.GetString("IrtDb_MakeDocumentXml_iRT_standards", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Linear.
/// </summary>
public static string IrtRegressionType_Linear {
get {
return ResourceManager.GetString("IrtRegressionType_Linear", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Logarithmic.
/// </summary>
public static string IrtRegressionType_Logarithmic {
get {
return ResourceManager.GetString("IrtRegressionType_Logarithmic", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Lowess.
/// </summary>
public static string IrtRegressionType_Lowess {
get {
return ResourceManager.GetString("IrtRegressionType_Lowess", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Automatic.
/// </summary>
public static string IrtStandard_AUTO_Automatic {
get {
return ResourceManager.GetString("IrtStandard_AUTO_Automatic", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No document to import.
/// </summary>
public static string IrtStandard_DocumentStream_No_document_to_import {
get {
return ResourceManager.GetString("IrtStandard_DocumentStream_No_document_to_import", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT Standards.
/// </summary>
public static string IrtStandardList_Label_iRT_Standards {
get {
return ResourceManager.GetString("IrtStandardList_Label_iRT_Standards", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit iRT Standards.
/// </summary>
public static string IrtStandardList_Title_Edit_iRT_Standards {
get {
return ResourceManager.GetString("IrtStandardList_Title_Edit_iRT_Standards", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation scheme can specify multiplexed windows only for prespecified isolation windows.
/// </summary>
public static string IsolationScheme_DoValidate_Isolation_scheme_can_specify_multiplexed_windows_only_for_prespecified_isolation_windows {
get {
return ResourceManager.GetString("IsolationScheme_DoValidate_Isolation_scheme_can_specify_multiplexed_windows_only_" +
"for_prespecified_isolation_windows", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation scheme cannot have a filter and a prespecifed isolation window.
/// </summary>
public static string IsolationScheme_DoValidate_Isolation_scheme_cannot_have_a_filter_and_a_prespecifed_isolation_window {
get {
return ResourceManager.GetString("IsolationScheme_DoValidate_Isolation_scheme_cannot_have_a_filter_and_a_prespecife" +
"d_isolation_window", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation scheme cannot have a right filter without a left filter.
/// </summary>
public static string IsolationScheme_DoValidate_Isolation_scheme_cannot_have_a_right_filter_without_a_left_filter {
get {
return ResourceManager.GetString("IsolationScheme_DoValidate_Isolation_scheme_cannot_have_a_right_filter_without_a_" +
"left_filter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation scheme for all ions cannot contain isolation windows.
/// </summary>
public static string IsolationScheme_DoValidate_Isolation_scheme_for_all_ions_cannot_contain_isolation_windows {
get {
return ResourceManager.GetString("IsolationScheme_DoValidate_Isolation_scheme_for_all_ions_cannot_contain_isolation" +
"_windows", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Multiplexed windows require at least one window per scan.
/// </summary>
public static string IsolationScheme_DoValidate_Multiplexed_windows_require_at_least_one_window_per_scan {
get {
return ResourceManager.GetString("IsolationScheme_DoValidate_Multiplexed_windows_require_at_least_one_window_per_sc" +
"an", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Special handling applies only to prespecified isolation windows.
/// </summary>
public static string IsolationScheme_DoValidate_Special_handling_applies_only_to_prespecified_isolation_windows {
get {
return ResourceManager.GetString("IsolationScheme_DoValidate_Special_handling_applies_only_to_prespecified_isolatio" +
"n_windows", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The number of prespecified isolation windows must be a multiple of the windows per scan in multiplexed sampling..
/// </summary>
public static string IsolationScheme_DoValidate_The_number_of_prespecified_isolation_windows_must_be_a_multiple_of_the_windows_per_scan_in_multiplexed_sampling {
get {
return ResourceManager.GetString("IsolationScheme_DoValidate_The_number_of_prespecified_isolation_windows_must_be_a" +
"_multiple_of_the_windows_per_scan_in_multiplexed_sampling", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor m/z filter must be between {0} and {1}.
/// </summary>
public static string IsolationScheme_DoValidate_The_precursor_m_z_filter_must_be_between__0__and__1_ {
get {
return ResourceManager.GetString("IsolationScheme_DoValidate_The_precursor_m_z_filter_must_be_between__0__and__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected name '{0}' for {1} isolation scheme.
/// </summary>
public static string IsolationScheme_DoValidate_Unexpected_name___0___for__1__isolation_scheme {
get {
return ResourceManager.GetString("IsolationScheme_DoValidate_Unexpected_name___0___for__1__isolation_scheme", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Windows per scan requires multiplexed isolation windows.
/// </summary>
public static string IsolationScheme_DoValidate_Windows_per_scan_requires_multiplexed_isolation_windows {
get {
return ResourceManager.GetString("IsolationScheme_DoValidate_Windows_per_scan_requires_multiplexed_isolation_window" +
"s", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results (0.5 margin).
/// </summary>
public static string IsolationSchemeList_GetDefaults_Results__0_5_margin_ {
get {
return ResourceManager.GetString("IsolationSchemeList_GetDefaults_Results__0_5_margin_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results only.
/// </summary>
public static string IsolationSchemeList_GetDefaults_Results_only {
get {
return ResourceManager.GetString("IsolationSchemeList_GetDefaults_Results_only", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SWATH (15 m/z).
/// </summary>
public static string IsolationSchemeList_GetDefaults_SWATH__15_m_z_ {
get {
return ResourceManager.GetString("IsolationSchemeList_GetDefaults_SWATH__15_m_z_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SWATH (25 m/z).
/// </summary>
public static string IsolationSchemeList_GetDefaults_SWATH__25_m_z_ {
get {
return ResourceManager.GetString("IsolationSchemeList_GetDefaults_SWATH__25_m_z_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SWATH (VW 100).
/// </summary>
public static string IsolationSchemeList_GetDefaults_SWATH__VW_100_ {
get {
return ResourceManager.GetString("IsolationSchemeList_GetDefaults_SWATH__VW_100_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SWATH (VW 64).
/// </summary>
public static string IsolationSchemeList_GetDefaults_SWATH__VW_64_ {
get {
return ResourceManager.GetString("IsolationSchemeList_GetDefaults_SWATH__VW_64_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Isolation scheme:.
/// </summary>
public static string IsolationSchemeList_Label_Isolation_scheme {
get {
return ResourceManager.GetString("IsolationSchemeList_Label_Isolation_scheme", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Isolation Scheme.
/// </summary>
public static string IsolationSchemeList_Title_Edit_Isolation_Scheme {
get {
return ResourceManager.GetString("IsolationSchemeList_Title_Edit_Isolation_Scheme", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reading isolation scheme from {0}.
/// </summary>
public static string IsolationSchemeReader_ReadIsolationRangesFromFiles_Reading_isolation_scheme_from__0_ {
get {
return ResourceManager.GetString("IsolationSchemeReader_ReadIsolationRangesFromFiles_Reading_isolation_scheme_from_" +
"_0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fixed.
/// </summary>
public static string IsolationWidthType_FIXED_Fixed {
get {
return ResourceManager.GetString("IsolationWidthType_FIXED_Fixed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results.
/// </summary>
public static string IsolationWidthType_RESULTS_Results {
get {
return ResourceManager.GetString("IsolationWidthType_RESULTS_Results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results with margin.
/// </summary>
public static string IsolationWidthType_RESULTS_WITH_MARGIN_Results_with_margin {
get {
return ResourceManager.GetString("IsolationWidthType_RESULTS_WITH_MARGIN_Results_with_margin", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation window End must be between {0} and {1}..
/// </summary>
public static string IsolationWindow_DoValidate_Isolation_window_End_must_be_between__0__and__1__ {
get {
return ResourceManager.GetString("IsolationWindow_DoValidate_Isolation_window_End_must_be_between__0__and__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation window margin must be non-negative..
/// </summary>
public static string IsolationWindow_DoValidate_Isolation_window_margin_must_be_non_negative {
get {
return ResourceManager.GetString("IsolationWindow_DoValidate_Isolation_window_margin_must_be_non_negative", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation window margins cover the entire isolation window at the extremes of the instrument range..
/// </summary>
public static string IsolationWindow_DoValidate_Isolation_window_margins_cover_the_entire_isolation_window_at_the_extremes_of_the_instrument_range {
get {
return ResourceManager.GetString("IsolationWindow_DoValidate_Isolation_window_margins_cover_the_entire_isolation_wi" +
"ndow_at_the_extremes_of_the_instrument_range", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation window Start must be between {0} and {1}..
/// </summary>
public static string IsolationWindow_DoValidate_Isolation_window_Start_must_be_between__0__and__1__ {
get {
return ResourceManager.GetString("IsolationWindow_DoValidate_Isolation_window_Start_must_be_between__0__and__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation window Start value is greater than the End value..
/// </summary>
public static string IsolationWindow_DoValidate_Isolation_window_Start_value_is_greater_than_the_End_value {
get {
return ResourceManager.GetString("IsolationWindow_DoValidate_Isolation_window_Start_value_is_greater_than_the_End_v" +
"alue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Target value is not within the range of the isolation window..
/// </summary>
public static string IsolationWindow_DoValidate_Target_value_is_not_within_the_range_of_the_isolation_window {
get {
return ResourceManager.GetString("IsolationWindow_DoValidate_Target_value_is_not_within_the_range_of_the_isolation_" +
"window", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isolation window requires a Target value..
/// </summary>
public static string IsolationWindow_TargetMatches_Isolation_window_requires_a_Target_value {
get {
return ResourceManager.GetString("IsolationWindow_TargetMatches_Isolation_window_requires_a_Target_value", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Minimum abundance {0} too high.
/// </summary>
public static string IsotopeDistInfo_IsotopeDistInfo_Minimum_abundance__0__too_high {
get {
return ResourceManager.GetString("IsotopeDistInfo_IsotopeDistInfo_Minimum_abundance__0__too_high", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Atom percent enrichment {0} must be between {1} and {2}.
/// </summary>
public static string IsotopeEnrichmentItem_DoValidate_Atom_percent_enrichment__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("IsotopeEnrichmentItem_DoValidate_Atom_percent_enrichment__0__must_be_between__1__" +
"and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isotope enrichment is not supported for the symbol {0}.
/// </summary>
public static string IsotopeEnrichmentItem_DoValidate_Isotope_enrichment_is_not_supported_for_the_symbol__0__ {
get {
return ResourceManager.GetString("IsotopeEnrichmentItem_DoValidate_Isotope_enrichment_is_not_supported_for_the_symb" +
"ol__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} = {1}%.
/// </summary>
public static string IsotopeEnrichmentItem_ToString__0__1__Percent {
get {
return ResourceManager.GetString("IsotopeEnrichmentItem_ToString__0__1__Percent", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default.
/// </summary>
public static string IsotopeEnrichments_DEFAULT_Default {
get {
return ResourceManager.GetString("IsotopeEnrichments_DEFAULT_Default", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Isotope labeling entrichment:.
/// </summary>
public static string IsotopeEnrichmentsList_Label_Isotope_labeling_entrichment {
get {
return ResourceManager.GetString("IsotopeEnrichmentsList_Label_Isotope_labeling_entrichment", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Isotope Labeling Enrichments.
/// </summary>
public static string IsotopeEnrichmentsList_Title_Edit_Isotope_Labeling_Enrichments {
get {
return ResourceManager.GetString("IsotopeEnrichmentsList_Title_Edit_Isotope_Labeling_Enrichments", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Permuting isotope modifications.
/// </summary>
public static string IsotopeModificationPermuter_PermuteIsotopeModifications_Permuting_isotope_modifications {
get {
return ResourceManager.GetString("IsotopeModificationPermuter_PermuteIsotopeModifications_Permuting_isotope_modific" +
"ations", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to KDE Aligner.
/// </summary>
public static string KdeAlignerFactory_ToString_KDE_Aligner {
get {
return ResourceManager.GetString("KdeAlignerFactory_ToString_KDE_Aligner", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Keep {
get {
object obj = ResourceManager.GetObject("Keep", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to LabelType.
/// </summary>
public static string LabelTypeComboDriver_LabelTypeComboDriver_LabelType {
get {
return ResourceManager.GetString("LabelTypeComboDriver_LabelTypeComboDriver_LabelType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <Edit list...>.
/// </summary>
public static string LabelTypeComboDriver_LoadList_Edit_list {
get {
return ResourceManager.GetString("LabelTypeComboDriver_LoadList_Edit_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to I&nternal standard type:.
/// </summary>
public static string LabelTypeComboDriver_LoadList_Internal_standard_type {
get {
return ResourceManager.GetString("LabelTypeComboDriver_LoadList_Internal_standard_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to I&nternal standard types:.
/// </summary>
public static string LabelTypeComboDriver_LoadList_Internal_standard_types {
get {
return ResourceManager.GetString("LabelTypeComboDriver_LoadList_Internal_standard_types", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to none.
/// </summary>
public static string LabelTypeComboDriver_LoadList_none {
get {
return ResourceManager.GetString("LabelTypeComboDriver_LoadList_none", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap LabKey {
get {
object obj = ResourceManager.GetObject("LabKey", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Identified count.
/// </summary>
public static string LegacyIdentifiedCountCalc_LegacyIdentifiedCountCalc_Legacy_identified_count {
get {
return ResourceManager.GetString("LegacyIdentifiedCountCalc_LegacyIdentifiedCountCalc_Legacy_identified_count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Log co-eluting area.
/// </summary>
public static string LegacyLogUnforcedAreaCalc_LegacyLogUnforcedAreaCalc_Legacy_log_unforced_area {
get {
return ResourceManager.GetString("LegacyLogUnforcedAreaCalc_LegacyLogUnforcedAreaCalc_Legacy_log_unforced_area", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default.
/// </summary>
public static string LegacyScoringModel_DEFAULT_NAME_Default {
get {
return ResourceManager.GetString("LegacyScoringModel_DEFAULT_NAME_Default", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Legacy scoring model is not trained..
/// </summary>
public static string LegacyScoringModel_DoValidate_Legacy_scoring_model_is_not_trained_ {
get {
return ResourceManager.GetString("LegacyScoringModel_DoValidate_Legacy_scoring_model_is_not_trained_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid legacy model..
/// </summary>
public static string LegacyScoringModel_ReadXml_Invalid_legacy_model_ {
get {
return ResourceManager.GetString("LegacyScoringModel_ReadXml_Invalid_legacy_model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Co-elution count.
/// </summary>
public static string LegacyUnforcedCountScoreCalc_LegacyUnforcedCountScoreCalc_Legacy_unforced_count {
get {
return ResourceManager.GetString("LegacyUnforcedCountScoreCalc_LegacyUnforcedCountScoreCalc_Legacy_unforced_count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default co-elution count.
/// </summary>
public static string LegacyUnforcedCountScoreDefaultCalc_Name_Default_co_elution_count {
get {
return ResourceManager.GetString("LegacyUnforcedCountScoreDefaultCalc_Name_Default_co_elution_count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reference co-elution count.
/// </summary>
public static string LegacyUnforcedCountScoreStandardCalc_LegacyUnforcedCountScoreStandardCalc_Legacy_unforced_count_standard {
get {
return ResourceManager.GetString("LegacyUnforcedCountScoreStandardCalc_LegacyUnforcedCountScoreStandardCalc_Legacy_" +
"unforced_count_standard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The number '{0}' is not in the correct format..
/// </summary>
public static string LibKeyModificationMatcher_EnumerateSequenceInfos_The_number___0___is_not_in_the_correct_format_ {
get {
return ResourceManager.GetString("LibKeyModificationMatcher_EnumerateSequenceInfos_The_number___0___is_not_in_the_c" +
"orrect_format_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data truncation in library header. File may be corrupted..
/// </summary>
public static string Library_ReadComplete_Data_truncation_in_library_header_File_may_be_corrupted {
get {
return ResourceManager.GetString("Library_ReadComplete_Data_truncation_in_library_header_File_may_be_corrupted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} distinct CiRT peptides were found. How many would you like to use as iRT standards?.
/// </summary>
public static string LibraryBuildNotificationHandler_AddIrts__0__distinct_CiRT_peptides_were_found__How_many_would_you_like_to_use_as_iRT_standards_ {
get {
return ResourceManager.GetString("LibraryBuildNotificationHandler_AddIrts__0__distinct_CiRT_peptides_were_found__Ho" +
"w_many_would_you_like_to_use_as_iRT_standards_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding iRTs to library.
/// </summary>
public static string LibraryBuildNotificationHandler_AddIrts_Adding_iRTs_to_library {
get {
return ResourceManager.GetString("LibraryBuildNotificationHandler_AddIrts_Adding_iRTs_to_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred trying to add iRTs to the library..
/// </summary>
public static string LibraryBuildNotificationHandler_AddIrts_An_error_occurred_trying_to_add_iRTs_to_the_library_ {
get {
return ResourceManager.GetString("LibraryBuildNotificationHandler_AddIrts_An_error_occurred_trying_to_add_iRTs_to_t" +
"he_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading library.
/// </summary>
public static string LibraryBuildNotificationHandler_AddIrts_Loading_library {
get {
return ResourceManager.GetString("LibraryBuildNotificationHandler_AddIrts_Loading_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading retention time providers.
/// </summary>
public static string LibraryBuildNotificationHandler_AddIrts_Loading_retention_time_providers {
get {
return ResourceManager.GetString("LibraryBuildNotificationHandler_AddIrts_Loading_retention_time_providers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Processing retention times.
/// </summary>
public static string LibraryBuildNotificationHandler_AddIrts_Processing_retention_times {
get {
return ResourceManager.GetString("LibraryBuildNotificationHandler_AddIrts_Processing_retention_times", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add retention time predictor.
/// </summary>
public static string LibraryBuildNotificationHandler_AddRetentionTimePredictor_Add_retention_time_predictor {
get {
return ResourceManager.GetString("LibraryBuildNotificationHandler_AddRetentionTimePredictor_Add_retention_time_pred" +
"ictor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding iRT Database.
/// </summary>
public static string LibraryGridViewDriver_AddIrtDatabase_Adding_iRT_Database {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddIrtDatabase_Adding_iRT_Database", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to load the iRT database file {0}..
/// </summary>
public static string LibraryGridViewDriver_AddIrtDatabase_An_error_occurred_attempting_to_load_the_iRT_database_file__0__ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddIrtDatabase_An_error_occurred_attempting_to_load_the_iRT" +
"_database_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding optimization library.
/// </summary>
public static string LibraryGridViewDriver_AddOptimizationLibrary_Adding_optimization_library {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddOptimizationLibrary_Adding_optimization_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding optimization values from {0}.
/// </summary>
public static string LibraryGridViewDriver_AddOptimizationLibrary_Adding_optimization_values_from__0_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddOptimizationLibrary_Adding_optimization_values_from__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to load the optimization library file {0}..
/// </summary>
public static string LibraryGridViewDriver_AddOptimizationLibrary_An_error_occurred_attempting_to_load_the_optimization_library_file__0__ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddOptimizationLibrary_An_error_occurred_attempting_to_load" +
"_the_optimization_library_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A single run does not have high enough correlation to the existing iRT values to allow retention time conversion..
/// </summary>
public static string LibraryGridViewDriver_AddProcessedIrts_A_single_run_does_not_have_high_enough_correlation_to_the_existing_iRT_values_to_allow_retention_time_conversion {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddProcessedIrts_A_single_run_does_not_have_high_enough_cor" +
"relation_to_the_existing_iRT_values_to_allow_retention_time_conversion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Correlation to the existing iRT values are not high enough to allow retention time conversion..
/// </summary>
public static string LibraryGridViewDriver_AddProcessedIrts_Correlation_to_the_existing_iRT_values_are_not_high_enough_to_allow_retention_time_conversion {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddProcessedIrts_Correlation_to_the_existing_iRT_values_are" +
"_not_high_enough_to_allow_retention_time_conversion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None of {0} runs were found with high enough correlation to the existing iRT values to allow retention time conversion..
/// </summary>
public static string LibraryGridViewDriver_AddProcessedIrts_None_of__0__runs_were_found_with_high_enough_correlation_to_the_existing_iRT_values_to_allow_retention_time_conversion {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddProcessedIrts_None_of__0__runs_were_found_with_high_enou" +
"gh_correlation_to_the_existing_iRT_values_to_allow_retention_time_conversion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding Results.
/// </summary>
public static string LibraryGridViewDriver_AddResults_Adding_Results {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddResults_Adding_Results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding retention times from imported results.
/// </summary>
public static string LibraryGridViewDriver_AddResults_Adding_retention_times_from_imported_results {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddResults_Adding_retention_times_from_imported_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to add results from current document..
/// </summary>
public static string LibraryGridViewDriver_AddResults_An_error_occurred_attempting_to_add_results_from_current_document {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddResults_An_error_occurred_attempting_to_add_results_from" +
"_current_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The active document must contain results in order to add iRT values..
/// </summary>
public static string LibraryGridViewDriver_AddResults_The_active_document_must_contain_results_in_order_to_add_iRT_values {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddResults_The_active_document_must_contain_results_in_orde" +
"r_to_add_iRT_values", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The active document must contain results in order to add optimized values..
/// </summary>
public static string LibraryGridViewDriver_AddResults_The_active_document_must_contain_results_in_order_to_add_optimized_values_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddResults_The_active_document_must_contain_results_in_orde" +
"r_to_add_optimized_values_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding retention times from {0}.
/// </summary>
public static string LibraryGridViewDriver_AddSpectralLibrary_Adding_retention_times_from__0__ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddSpectralLibrary_Adding_retention_times_from__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding Spectral Library.
/// </summary>
public static string LibraryGridViewDriver_AddSpectralLibrary_Adding_Spectral_Library {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddSpectralLibrary_Adding_Spectral_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to load the library file {0}..
/// </summary>
public static string LibraryGridViewDriver_AddSpectralLibrary_An_error_occurred_attempting_to_load_the_library_file__0__ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddSpectralLibrary_An_error_occurred_attempting_to_load_the" +
"_library_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The library {0} does not contain retention time information..
/// </summary>
public static string LibraryGridViewDriver_AddSpectralLibrary_The_library__0__does_not_contain_retention_time_information {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddSpectralLibrary_The_library__0__does_not_contain_retenti" +
"on_time_information", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while recalibrating..
/// </summary>
public static string LibraryGridViewDriver_AddToLibrary_An_error_occurred_while_recalibrating_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddToLibrary_An_error_occurred_while_recalibrating_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to recalibrate the iRT standard values relative to the peptides being added?.
/// </summary>
public static string LibraryGridViewDriver_AddToLibrary_Do_you_want_to_recalibrate_the_iRT_standard_values_relative_to_the_peptides_being_added_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddToLibrary_Do_you_want_to_recalibrate_the_iRT_standard_va" +
"lues_relative_to_the_peptides_being_added_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Recalibrate iRT Standard Peptides.
/// </summary>
public static string LibraryGridViewDriver_AddToLibrary_Recalibrate_iRT_Standard_Peptides {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddToLibrary_Recalibrate_iRT_Standard_Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Recalibrating iRT standard peptides and reprocessing iRT values.
/// </summary>
public static string LibraryGridViewDriver_AddToLibrary_Recalibrating_iRT_standard_peptides_and_reprocessing_iRT_values {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddToLibrary_Recalibrating_iRT_standard_peptides_and_reproc" +
"essing_iRT_values", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This can improve retention time alignment under stable chromatographic conditions..
/// </summary>
public static string LibraryGridViewDriver_AddToLibrary_This_can_improve_retention_time_alignment_under_stable_chromatographic_conditions_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_AddToLibrary_This_can_improve_retention_time_alignment_unde" +
"r_stable_chromatographic_conditions_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is already an optimization with sequence '{0}' and product ion '{2}' in the list..
/// </summary>
public static string LibraryGridViewDriver_DoCellValidating_There_is_already_an_optimization_with_sequence___0___and_product_ion___2___in_the_list_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_DoCellValidating_There_is_already_an_optimization_with_sequ" +
"ence___0___and_product_ion___2___in_the_list_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide {0} is already present in the {1} table, and may not be pasted into the {2} table..
/// </summary>
public static string LibraryGridViewDriver_DoPaste_The_peptide__0__is_already_present_in_the__1__table__and_may_not_be_pasted_into_the__2__table {
get {
return ResourceManager.GetString("LibraryGridViewDriver_DoPaste_The_peptide__0__is_already_present_in_the__1__table" +
"__and_may_not_be_pasted_into_the__2__table", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding retention times.
/// </summary>
public static string LibraryGridViewDriver_ProcessRetentionTimes_Adding_retention_times {
get {
return ResourceManager.GetString("LibraryGridViewDriver_ProcessRetentionTimes_Adding_retention_times", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Converting retention times from {0}.
/// </summary>
public static string LibraryGridViewDriver_ProcessRetentionTimes_Converting_retention_times_from__0__ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_ProcessRetentionTimes_Converting_retention_times_from__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product m/zs must be greater than zero..
/// </summary>
public static string LibraryGridViewDriver_ValidateMz_Product_m_zs_must_be_greater_than_zero_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_ValidateMz_Product_m_zs_must_be_greater_than_zero_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing product ion on line {1}..
/// </summary>
public static string LibraryGridViewDriver_ValidateOptimizationRow_Missing_product_ion_on_line__1_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_ValidateOptimizationRow_Missing_product_ion_on_line__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The pasted text must contain the same number of columns as the table..
/// </summary>
public static string LibraryGridViewDriver_ValidateOptimizationRow_The_pasted_text_must_contain_the_same_number_of_columns_as_the_table_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_ValidateOptimizationRow_The_pasted_text_must_contain_the_sa" +
"me_number_of_columns_as_the_table_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Optimized values must be greater than zero..
/// </summary>
public static string LibraryGridViewDriver_ValidateOptimizedValue_Optimized_values_must_be_greater_than_zero_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_ValidateOptimizedValue_Optimized_values_must_be_greater_tha" +
"n_zero_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Optimized values must be valid decimal numbers..
/// </summary>
public static string LibraryGridViewDriver_ValidateOptimizedValue_Optimized_values_must_be_valid_decimal_numbers_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_ValidateOptimizedValue_Optimized_values_must_be_valid_decim" +
"al_numbers_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product ion {0} is invalid..
/// </summary>
public static string LibraryGridViewDriver_ValidateProductIon_Product_ion__0__is_invalid_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_ValidateProductIon_Product_ion__0__is_invalid_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product ion cannot be empty..
/// </summary>
public static string LibraryGridViewDriver_ValidateProductIon_Product_ion_cannot_be_empty_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_ValidateProductIon_Product_ion_cannot_be_empty_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid product ion format {0} on line {1}..
/// </summary>
public static string LibraryGridViewDriver_ValidateRow_Invalid_product_ion_format__0__on_line__1__ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_ValidateRow_Invalid_product_ion_format__0__on_line__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sequence cannot be empty..
/// </summary>
public static string LibraryGridViewDriver_ValidateSequence_Sequence_cannot_be_empty_ {
get {
return ResourceManager.GetString("LibraryGridViewDriver_ValidateSequence_Sequence_cannot_be_empty_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Updating library settings for {0}.
/// </summary>
public static string LibraryManager_LoadBackground_Updating_library_settings_for__0_ {
get {
return ResourceManager.GetString("LibraryManager_LoadBackground_Updating_library_settings_for__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add spectral library.
/// </summary>
public static string LibrarySpec_Add_spectral_library {
get {
return ResourceManager.GetString("LibrarySpec_Add_spectral_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unrecognized library type at {0}.
/// </summary>
public static string LibrarySpec_CreateFromPath_Unrecognized_library_type_at__0_ {
get {
return ResourceManager.GetString("LibrarySpec_CreateFromPath_Unrecognized_library_type_at__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Spectrum count.
/// </summary>
public static string LibrarySpec_PEP_RANK_COPIES_Spectrum_count {
get {
return ResourceManager.GetString("LibrarySpec_PEP_RANK_COPIES_Spectrum_count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Picked intensity.
/// </summary>
public static string LibrarySpec_PEP_RANK_PICKED_INTENSITY_Picked_intensity {
get {
return ResourceManager.GetString("LibrarySpec_PEP_RANK_PICKED_INTENSITY_Picked_intensity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Total intensity.
/// </summary>
public static string LibrarySpec_PEP_RANK_TOTAL_INTENSITY_Total_intensity {
get {
return ResourceManager.GetString("LibrarySpec_PEP_RANK_TOTAL_INTENSITY_Total_intensity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document library specs cannot be persisted to XML..
/// </summary>
public static string LibrarySpec_WriteXml_Document_library_specs_cannot_be_persisted_to_XML_ {
get {
return ResourceManager.GetString("LibrarySpec_WriteXml_Document_library_specs_cannot_be_persisted_to_XML_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document local library specs cannot be persisted to XML..
/// </summary>
public static string LibrarySpec_WriteXml_Document_local_library_specs_cannot_be_persisted_to_XML {
get {
return ResourceManager.GetString("LibrarySpec_WriteXml_Document_local_library_specs_cannot_be_persisted_to_XML", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to do a regression in log space because one or more points are non-positive..
/// </summary>
public static string LinearInLogSpace_FitPoints_Unable_to_do_a_regression_in_log_space_because_one_or_more_points_are_non_positive_ {
get {
return ResourceManager.GetString("LinearInLogSpace_FitPoints_Unable_to_do_a_regression_in_log_space_because_one_or_" +
"more_points_are_non_positive_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Linear in Log Space.
/// </summary>
public static string LinearInLogSpace_Label_Linear_in_Log_Space {
get {
return ResourceManager.GetString("LinearInLogSpace_Label_Linear_in_Log_Space", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Every calculator in the model either has an unknown value, or takes on only one value..
/// </summary>
public static string LinearModelParams_RescaleParameters_Every_calculator_in_the_model_either_has_an_unknown_value__or_takes_on_only_one_value_ {
get {
return ResourceManager.GetString("LinearModelParams_RescaleParameters_Every_calculator_in_the_model_either_has_an_u" +
"nknown_value__or_takes_on_only_one_value_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempted to score a peak with {0} features using a model with {1} trained scores..
/// </summary>
public static string LinearModelParams_Score_Attempted_to_score_a_peak_with__0__features_using_a_model_with__1__trained_scores_ {
get {
return ResourceManager.GetString("LinearModelParams_Score_Attempted_to_score_a_peak_with__0__features_using_a_model" +
"_with__1__trained_scores_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}, line {1}..
/// </summary>
public static string LineColNumberedIoException_FormatMessage__0___line__1__ {
get {
return ResourceManager.GetString("LineColNumberedIoException_FormatMessage__0___line__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}, line {1}, col {2}..
/// </summary>
public static string LineColNumberedIoException_FormatMessage__0___line__1___col__2__ {
get {
return ResourceManager.GetString("LineColNumberedIoException_FormatMessage__0___line__1___col__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to (fixed).
/// </summary>
public static string ListBoxModification_ToString__fixed_ {
get {
return ResourceManager.GetString("ListBoxModification_ToString__fixed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to (isotopic label).
/// </summary>
public static string ListBoxModification_ToString__isotopic_label_ {
get {
return ResourceManager.GetString("ListBoxModification_ToString__isotopic_label_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to (variable).
/// </summary>
public static string ListBoxModification_ToString__variable_ {
get {
return ResourceManager.GetString("ListBoxModification_ToString__variable_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No such list {0}.
/// </summary>
public static string ListColumnPropertyDescriptor_ChangeListData_No_such_list__0_ {
get {
return ResourceManager.GetString("ListColumnPropertyDescriptor_ChangeListData_No_such_list__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to List has been deleted.
/// </summary>
public static string ListColumnPropertyDescriptor_SetValue_List_has_been_deleted {
get {
return ResourceManager.GetString("ListColumnPropertyDescriptor_SetValue_List_has_been_deleted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to List item has been deleted..
/// </summary>
public static string ListColumnPropertyDescriptor_SetValue_List_item_has_been_deleted_ {
get {
return ResourceManager.GetString("ListColumnPropertyDescriptor_SetValue_List_item_has_been_deleted_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Lists.
/// </summary>
public static string ListDefList_Label_Lists {
get {
return ResourceManager.GetString("ListDefList_Label_Lists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Define Lists.
/// </summary>
public static string ListDefList_Title_Define_Lists {
get {
return ResourceManager.GetString("ListDefList_Title_Define_Lists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Duplicate property name.
/// </summary>
public static string ListDesigner_OkDialog_Duplicate_property_name {
get {
return ResourceManager.GetString("ListDesigner_OkDialog_Duplicate_property_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No such property.
/// </summary>
public static string ListDesigner_OkDialog_No_such_property {
get {
return ResourceManager.GetString("ListDesigner_OkDialog_No_such_property", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is already a list named '{0}'..
/// </summary>
public static string ListDesigner_OkDialog_There_is_already_a_list_named___0___ {
get {
return ResourceManager.GetString("ListDesigner_OkDialog_There_is_already_a_list_named___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There was an error trying to apply this list definition to the original data:.
/// </summary>
public static string ListDesigner_OkDialog_There_was_an_error_trying_to_apply_this_list_definition_to_the_original_data_ {
get {
return ResourceManager.GetString("ListDesigner_OkDialog_There_was_an_error_trying_to_apply_this_list_definition_to_" +
"the_original_data_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Column '{0}' does not exist..
/// </summary>
public static string ListExceptionDetail_ColumnNotFound_Column___0___does_not_exist_ {
get {
return ResourceManager.GetString("ListExceptionDetail_ColumnNotFound_Column___0___does_not_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Duplicate value '{1}' found in column '{0}'..
/// </summary>
public static string ListExceptionDetail_DuplicateValue_Duplicate_value___1___found_in_column___0___ {
get {
return ResourceManager.GetString("ListExceptionDetail_DuplicateValue_Duplicate_value___1___found_in_column___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid value '{1}' for column '{0}'..
/// </summary>
public static string ListExceptionDetail_InvalidValue_Invalid_value___1___for_column___0___ {
get {
return ResourceManager.GetString("ListExceptionDetail_InvalidValue_Invalid_value___1___for_column___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Column '{0}' cannot be blank..
/// </summary>
public static string ListExceptionDetail_NullValue_Column___0___cannot_be_blank_ {
get {
return ResourceManager.GetString("ListExceptionDetail_NullValue_Column___0___cannot_be_blank_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to List: .
/// </summary>
public static string ListGridForm_BindingListSourceOnListChanged_List__ {
get {
return ResourceManager.GetString("ListGridForm_BindingListSourceOnListChanged_List__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Number.
/// </summary>
public static string ListPropertyType_GetAnnotationTypeName_Number {
get {
return ResourceManager.GetString("ListPropertyType_GetAnnotationTypeName_Number", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Text.
/// </summary>
public static string ListPropertyType_GetAnnotationTypeName_Text {
get {
return ResourceManager.GetString("ListPropertyType_GetAnnotationTypeName_Text", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to True/False.
/// </summary>
public static string ListPropertyType_GetAnnotationTypeName_True_False {
get {
return ResourceManager.GetString("ListPropertyType_GetAnnotationTypeName_True_False", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Value List.
/// </summary>
public static string ListPropertyType_GetAnnotationTypeName_Value_List {
get {
return ResourceManager.GetString("ListPropertyType_GetAnnotationTypeName_Value_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Lookup: .
/// </summary>
public static string ListPropertyType_Label_Lookup__ {
get {
return ResourceManager.GetString("ListPropertyType_Label_Lookup__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add new item to list '{0}'.
/// </summary>
public static string ListViewContext_CommitAddNew_Add_new_item_to_list___0__ {
get {
return ResourceManager.GetString("ListViewContext_CommitAddNew_Add_new_item_to_list___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete the {0} selected items from the list '{1}'?.
/// </summary>
public static string ListViewContext_Delete_Are_you_sure_you_want_to_delete_the__0__selected_items_from_the_list___1___ {
get {
return ResourceManager.GetString("ListViewContext_Delete_Are_you_sure_you_want_to_delete_the__0__selected_items_fro" +
"m_the_list___1___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Delete from list '{0}'.
/// </summary>
public static string ListViewContext_Delete_Delete_from_list___0__ {
get {
return ResourceManager.GetString("ListViewContext_Delete_Delete_from_list___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Press OK to continue editing your row, or Cancel to throw away the new row..
/// </summary>
public static string ListViewContext_ValidateNewRow_Press_OK_to_continue_editing_your_row__or_Cancel_to_throw_away_the_new_row_ {
get {
return ResourceManager.GetString("ListViewContext_ValidateNewRow_Press_OK_to_continue_editing_your_row__or_Cancel_t" +
"o_throw_away_the_new_row_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The new row could not be added because of the following error:.
/// </summary>
public static string ListViewContext_ValidateNewRow_The_new_row_could_not_be_added_because_of_the_following_error_ {
get {
return ResourceManager.GetString("ListViewContext_ValidateNewRow_The_new_row_could_not_be_added_because_of_the_foll" +
"owing_error_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data import canceled.
/// </summary>
public static string LoadCanceledException_LoadCanceledException_Data_import_canceled {
get {
return ResourceManager.GetString("LoadCanceledException_LoadCanceledException_Data_import_canceled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed importing results into '{0}'..
/// </summary>
public static string Loader_Fail_Failed_importing_results_into___0___ {
get {
return ResourceManager.GetString("Loader_Fail_Failed_importing_results_into___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Updating peak statistics.
/// </summary>
public static string Loader_FinishLoad_Updating_peak_statistics {
get {
return ResourceManager.GetString("Loader_FinishLoad_Updating_peak_statistics", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure attempting to load the data cache file {0}.
/// </summary>
public static string Loader_Load_Failure_attempting_to_load_the_data_cache_file__0_ {
get {
return ResourceManager.GetString("Loader_Load_Failure_attempting_to_load_the_data_cache_file__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure reading the data file {0}..
/// </summary>
public static string Loader_Load_Failure_reading_the_data_file__0__ {
get {
return ResourceManager.GetString("Loader_Load_Failure_reading_the_data_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading results for {0}.
/// </summary>
public static string Loader_Load_Loading_results_for__0__ {
get {
return ResourceManager.GetString("Loader_Load_Loading_results_for__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data import expected to consume {0} minutes with maximum of {1} minutes.
/// </summary>
public static string LoadingTooSlowlyException_LoadingTooSlowlyException_Data_import_expected_to_consume__0__minutes_with_maximum_of__1__mintues {
get {
return ResourceManager.GetString("LoadingTooSlowlyException_LoadingTooSlowlyException_Data_import_expected_to_consu" +
"me__0__minutes_with_maximum_of__1__mintues", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Below is the saved value for the path to the executable..
/// </summary>
public static string LocateFileDlg_LocateFileDlg_Below_is_the_saved_value_for_the_path_to_the_executable {
get {
return ResourceManager.GetString("LocateFileDlg_LocateFileDlg_Below_is_the_saved_value_for_the_path_to_the_executab" +
"le", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to If you have it installed please provide the path below..
/// </summary>
public static string LocateFileDlg_LocateFileDlg_If_you_have_it_installed_please_provide_the_path_below {
get {
return ResourceManager.GetString("LocateFileDlg_LocateFileDlg_If_you_have_it_installed_please_provide_the_path_belo" +
"w", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Otherwise, please cancel and install {0} first.
/// </summary>
public static string LocateFileDlg_LocateFileDlg_Otherwise__please_cancel_and_install__0__first {
get {
return ResourceManager.GetString("LocateFileDlg_LocateFileDlg_Otherwise__please_cancel_and_install__0__first", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Otherwise, please cancel and install {0} version {1} first.
/// </summary>
public static string LocateFileDlg_LocateFileDlg_Otherwise__please_cancel_and_install__0__version__1__first {
get {
return ResourceManager.GetString("LocateFileDlg_LocateFileDlg_Otherwise__please_cancel_and_install__0__version__1__" +
"first", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please verify and update if incorrect..
/// </summary>
public static string LocateFileDlg_LocateFileDlg_Please_verify_and_update_if_incorrect {
get {
return ResourceManager.GetString("LocateFileDlg_LocateFileDlg_Please_verify_and_update_if_incorrect", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to then run the tool again..
/// </summary>
public static string LocateFileDlg_LocateFileDlg_then_run_the_tool_again {
get {
return ResourceManager.GetString("LocateFileDlg_LocateFileDlg_then_run_the_tool_again", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires {0}..
/// </summary>
public static string LocateFileDlg_LocateFileDlg_This_tool_requires_0 {
get {
return ResourceManager.GetString("LocateFileDlg_LocateFileDlg_This_tool_requires_0", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires {0} version {1}..
/// </summary>
public static string LocateFileDlg_LocateFileDlg_This_tool_requires_0_version_1 {
get {
return ResourceManager.GetString("LocateFileDlg_LocateFileDlg_This_tool_requires_0_version_1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You have not provided a valid path..
/// </summary>
public static string LocateFileDlg_PathPasses_You_have_not_provided_a_valid_path_ {
get {
return ResourceManager.GetString("LocateFileDlg_PathPasses_You_have_not_provided_a_valid_path_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to canceled.
/// </summary>
public static string LongWaitDlg_PerformWork_canceled {
get {
return ResourceManager.GetString("LongWaitDlg_PerformWork_canceled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Always.
/// </summary>
public static string LossInclusionExtension_LOCALIZED_VALUES_Always {
get {
return ResourceManager.GetString("LossInclusionExtension_LOCALIZED_VALUES_Always", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Matching Library.
/// </summary>
public static string LossInclusionExtension_LOCALIZED_VALUES_Matching_Library {
get {
return ResourceManager.GetString("LossInclusionExtension_LOCALIZED_VALUES_Matching_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Never.
/// </summary>
public static string LossInclusionExtension_LOCALIZED_VALUES_Never {
get {
return ResourceManager.GetString("LossInclusionExtension_LOCALIZED_VALUES_Never", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to LOWESS Aligner.
/// </summary>
public static string LowessAlignerFactory_ToString_LOWESS_Aligner {
get {
return ResourceManager.GetString("LowessAlignerFactory_ToString_LOWESS_Aligner", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap magnifier_zoom_in {
get {
object obj = ResourceManager.GetObject("magnifier_zoom_in", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to All results must be completely imported before any can be re-imported..
/// </summary>
public static string ManageResultsDlg_ReimportResults_All_results_must_be_completely_imported_before_any_can_be_re_imported {
get {
return ResourceManager.GetString("ManageResultsDlg_ReimportResults_All_results_must_be_completely_imported_before_a" +
"ny_can_be_re_imported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find the following files, either in their original locations or in the folder of the current document:.
/// </summary>
public static string ManageResultsDlg_ReimportResults_Unable_to_find_the_following_files_either_in_their_original_locations_or_in_the_folder_of_the_current_document {
get {
return ResourceManager.GetString("ManageResultsDlg_ReimportResults_Unable_to_find_the_following_files_either_in_the" +
"ir_original_locations_or_in_the_folder_of_the_current_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Manually integrated peaks.
/// </summary>
public static string ManuallyIntegratedPeakFinder_DisplayName_Manually_integrated_peaks {
get {
return ResourceManager.GetString("ManuallyIntegratedPeakFinder_DisplayName_Manually_integrated_peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Manually integrated peak.
/// </summary>
public static string ManuallyIntegratedPeakFinder_MatchTransition_Manually_integrated_peak {
get {
return ResourceManager.GetString("ManuallyIntegratedPeakFinder_MatchTransition_Manually_integrated_peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to m/z.
/// </summary>
public static string MassErrorHistogram2DGraphPane_Graph_Mz {
get {
return ResourceManager.GetString("MassErrorHistogram2DGraphPane_Graph_Mz", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention Time.
/// </summary>
public static string MassErrorHistogram2DGraphPane_Graph_Retention_Time {
get {
return ResourceManager.GetString("MassErrorHistogram2DGraphPane_Graph_Retention_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mass Errors Unavailable.
/// </summary>
public static string MassErrorHistogramGraphPane_AddLabels_Mass_Errors_Unavailable {
get {
return ResourceManager.GetString("MassErrorHistogramGraphPane_AddLabels_Mass_Errors_Unavailable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mean.
/// </summary>
public static string MassErrorHistogramGraphPane_AddLabels_mean {
get {
return ResourceManager.GetString("MassErrorHistogramGraphPane_AddLabels_mean", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Standard Deviation.
/// </summary>
public static string MassErrorHistogramGraphPane_AddLabels_standard_deviation {
get {
return ResourceManager.GetString("MassErrorHistogramGraphPane_AddLabels_standard_deviation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Count.
/// </summary>
public static string MassErrorHistogramGraphPane_UpdateGraph_Count {
get {
return ResourceManager.GetString("MassErrorHistogramGraphPane_UpdateGraph_Count", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mass Error (ppm).
/// </summary>
public static string MassErrorReplicateGraphPane_UpdateGraph_Mass_Error {
get {
return ResourceManager.GetString("MassErrorReplicateGraphPane_UpdateGraph_Mass_Error", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mass Error.
/// </summary>
public static string MassErrorReplicateGraphPane_UpdateGraph_Mass_Error_No_Ppm {
get {
return ResourceManager.GetString("MassErrorReplicateGraphPane_UpdateGraph_Mass_Error_No_Ppm", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Select a peptide to see the mass error graph.
/// </summary>
public static string MassErrorReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_mass_error_graph {
get {
return ResourceManager.GetString("MassErrorReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_mass_error_gr" +
"aph", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid iRT value at precusor m/z {0} for peptide {1}..
/// </summary>
public static string MassListImporter_AddRow_Invalid_iRT_value_at_precusor_m_z__0__for_peptide__1_ {
get {
return ResourceManager.GetString("MassListImporter_AddRow_Invalid_iRT_value_at_precusor_m_z__0__for_peptide__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid library intensity at precursor {0} for peptide {1}..
/// </summary>
public static string MassListImporter_AddRow_Invalid_library_intensity_at_precursor__0__for_peptide__1_ {
get {
return ResourceManager.GetString("MassListImporter_AddRow_Invalid_library_intensity_at_precursor__0__for_peptide__1" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Empty transition list..
/// </summary>
public static string MassListImporter_Import_Empty_transition_list {
get {
return ResourceManager.GetString("MassListImporter_Import_Empty_transition_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to find peptide column..
/// </summary>
public static string MassListImporter_Import_Failed_to_find_peptide_column {
get {
return ResourceManager.GetString("MassListImporter_Import_Failed_to_find_peptide_column", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Importing {0}.
/// </summary>
public static string MassListImporter_Import_Importing__0__ {
get {
return ResourceManager.GetString("MassListImporter_Import_Importing__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Inspecting peptide sequence information.
/// </summary>
public static string MassListImporter_Import_Inspecting_peptide_sequence_information {
get {
return ResourceManager.GetString("MassListImporter_Import_Inspecting_peptide_sequence_information", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid transition list. Transition lists must contain at least precursor m/z, product m/z, and peptide sequence..
/// </summary>
public static string MassListImporter_Import_Invalid_transition_list_Transition_lists_must_contain_at_least_precursor_m_z_product_m_z_and_peptide_sequence {
get {
return ResourceManager.GetString("MassListImporter_Import_Invalid_transition_list_Transition_lists_must_contain_at_" +
"least_precursor_m_z_product_m_z_and_peptide_sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reading transition list.
/// </summary>
public static string MassListImporter_Import_Reading_transition_list {
get {
return ResourceManager.GetString("MassListImporter_Import_Reading_transition_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor m/z {0} does not match the closest possible value {1} (delta = {2}), peptide {3}..
/// </summary>
public static string MassListRowReader_CalcPrecursorExplanations_ {
get {
return ResourceManager.GetString("MassListRowReader_CalcPrecursorExplanations_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check the Instrument tab in the Transition Settings..
/// </summary>
public static string MassListRowReader_CalcPrecursorExplanations_Check_the_Instrument_tab_in_the_Transition_Settings {
get {
return ResourceManager.GetString("MassListRowReader_CalcPrecursorExplanations_Check_the_Instrument_tab_in_the_Trans" +
"ition_Settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check the isolation scheme in the full scan tab of the transition settings..
/// </summary>
public static string MassListRowReader_CalcPrecursorExplanations_Check_the_isolation_scheme_in_the_full_scan_settings_ {
get {
return ResourceManager.GetString("MassListRowReader_CalcPrecursorExplanations_Check_the_isolation_scheme_in_the_ful" +
"l_scan_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor m/z {0} of the peptide {1} is out of range for the instrument settings..
/// </summary>
public static string MassListRowReader_CalcPrecursorExplanations_The_precursor_m_z__0__of_the_peptide__1__is_out_of_range_for_the_instrument_settings_ {
get {
return ResourceManager.GetString("MassListRowReader_CalcPrecursorExplanations_The_precursor_m_z__0__of_the_peptide_" +
"_1__is_out_of_range_for_the_instrument_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor m/z {0} of the peptide {1} is outside the range covered by the DIA isolation scheme..
/// </summary>
public static string MassListRowReader_CalcPrecursorExplanations_The_precursor_m_z__0__of_the_peptide__1__is_outside_the_range_covered_by_the_DIA_isolation_scheme_ {
get {
return ResourceManager.GetString("MassListRowReader_CalcPrecursorExplanations_The_precursor_m_z__0__of_the_peptide_" +
"_1__is_outside_the_range_covered_by_the_DIA_isolation_scheme_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product m/z value {0} in peptide {1} has no matching product ion..
/// </summary>
public static string MassListRowReader_CalcTransitionExplanations_Product_m_z_value__0__in_peptide__1__has_no_matching_product_ion {
get {
return ResourceManager.GetString("MassListRowReader_CalcTransitionExplanations_Product_m_z_value__0__in_peptide__1_" +
"_has_no_matching_product_ion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The product m/z {0} is out of range for the instrument settings, in the peptide sequence {1}..
/// </summary>
public static string MassListRowReader_CalcTransitionExplanations_The_product_m_z__0__is_out_of_range_for_the_instrument_settings__in_the_peptide_sequence__1_ {
get {
return ResourceManager.GetString("MassListRowReader_CalcTransitionExplanations_The_product_m_z__0__is_out_of_range_" +
"for_the_instrument_settings__in_the_peptide_sequence__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check the Modifications tab in Transition Settings..
/// </summary>
public static string MassListRowReader_NextRow_Check_the_Modifications_tab_in_Transition_Settings {
get {
return ResourceManager.GetString("MassListRowReader_NextRow_Check_the_Modifications_tab_in_Transition_Settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid peptide sequence {0} found.
/// </summary>
public static string MassListRowReader_NextRow_Invalid_peptide_sequence__0__found {
get {
return ResourceManager.GetString("MassListRowReader_NextRow_Invalid_peptide_sequence__0__found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isotope labeled entry found without matching settings..
/// </summary>
public static string MassListRowReader_NextRow_Isotope_labeled_entry_found_without_matching_settings_ {
get {
return ResourceManager.GetString("MassListRowReader_NextRow_Isotope_labeled_entry_found_without_matching_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No peptide modified sequence column specified.
/// </summary>
public static string MassListRowReader_NextRow_No_peptide_sequence_column_specified {
get {
return ResourceManager.GetString("MassListRowReader_NextRow_No_peptide_sequence_column_specified", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add checked modifications.
/// </summary>
public static string MatchModificationsControl_AddCheckedModifications_Add_checked_modifications {
get {
return ResourceManager.GetString("MatchModificationsControl_AddCheckedModifications_Add_checked_modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add {0} modification {1}.
/// </summary>
public static string MatchModificationsControl_AddModification_Add__0__modification__1_ {
get {
return ResourceManager.GetString("MatchModificationsControl_AddModification_Add__0__modification__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Edit modifications.
/// </summary>
public static string MatchModificationsControl_Initialize__Edit_modifications {
get {
return ResourceManager.GetString("MatchModificationsControl_Initialize__Edit_modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit &heavy modifications....
/// </summary>
public static string MatchModificationsControl_Initialize_Edit__heavy_modifications___ {
get {
return ResourceManager.GetString("MatchModificationsControl_Initialize_Edit__heavy_modifications___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit &structural modifications....
/// </summary>
public static string MatchModificationsControl_Initialize_Edit__structural_modifications___ {
get {
return ResourceManager.GetString("MatchModificationsControl_Initialize_Edit__structural_modifications___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Specify all modifications you want to include in the search:.
/// </summary>
public static string MatchModificationsControl_ModificationLabelText_DDA_Search {
get {
return ResourceManager.GetString("MatchModificationsControl_ModificationLabelText_DDA_Search", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Charge state values must be greater than 0..
/// </summary>
public static string MeasuredCollisionalCrossSection_Validate_Charge_state_values_must_be_greater_than_0_ {
get {
return ResourceManager.GetString("MeasuredCollisionalCrossSection_Validate_Charge_state_values_must_be_greater_than" +
"_0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collisional cross section values must be greater than 0..
/// </summary>
public static string MeasuredCollisionalCrossSection_Validate_Collisional_cross_section_values_must_be_greater_than_0_ {
get {
return ResourceManager.GetString("MeasuredCollisionalCrossSection_Validate_Collisional_cross_section_values_must_be" +
"_greater_than_0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to On line {0} {1}.
/// </summary>
public static string MeasuredDriftTimeTable_ValidateMeasuredDriftTimeCellValues_On_line__0___1_ {
get {
return ResourceManager.GetString("MeasuredDriftTimeTable_ValidateMeasuredDriftTimeCellValues_On_line__0___1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Multiple charge states for custom ions are no longer supported..
/// </summary>
public static string MeasuredIon_ReadXml_Multiple_charge_states_for_custom_ions_are_no_longer_supported_ {
get {
return ResourceManager.GetString("MeasuredIon_ReadXml_Multiple_charge_states_for_custom_ions_are_no_longer_supporte" +
"d_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reporter ion masses must be greater than or equal to {0}..
/// </summary>
public static string MeasuredIon_Validate_Reporter_ion_masses_must_be_greater_than_or_equal_to__0__ {
get {
return ResourceManager.GetString("MeasuredIon_Validate_Reporter_ion_masses_must_be_greater_than_or_equal_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reporter ion masses must be less than or equal to {0}..
/// </summary>
public static string MeasuredIon_Validate_Reporter_ion_masses_must_be_less_than_or_equal_to__0__ {
get {
return ResourceManager.GetString("MeasuredIon_Validate_Reporter_ion_masses_must_be_less_than_or_equal_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reporter ions must specify a formula or valid monoisotopic and average masses..
/// </summary>
public static string MeasuredIon_Validate_Reporter_ions_must_specify_a_formula_or_valid_monoisotopic_and_average_masses {
get {
return ResourceManager.GetString("MeasuredIon_Validate_Reporter_ions_must_specify_a_formula_or_valid_monoisotopic_a" +
"nd_average_masses", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Special fragment ions must have at least one fragmentation residue..
/// </summary>
public static string MeasuredIon_Validate_Special_fragment_ions_must_have_at_least_one_fragmentation_residue {
get {
return ResourceManager.GetString("MeasuredIon_Validate_Special_fragment_ions_must_have_at_least_one_fragmentation_r" +
"esidue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Special fragment ions must specify the terminal side of the amino acid residue on which fragmentation occurs..
/// </summary>
public static string MeasuredIon_Validate_Special_fragment_ions_must_specify_the_terminal_side_of_the_amino_acid_residue_on_which_fragmentation_occurs {
get {
return ResourceManager.GetString("MeasuredIon_Validate_Special_fragment_ions_must_specify_the_terminal_side_of_the_" +
"amino_acid_residue_on_which_fragmentation_occurs", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The minimum length {0} must be between {1} and {2}..
/// </summary>
public static string MeasuredIon_Validate_The_minimum_length__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("MeasuredIon_Validate_The_minimum_length__0__must_be_between__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Special ion:.
/// </summary>
public static string MeasuredIonList_Label_Special_ion {
get {
return ResourceManager.GetString("MeasuredIonList_Label_Special_ion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Special Ions.
/// </summary>
public static string MeasuredIonList_Title_Edit_Special_Ions {
get {
return ResourceManager.GetString("MeasuredIonList_Title_Edit_Special_Ions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measured retention times must be greater than zero..
/// </summary>
public static string MeasuredPeptide_ValidateRetentionTime_Measured_retention_times_must_be_greater_than_zero {
get {
return ResourceManager.GetString("MeasuredPeptide_ValidateRetentionTime_Measured_retention_times_must_be_greater_th" +
"an_zero", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measured retention times must be valid decimal numbers..
/// </summary>
public static string MeasuredPeptide_ValidateRetentionTime_Measured_retention_times_must_be_valid_decimal_numbers {
get {
return ResourceManager.GetString("MeasuredPeptide_ValidateRetentionTime_Measured_retention_times_must_be_valid_deci" +
"mal_numbers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A modified peptide sequence is required for each entry..
/// </summary>
public static string MeasuredPeptide_ValidateSequence_A_modified_peptide_sequence_is_required_for_each_entry {
get {
return ResourceManager.GetString("MeasuredPeptide_ValidateSequence_A_modified_peptide_sequence_is_required_for_each" +
"_entry", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The sequence '{0}' is not a valid modified peptide sequence..
/// </summary>
public static string MeasuredPeptide_ValidateSequence_The_sequence__0__is_not_a_valid_modified_peptide_sequence {
get {
return ResourceManager.GetString("MeasuredPeptide_ValidateSequence_The_sequence__0__is_not_a_valid_modified_peptide" +
"_sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempting to recalculate peak integration without first completing raw data import..
/// </summary>
public static string MeasuredResults_ChangeRecalcStatus_Attempting_to_recalculate_peak_integration_without_first_completing_raw_data_import_ {
get {
return ResourceManager.GetString("MeasuredResults_ChangeRecalcStatus_Attempting_to_recalculate_peak_integration_wit" +
"hout_first_completing_raw_data_import_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The chromatogram cache must be loaded before it can be changed..
/// </summary>
public static string MeasuredResults_CommitCacheFile_The_chromatogram_cache_must_be_loaded_before_it_can_be_changed {
get {
return ResourceManager.GetString("MeasuredResults_CommitCacheFile_The_chromatogram_cache_must_be_loaded_before_it_c" +
"an_be_changed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The chromatogram cache must be loaded before it is optimized..
/// </summary>
public static string MeasuredResults_OptimizeCache_The_chromatogram_cache_must_be_loaded_before_it_is_optimized {
get {
return ResourceManager.GetString("MeasuredResults_OptimizeCache_The_chromatogram_cache_must_be_loaded_before_it_is_" +
"optimized", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measured retention times must be positive values..
/// </summary>
public static string MeasuredRetentionTime_Validate_Measured_retention_times_must_be_positive_values {
get {
return ResourceManager.GetString("MeasuredRetentionTime_Validate_Measured_retention_times_must_be_positive_values", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The sequence {0} is not a valid peptide..
/// </summary>
public static string MeasuredRetentionTime_Validate_The_sequence__0__is_not_a_valid_peptide {
get {
return ResourceManager.GetString("MeasuredRetentionTime_Validate_The_sequence__0__is_not_a_valid_peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Field.
/// </summary>
public static string MessageBoxHelper_GetControlMessage_Field {
get {
return ResourceManager.GetString("MessageBoxHelper_GetControlMessage_Field", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must contain a comma separated list of adducts or integers describing charge states with absolute value from {1} to {2}..
/// </summary>
public static string MessageBoxHelper_ValidateAdductListTextBox__0__must_contain_a_comma_separated_list_of_adducts_or_integers_describing_charge_states_with_absolute_value_from__1__to__2__ {
get {
return ResourceManager.GetString("MessageBoxHelper_ValidateAdductListTextBox__0__must_contain_a_comma_separated_lis" +
"t_of_adducts_or_integers_describing_charge_states_with_absolute_value_from__1__t" +
"o__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must contain a comma separated list of adducts or integers describing charge states with absolute values from {1} to {2}..
/// </summary>
public static string MessageBoxHelper_ValidateAdductListTextBox__0__must_contain_a_comma_separated_list_of_adducts_or_integers_describing_charge_states_with_absolute_values_from__1__to__2__ {
get {
return ResourceManager.GetString("MessageBoxHelper_ValidateAdductListTextBox__0__must_contain_a_comma_separated_lis" +
"t_of_adducts_or_integers_describing_charge_states_with_absolute_values_from__1__" +
"to__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must contain a comma separated list of decimal values from {1} to {2}..
/// </summary>
public static string MessageBoxHelper_ValidateDecimalListTextBox__0__must_contain_a_comma_separated_list_of_decimal_values_from__1__to__2__ {
get {
return ResourceManager.GetString("MessageBoxHelper_ValidateDecimalListTextBox__0__must_contain_a_comma_separated_li" +
"st_of_decimal_values_from__1__to__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must be greater than {1}..
/// </summary>
public static string MessageBoxHelper_ValidateDecimalTextBox__0__must_be_greater_than__1__ {
get {
return ResourceManager.GetString("MessageBoxHelper_ValidateDecimalTextBox__0__must_be_greater_than__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must be greater than or equal to {1}..
/// </summary>
public static string MessageBoxHelper_ValidateDecimalTextBox__0__must_be_greater_than_or_equal_to__1__ {
get {
return ResourceManager.GetString("MessageBoxHelper_ValidateDecimalTextBox__0__must_be_greater_than_or_equal_to__1__" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must be less than {1}..
/// </summary>
public static string MessageBoxHelper_ValidateDecimalTextBox__0__must_be_less_than__1__ {
get {
return ResourceManager.GetString("MessageBoxHelper_ValidateDecimalTextBox__0__must_be_less_than__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must be less than or equal to {1}..
/// </summary>
public static string MessageBoxHelper_ValidateDecimalTextBox__0__must_be_less_than_or_equal_to__1__ {
get {
return ResourceManager.GetString("MessageBoxHelper_ValidateDecimalTextBox__0__must_be_less_than_or_equal_to__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must contain a decimal value..
/// </summary>
public static string MessageBoxHelper_ValidateDecimalTextBox__0__must_contain_a_decimal_value {
get {
return ResourceManager.GetString("MessageBoxHelper_ValidateDecimalTextBox__0__must_contain_a_decimal_value", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} cannot be empty..
/// </summary>
public static string MessageBoxHelper_ValidateNameTextBox__0__cannot_be_empty {
get {
return ResourceManager.GetString("MessageBoxHelper_ValidateNameTextBox__0__cannot_be_empty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must contain a comma separated list of integers from {1} to {2}..
/// </summary>
public static string MessageBoxHelper_ValidateNumberListTextBox__0__must_contain_a_comma_separated_list_of_integers_from__1__to__2__ {
get {
return ResourceManager.GetString("MessageBoxHelper_ValidateNumberListTextBox__0__must_contain_a_comma_separated_lis" +
"t_of_integers_from__1__to__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must contain an integer..
/// </summary>
public static string MessageBoxHelper_ValidateNumberTextBox__0__must_contain_an_integer {
get {
return ResourceManager.GetString("MessageBoxHelper_ValidateNumberTextBox__0__must_contain_an_integer", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Value {0} must be between {1} and {2} or {3} and {4}..
/// </summary>
public static string MessageBoxHelper_ValidateSignedNumberTextBox_Value__0__must_be_between__1__and__2__or__3__and__4__ {
get {
return ResourceManager.GetString("MessageBoxHelper_ValidateSignedNumberTextBox_Value__0__must_be_between__1__and__2" +
"__or__3__and__4__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error converting '{0}' to '{1}':.
/// </summary>
public static string MetadataExtractor_ApplyStep_Error_converting___0___to___1___ {
get {
return ResourceManager.GetString("MetadataExtractor_ApplyStep_Error_converting___0___to___1___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find column {0}.
/// </summary>
public static string MetadataExtractor_ResolveColumn_Unable_to_find_column__0_ {
get {
return ResourceManager.GetString("MetadataExtractor_ResolveColumn_Unable_to_find_column__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} cannot be blank.
/// </summary>
public static string MetadataRuleEditor_OkDialog__0__cannot_be_blank {
get {
return ResourceManager.GetString("MetadataRuleEditor_OkDialog__0__cannot_be_blank", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is already a result file rule set named '{0}'..
/// </summary>
public static string MetadataRuleEditor_OkDialog_There_is_already_a_metadata_rule_named___0___ {
get {
return ResourceManager.GetString("MetadataRuleEditor_OkDialog_There_is_already_a_metadata_rule_named___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This is not a valid regular expression..
/// </summary>
public static string MetadataRuleEditor_OkDialog_This_is_not_a_valid_regular_expression_ {
get {
return ResourceManager.GetString("MetadataRuleEditor_OkDialog_This_is_not_a_valid_regular_expression_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Rule Set.
/// </summary>
public static string MetadataRuleSetList_Label_Rule_Set {
get {
return ResourceManager.GetString("MetadataRuleSetList_Label_Rule_Set", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Rule Sets.
/// </summary>
public static string MetadataRuleSetList_Title_Rule_Sets {
get {
return ResourceManager.GetString("MetadataRuleSetList_Title_Rule_Sets", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The text '{0}' must either be a valid regular expression or blank.
/// </summary>
public static string MetadataRuleStepEditor_OkDialog__0__must_either_be_a_valid_regular_expression_or_blank {
get {
return ResourceManager.GetString("MetadataRuleStepEditor_OkDialog__0__must_either_be_a_valid_regular_expression_or_" +
"blank", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting method {0}....
/// </summary>
public static string MethodExporter_ExportMethod_Exporting_method__0__ {
get {
return ResourceManager.GetString("MethodExporter_ExportMethod_Exporting_method__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting methods....
/// </summary>
public static string MethodExporter_ExportMethod_Exporting_methods {
get {
return ResourceManager.GetString("MethodExporter_ExportMethod_Exporting_methods", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1/K0 lower limit.
/// </summary>
public static string Metrics_Col1K0LowerLimit__1_K0_lower_limit {
get {
return ResourceManager.GetString("Metrics_Col1K0LowerLimit__1_K0_lower_limit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1/K0 upper limit.
/// </summary>
public static string Metrics_Col1K0UpperLimit__1_K0_upper_limit {
get {
return ResourceManager.GetString("Metrics_Col1K0UpperLimit__1_K0_upper_limit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Max sampling time (seconds).
/// </summary>
public static string Metrics_ColMaxSamplingTime_Max_sampling_time__seconds_ {
get {
return ResourceManager.GetString("Metrics_ColMaxSamplingTime_Max_sampling_time__seconds_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mean sampling time (seconds).
/// </summary>
public static string Metrics_ColMeanSamplingTime_Mean_sampling_time__seconds_ {
get {
return ResourceManager.GetString("Metrics_ColMeanSamplingTime_Mean_sampling_time__seconds_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to m/z.
/// </summary>
public static string Metrics_ColMz_m_z {
get {
return ResourceManager.GetString("Metrics_ColMz_m_z", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to RT begin.
/// </summary>
public static string Metrics_ColRtBegin_RT_begin {
get {
return ResourceManager.GetString("Metrics_ColRtBegin_RT_begin", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to RT end.
/// </summary>
public static string Metrics_ColRtEnd_RT_end {
get {
return ResourceManager.GetString("Metrics_ColRtEnd_RT_end", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Target.
/// </summary>
public static string Metrics_ColTarget_Target {
get {
return ResourceManager.GetString("Metrics_ColTarget_Target", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding spectra to MIDAS library.
/// </summary>
public static string MidasLibrary_AddSpectra_Adding_spectra_to_MIDAS_library {
get {
return ResourceManager.GetString("MidasLibrary_AddSpectra_Adding_spectra_to_MIDAS_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error loading MIDAS library for adding spectra..
/// </summary>
public static string MidasLibrary_AddSpectra_Error_loading_MIDAS_library_for_adding_spectra_ {
get {
return ResourceManager.GetString("MidasLibrary_AddSpectra_Error_loading_MIDAS_library_for_adding_spectra_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reading MIDAS spectra.
/// </summary>
public static string MidasLibrary_AddSpectra_Reading_MIDAS_spectra {
get {
return ResourceManager.GetString("MidasLibrary_AddSpectra_Reading_MIDAS_spectra", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error reading LibInfo from MIDAS library.
/// </summary>
public static string MidasLibrary_Load_Error_reading_LibInfo_from_MIDAS_library {
get {
return ResourceManager.GetString("MidasLibrary_Load_Error_reading_LibInfo_from_MIDAS_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading MIDAS library.
/// </summary>
public static string MidasLibrary_Load_Loading_MIDAS_library {
get {
return ResourceManager.GetString("MidasLibrary_Load_Loading_MIDAS_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to MIDAS Spectral Library.
/// </summary>
public static string MidasLibrary_SpecFilter_MIDAS_Spectral_Library {
get {
return ResourceManager.GetString("MidasLibrary_SpecFilter_MIDAS_Spectral_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The cache file has not been loaded yet..
/// </summary>
public static string MinimizeResultsDlg_ChromCacheMinimizer_The_cache_file_has_not_been_loaded_yet {
get {
return ResourceManager.GetString("MinimizeResultsDlg_ChromCacheMinimizer_The_cache_file_has_not_been_loaded_yet", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All results must be completely imported before any can be minimized..
/// </summary>
public static string MinimizeResultsDlg_Minimize_All_results_must_be_completely_imported_before_any_can_be_minimized {
get {
return ResourceManager.GetString("MinimizeResultsDlg_Minimize_All_results_must_be_completely_imported_before_any_ca" +
"n_be_minimized", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You have not chosen any options to minimize your cache file. Are you sure you want to continue?.
/// </summary>
public static string MinimizeResultsDlg_Minimize_You_have_not_chosen_any_options_to_minimize_your_cache_file_Are_you_sure_you_want_to_continue {
get {
return ResourceManager.GetString("MinimizeResultsDlg_Minimize_You_have_not_chosen_any_options_to_minimize_your_cach" +
"e_file_Are_you_sure_you_want_to_continue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An unexpected error occurred while saving the data cache file {0}..
/// </summary>
public static string MinimizeResultsDlg_MinimizeToFile_An_unexpected_error_occurred_while_saving_the_data_cache_file__0__ {
get {
return ResourceManager.GetString("MinimizeResultsDlg_MinimizeToFile_An_unexpected_error_occurred_while_saving_the_d" +
"ata_cache_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Saving new cache file.
/// </summary>
public static string MinimizeResultsDlg_MinimizeToFile_Saving_new_cache_file {
get {
return ResourceManager.GetString("MinimizeResultsDlg_MinimizeToFile_Saving_new_cache_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The noise time limit must be a positive decimal number..
/// </summary>
public static string MinimizeResultsDlg_tbxNoiseTimeRange_Leave_The_noise_time_limit_must_be_a_positive_decimal_number {
get {
return ResourceManager.GetString("MinimizeResultsDlg_tbxNoiseTimeRange_Leave_The_noise_time_limit_must_be_a_positiv" +
"e_decimal_number", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The noise time limit must be a valid decimal number..
/// </summary>
public static string MinimizeResultsDlg_tbxNoiseTimeRange_Leave_The_noise_time_limit_must_be_a_valid_decimal_number {
get {
return ResourceManager.GetString("MinimizeResultsDlg_tbxNoiseTimeRange_Leave_The_noise_time_limit_must_be_a_valid_d" +
"ecimal_number", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mismatched transitions.
/// </summary>
public static string MismatchedIsotopeTransitionsFinder_DisplayName_Mismatched_transitions {
get {
return ResourceManager.GetString("MismatchedIsotopeTransitionsFinder_DisplayName_Mismatched_transitions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing all results.
/// </summary>
public static string MissingAllResultsFinder_DisplayName_Missing_all_results {
get {
return ResourceManager.GetString("MissingAllResultsFinder_DisplayName_Missing_all_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing any results.
/// </summary>
public static string MissingAnyResultsFinder_DisplayName_Missing_any_results {
get {
return ResourceManager.GetString("MissingAnyResultsFinder_DisplayName_Missing_any_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must choose a file with the '{0}' filename extension..
/// </summary>
public static string MissingFileDlg_ValidateFilePath_You_must_choose_a_file_with_the___0___filename_extension_ {
get {
return ResourceManager.GetString("MissingFileDlg_ValidateFilePath_You_must_choose_a_file_with_the___0___filename_ex" +
"tension_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No matching library data.
/// </summary>
public static string MissingLibraryDataFinder_DisplayName_No_matching_library_data {
get {
return ResourceManager.GetString("MissingLibraryDataFinder_DisplayName_No_matching_library_data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to missing scores.
/// </summary>
public static string MissingScoresFinder_DisplayName_missing_scores {
get {
return ResourceManager.GetString("MissingScoresFinder_DisplayName_missing_scores", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} missing from chromatogram peak.
/// </summary>
public static string MissingScoresFinder_Match__0__missing_from_chromatogram_peak {
get {
return ResourceManager.GetString("MissingScoresFinder_Match__0__missing_from_chromatogram_peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} missing from peptide.
/// </summary>
public static string MissingScoresFinder_Match__0__missing_from_peptide {
get {
return ResourceManager.GetString("MissingScoresFinder_Match__0__missing_from_peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Would you like to create a new empty document?.
/// </summary>
public static string ModeUIAwareFormHelper_EnableNeededButtonsForModeUI___Would_you_like_to_create_a_new_empty_document_ {
get {
return ResourceManager.GetString("ModeUIAwareFormHelper_EnableNeededButtonsForModeUI___Would_you_like_to_create_a_n" +
"ew_empty_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot switch to molecule interface because the current document contains proteomics data..
/// </summary>
public static string ModeUIAwareFormHelper_EnableNeededButtonsForModeUI_Cannot_switch_to_molecule_interface_because_the_current_document_contains_proteomics_data_ {
get {
return ResourceManager.GetString("ModeUIAwareFormHelper_EnableNeededButtonsForModeUI_Cannot_switch_to_molecule_inte" +
"rface_because_the_current_document_contains_proteomics_data_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot switch to proteomics interface because the current document contains non-proteomic molecule data..
/// </summary>
public static string ModeUIAwareFormHelper_EnableNeededButtonsForModeUI_Cannot_switch_to_proteomics_interface_because_the_current_document_contains_small_molecules_data_ {
get {
return ResourceManager.GetString("ModeUIAwareFormHelper_EnableNeededButtonsForModeUI_Cannot_switch_to_proteomics_in" +
"terface_because_the_current_document_contains_small_molecules_data_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Would you like to create a new document?.
/// </summary>
public static string ModeUIAwareFormHelper_EnableNeededButtonsForModeUI_Would_you_like_to_create_a_new_document_ {
get {
return ResourceManager.GetString("ModeUIAwareFormHelper_EnableNeededButtonsForModeUI_Would_you_like_to_create_a_new" +
"_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mixed interface.
/// </summary>
public static string ModeUIAwareFormHelper_SetModeUIToolStripButtons_Mixed_interface {
get {
return ResourceManager.GetString("ModeUIAwareFormHelper_SetModeUIToolStripButtons_Mixed_interface", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only show menus and controls appropriate to proteomics analysis.
/// </summary>
public static string ModeUIAwareFormHelper_SetModeUIToolStripButtons_Only_show_menus_and_controls_appropriate_to_proteomics_analysis {
get {
return ResourceManager.GetString("ModeUIAwareFormHelper_SetModeUIToolStripButtons_Only_show_menus_and_controls_appr" +
"opriate_to_proteomics_analysis", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only show menus and controls appropriate to non-proteomic molecule analysis.
/// </summary>
public static string ModeUIAwareFormHelper_SetModeUIToolStripButtons_Only_show_menus_and_controls_appropriate_to_small_molecule_analysis {
get {
return ResourceManager.GetString("ModeUIAwareFormHelper_SetModeUIToolStripButtons_Only_show_menus_and_controls_appr" +
"opriate_to_small_molecule_analysis", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Proteomics interface.
/// </summary>
public static string ModeUIAwareFormHelper_SetModeUIToolStripButtons_Proteomics_interface {
get {
return ResourceManager.GetString("ModeUIAwareFormHelper_SetModeUIToolStripButtons_Proteomics_interface", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show all menus and controls.
/// </summary>
public static string ModeUIAwareFormHelper_SetModeUIToolStripButtons_Show_all_menus_and_controls {
get {
return ResourceManager.GetString("ModeUIAwareFormHelper_SetModeUIToolStripButtons_Show_all_menus_and_controls", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule interface.
/// </summary>
public static string ModeUIAwareFormHelper_SetModeUIToolStripButtons_Small_Molecules_interface {
get {
return ResourceManager.GetString("ModeUIAwareFormHelper_SetModeUIToolStripButtons_Small_Molecules_interface", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Matching modifications.
/// </summary>
public static string ModificationMatcher_CreateMatches_Matching_modifications {
get {
return ResourceManager.GetString("ModificationMatcher_CreateMatches_Matching_modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unrecognized modification placement for Unimod id {0} in modified peptide sequence {1} (amino acid {2}, {3})..
/// </summary>
public static string ModificationMatcher_ThrowUnimodException_Unrecognized_modification_placement_for_Unimod_id__0__in_modified_peptide_sequence__1___amino_acid__2____3___ {
get {
return ResourceManager.GetString("ModificationMatcher_ThrowUnimodException_Unrecognized_modification_placement_for_" +
"Unimod_id__0__in_modified_peptide_sequence__1___amino_acid__2____3___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unrecognized Unimod id {0} in modified peptide sequence {1} (amino acid {2}, {3})..
/// </summary>
public static string ModificationMatcher_ThrowUnimodException_Unrecognized_Unimod_id__0__in_modified_peptide_sequence__1___amino_acid__2____3___ {
get {
return ResourceManager.GetString("ModificationMatcher_ThrowUnimodException_Unrecognized_Unimod_id__0__in_modified_p" +
"eptide_sequence__1___amino_acid__2____3___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid attempt to add data to completed MassLookup..
/// </summary>
public static string ModMassLookup_Add_Invalid_attempt_to_add_data_to_completed_MassLookup {
get {
return ResourceManager.GetString("ModMassLookup_Add_Invalid_attempt_to_add_data_to_completed_MassLookup", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid attempt to access incomplete MassLookup..
/// </summary>
public static string ModMassLookup_MatchModificationMass_Invalid_attempt_to_access_incomplete_MassLookup {
get {
return ResourceManager.GetString("ModMassLookup_MatchModificationMass_Invalid_attempt_to_access_incomplete_MassLook" +
"up", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Molecule {
get {
object obj = ResourceManager.GetObject("Molecule", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap MoleculeIrt {
get {
object obj = ResourceManager.GetObject("MoleculeIrt", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap MoleculeIrtLib {
get {
object obj = ResourceManager.GetObject("MoleculeIrtLib", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap MoleculeLib {
get {
object obj = ResourceManager.GetObject("MoleculeLib", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap MoleculeList {
get {
object obj = ResourceManager.GetObject("MoleculeList", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap MoleculeStandard {
get {
object obj = ResourceManager.GetObject("MoleculeStandard", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap MoleculeStandardLib {
get {
object obj = ResourceManager.GetObject("MoleculeStandardLib", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap MoleculeUI {
get {
object obj = ResourceManager.GetObject("MoleculeUI", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Export mProphet Features.
/// </summary>
public static string MProphetFeaturesDlg_OkDialog_Export_mProphet_Features {
get {
return ResourceManager.GetString("MProphetFeaturesDlg_OkDialog_Export_mProphet_Features", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed attempting to save mProphet features to {0}..
/// </summary>
public static string MProphetFeaturesDlg_OkDialog_Failed_attempting_to_save_mProphet_features_to__0__ {
get {
return ResourceManager.GetString("MProphetFeaturesDlg_OkDialog_Failed_attempting_to_save_mProphet_features_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to mProphet Feature Files.
/// </summary>
public static string MProphetFeaturesDlg_OkDialog_mProphet_Feature_Files {
get {
return ResourceManager.GetString("MProphetFeaturesDlg_OkDialog_mProphet_Feature_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to To export MProphet features first train an MProphet model..
/// </summary>
public static string MProphetFeaturesDlg_OkDialog_To_export_MProphet_features_first_train_an_MProphet_model_ {
get {
return ResourceManager.GetString("MProphetFeaturesDlg_OkDialog_To_export_MProphet_features_first_train_an_MProphet_" +
"model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempted to score a peak with {0} features using a model with {1} trained scores..
/// </summary>
public static string MProphetPeakScoringModel_CalcLinearScore_Attempted_to_score_a_peak_with__0__features_using_a_model_with__1__trained_scores_ {
get {
return ResourceManager.GetString("MProphetPeakScoringModel_CalcLinearScore_Attempted_to_score_a_peak_with__0__featu" +
"res_using_a_model_with__1__trained_scores_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insufficient decoy peaks ({0} with {1} targets) to continue training..
/// </summary>
public static string MProphetPeakScoringModel_CalculateWeights_Insufficient_decoy_peaks___0__with__1__targets__to_continue_training_ {
get {
return ResourceManager.GetString("MProphetPeakScoringModel_CalculateWeights_Insufficient_decoy_peaks___0__with__1__" +
"targets__to_continue_training_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insufficient target peaks ({0} with {1} decoys) detected at {2}% FDR to continue training..
/// </summary>
public static string MProphetPeakScoringModel_CalculateWeights_Insufficient_target_peaks___0__with__1__decoys__detected_at__2___FDR_to_continue_training_ {
get {
return ResourceManager.GetString("MProphetPeakScoringModel_CalculateWeights_Insufficient_target_peaks___0__with__1_" +
"_decoys__detected_at__2___FDR_to_continue_training_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to MProphetScoringModel was given a peak with {0} features, but it has {1} peak feature calculators.
/// </summary>
public static string MProphetPeakScoringModel_CreateTransitionGroups_MProphetScoringModel_was_given_a_peak_with__0__features__but_it_has__1__peak_feature_calculators {
get {
return ResourceManager.GetString("MProphetPeakScoringModel_CreateTransitionGroups_MProphetScoringModel_was_given_a_" +
"peak_with__0__features__but_it_has__1__peak_feature_calculators", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to MProphetPeakScoringModel requires at least one peak feature calculator with a weight value.
/// </summary>
public static string MProphetPeakScoringModel_DoValidate_MProphetPeakScoringModel_requires_at_least_one_peak_feature_calculator_with_a_weight_value {
get {
return ResourceManager.GetString("MProphetPeakScoringModel_DoValidate_MProphetPeakScoringModel_requires_at_least_on" +
"e_peak_feature_calculator_with_a_weight_value", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scoring model converged (iteration {0} - {1:#,#} peaks at {2:0.##%} FDR).
/// </summary>
public static string MProphetPeakScoringModel_Train_Scoring_model_converged__iteration__0_____1______peaks_at__2_0_____FDR_ {
get {
return ResourceManager.GetString("MProphetPeakScoringModel_Train_Scoring_model_converged__iteration__0_____1______p" +
"eaks_at__2_0_____FDR_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Training peak scoring model.
/// </summary>
public static string MProphetPeakScoringModel_Train_Training_peak_scoring_model {
get {
return ResourceManager.GetString("MProphetPeakScoringModel_Train_Training_peak_scoring_model", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Training scoring model (iteration {0} of {1}).
/// </summary>
public static string MProphetPeakScoringModel_Train_Training_scoring_model__iteration__0__of__1__ {
get {
return ResourceManager.GetString("MProphetPeakScoringModel_Train_Training_scoring_model__iteration__0__of__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Training scoring model (iteration {0} of {1} - {2:#,#} peaks at {3:0.##%} FDR).
/// </summary>
public static string MProphetPeakScoringModel_Train_Training_scoring_model__iteration__0__of__1_____2______peaks_at__3_0_____FDR_ {
get {
return ResourceManager.GetString("MProphetPeakScoringModel_Train_Training_scoring_model__iteration__0__of__1_____2_" +
"_____peaks_at__3_0_____FDR_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adjusting peak boundaries.
/// </summary>
public static string MProphetResultsHandler_ChangePeaks_Adjusting_peak_boundaries {
get {
return ResourceManager.GetString("MProphetResultsHandler_ChangePeaks_Adjusting_peak_boundaries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Q Value.
/// </summary>
public static string MProphetResultsHandler_Q_VALUE_ANNOTATION_Q_Value {
get {
return ResourceManager.GetString("MProphetResultsHandler_Q_VALUE_ANNOTATION_Q_Value", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Co-elution.
/// </summary>
public static string MQuestCoElutionCalc_MQuestCoElutionCalc_Coelution {
get {
return ResourceManager.GetString("MQuestCoElutionCalc_MQuestCoElutionCalc_Coelution", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default intensity.
/// </summary>
public static string MQuestDefaultIntensityCalc_Name_Default_Intensity {
get {
return ResourceManager.GetString("MQuestDefaultIntensityCalc_Name_Default_Intensity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default dotp or idotp.
/// </summary>
public static string MQuestDefaultIntensityCorrelationCalc_Name_Default_dotp_or_idotp {
get {
return ResourceManager.GetString("MQuestDefaultIntensityCorrelationCalc_Name_Default_dotp_or_idotp", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default co-elution (weighted).
/// </summary>
public static string MQuestDefaultWeightedCoElutionCalc_Name_Default_co_elution__weighted_ {
get {
return ResourceManager.GetString("MQuestDefaultWeightedCoElutionCalc_Name_Default_co_elution__weighted_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default shape (weighted).
/// </summary>
public static string MQuestDefaultWeightedShapeCalc_Name_Default_shape__weighted_ {
get {
return ResourceManager.GetString("MQuestDefaultWeightedShapeCalc_Name_Default_shape__weighted_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Intensity.
/// </summary>
public static string MQuestIntensityCalc_MQuestIntensityCalc_Intensity {
get {
return ResourceManager.GetString("MQuestIntensityCalc_MQuestIntensityCalc_Intensity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library intensity dot-product.
/// </summary>
public static string MQuestIntensityCorrelationCalc_Name_Library_intensity_dot_product {
get {
return ResourceManager.GetString("MQuestIntensityCorrelationCalc_Name_Library_intensity_dot_product", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Standard library dot-product.
/// </summary>
public static string MQuestIntensityStandardCorrelationCalc_Name_Standard_library_dot_product {
get {
return ResourceManager.GetString("MQuestIntensityStandardCorrelationCalc_Name_Standard_library_dot_product", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reference co-elution.
/// </summary>
public static string MQuestReferenceCoElutionCalc_MQuestReferenceCoElutionCalc_Reference_coelution {
get {
return ResourceManager.GetString("MQuestReferenceCoElutionCalc_MQuestReferenceCoElutionCalc_Reference_coelution", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reference intensity dot-product.
/// </summary>
public static string MQuestReferenceCorrelationCalc_MQuestReferenceCorrelationCalc_mQuest_reference_correlation {
get {
return ResourceManager.GetString("MQuestReferenceCorrelationCalc_MQuestReferenceCorrelationCalc_mQuest_reference_co" +
"rrelation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to mProphet weighted reference.
/// </summary>
public static string MQuestReferenceShapeCalc_MQuestReferenceShapeCalc_mProphet_weighted_reference {
get {
return ResourceManager.GetString("MQuestReferenceShapeCalc_MQuestReferenceShapeCalc_mProphet_weighted_reference", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reference shape.
/// </summary>
public static string MQuestReferenceShapeCalc_MQuestReferenceShapeCalc_Reference_shape {
get {
return ResourceManager.GetString("MQuestReferenceShapeCalc_MQuestReferenceShapeCalc_Reference_shape", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention time difference.
/// </summary>
public static string MQuestRetentionTimePredictionCalc_MQuestRetentionTimePredictionCalc_Retention_time_difference {
get {
return ResourceManager.GetString("MQuestRetentionTimePredictionCalc_MQuestRetentionTimePredictionCalc_Retention_tim" +
"e_difference", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention time difference squared.
/// </summary>
public static string MQuestRetentionTimeSquaredPredictionCalc_MQuestRetentionTimeSquaredPredictionCalc_Retention_time_difference_squared {
get {
return ResourceManager.GetString("MQuestRetentionTimeSquaredPredictionCalc_MQuestRetentionTimeSquaredPredictionCalc" +
"_Retention_time_difference_squared", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shape.
/// </summary>
public static string MQuestShapeCalc_MQuestShapeCalc_Shape {
get {
return ResourceManager.GetString("MQuestShapeCalc_MQuestShapeCalc_Shape", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Standard Intensity.
/// </summary>
public static string MQuestStandardIntensityCalc_Name_Standard_Intensity {
get {
return ResourceManager.GetString("MQuestStandardIntensityCalc_Name_Standard_Intensity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Standard co-elution (weighted).
/// </summary>
public static string MQuestStandardWeightedCoElutionCalc_Name_Standard_co_elution__weighted_ {
get {
return ResourceManager.GetString("MQuestStandardWeightedCoElutionCalc_Name_Standard_co_elution__weighted_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Standard shape (weighted).
/// </summary>
public static string MQuestStandardWeightedShapeCalc_Name_Standard_shape__weighted_ {
get {
return ResourceManager.GetString("MQuestStandardWeightedShapeCalc_Name_Standard_shape__weighted_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Co-elution (weighted).
/// </summary>
public static string MQuestWeightedCoElutionCalc_MQuestWeightedCoElutionCalc_mQuest_weighted_coelution {
get {
return ResourceManager.GetString("MQuestWeightedCoElutionCalc_MQuestWeightedCoElutionCalc_mQuest_weighted_coelution" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reference co-elution (weighted).
/// </summary>
public static string MQuestWeightedReferenceCoElutionCalc_MQuestWeightedReferenceCoElutionCalc_mQuest_weighted_reference_coelution {
get {
return ResourceManager.GetString("MQuestWeightedReferenceCoElutionCalc_MQuestWeightedReferenceCoElutionCalc_mQuest_" +
"weighted_reference_coelution", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reference shape (weighted).
/// </summary>
public static string MQuestWeightedReferenceShapeCalc_MQuestWeightedReferenceShapeCalc_mProphet_weighted_reference_shape {
get {
return ResourceManager.GetString("MQuestWeightedReferenceShapeCalc_MQuestWeightedReferenceShapeCalc_mProphet_weight" +
"ed_reference_shape", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shape (weighted).
/// </summary>
public static string MQuestWeightedShapeCalc_MQuestWeightedShapeCalc_mQuest_weighted_shape {
get {
return ResourceManager.GetString("MQuestWeightedShapeCalc_MQuestWeightedShapeCalc_mQuest_weighted_shape", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap MSAmandaLogo {
get {
object obj = ResourceManager.GetObject("MSAmandaLogo", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to MS/MS scan index {0} not found.
/// </summary>
public static string MsxDemultiplexer_FindStartStop_MsxDemultiplexer_MS_MS_index__0__not_found {
get {
return ResourceManager.GetString("MsxDemultiplexer_FindStartStop_MsxDemultiplexer_MS_MS_index__0__not_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading {0}.
/// </summary>
public static string MultiFileAsynchronousDownloadClient_DownloadFileAsync_Downloading__0 {
get {
return ResourceManager.GetString("MultiFileAsynchronousDownloadClient_DownloadFileAsync_Downloading__0", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading {0}.
/// </summary>
public static string MultiFileAsynchronousDownloadClient_DownloadFileAsync_Downloading__0_ {
get {
return ResourceManager.GetString("MultiFileAsynchronousDownloadClient_DownloadFileAsync_Downloading__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Download canceled..
/// </summary>
public static string MultiFileAsynchronousDownloadClient_DownloadFileAsyncWithBroker_Download_canceled_ {
get {
return ResourceManager.GetString("MultiFileAsynchronousDownloadClient_DownloadFileAsyncWithBroker_Download_canceled" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check the Modification tab in the Peptide Settings, the m/z types on the Prediction tab, or the m/z match tolerance on the Instrument tab of the Transition Settings..
/// </summary>
public static string MzMatchException_suggestion {
get {
return ResourceManager.GetString("MzMatchException_suggestion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap NewDocument {
get {
object obj = ResourceManager.GetObject("NewDocument", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Precursor-product shape score.
/// </summary>
public static string NextGenCrossWeightedShapeCalc_NextGenCrossWeightedShapeCalc_Precursor_product_shape_score {
get {
return ResourceManager.GetString("NextGenCrossWeightedShapeCalc_NextGenCrossWeightedShapeCalc_Precursor_product_sha" +
"pe_score", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor isotope dot product.
/// </summary>
public static string NextGenIsotopeDotProductCalc_NextGenIsotopeDotProductCalc_Precursor_isotope_dot_product {
get {
return ResourceManager.GetString("NextGenIsotopeDotProductCalc_NextGenIsotopeDotProductCalc_Precursor_isotope_dot_p" +
"roduct", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor mass error.
/// </summary>
public static string NextGenPrecursorMassErrorCalc_NextGenPrecursorMassErrorCalc_Precursor_mass_error {
get {
return ResourceManager.GetString("NextGenPrecursorMassErrorCalc_NextGenPrecursorMassErrorCalc_Precursor_mass_error", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product mass error.
/// </summary>
public static string NextGenProductMassErrorCalc_NextGenProductMassErrorCalc_Product_mass_error {
get {
return ResourceManager.GetString("NextGenProductMassErrorCalc_NextGenProductMassErrorCalc_Product_mass_error", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Signal to noise.
/// </summary>
public static string NextGenSignalNoiseCalc_NextGenSignalNoiseCalc_Signal_to_noise {
get {
return ResourceManager.GetString("NextGenSignalNoiseCalc_NextGenSignalNoiseCalc_Signal_to_noise", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Standard product mass error.
/// </summary>
public static string NextGenStandardProductMassErrorCalc_Name_Standard_product_mass_error {
get {
return ResourceManager.GetString("NextGenStandardProductMassErrorCalc_Name_Standard_product_mass_error", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Standard signal to noise.
/// </summary>
public static string NextGenStandardSignalNoiseCalc_Name_Standard_signal_to_noise {
get {
return ResourceManager.GetString("NextGenStandardSignalNoiseCalc_Name_Standard_signal_to_noise", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to NIST Spectral Library.
/// </summary>
public static string NistLibrary_SpecFilter_NIST_Spectral_Library {
get {
return ResourceManager.GetString("NistLibrary_SpecFilter_NIST_Spectral_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Imported library contains multiple entries for one or more {0} pairs.
///
///This is probably due to the library containing entries for multiple parameters
///such as instrument type or collision energy, but Skyline keys only on
///{0} so these entries are ambiguous.
///
///You should filter the library as needed before importing to Skyline.
///
///Here are the {0} pairs with multiple entries:
///{1}.
/// </summary>
public static string NistLibraryBase_CreateCache_ {
get {
return ResourceManager.GetString("NistLibraryBase_CreateCache_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not read the precursor m/z value "{0}".
/// </summary>
public static string NistLibraryBase_CreateCache_Could_not_read_the_precursor_m_z_value___0__ {
get {
return ResourceManager.GetString("NistLibraryBase_CreateCache_Could_not_read_the_precursor_m_z_value___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid format at peak {0} for {1}..
/// </summary>
public static string NistLibraryBase_CreateCache_Invalid_format_at_peak__0__for__1__ {
get {
return ResourceManager.GetString("NistLibraryBase_CreateCache_Invalid_format_at_peak__0__for__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to molecule+adduct.
/// </summary>
public static string NistLibraryBase_CreateCache_molecule_adduct {
get {
return ResourceManager.GetString("NistLibraryBase_CreateCache_molecule_adduct", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No peaks found for peptide {0}..
/// </summary>
public static string NistLibraryBase_CreateCache_No_peaks_found_for_peptide__0__ {
get {
return ResourceManager.GetString("NistLibraryBase_CreateCache_No_peaks_found_for_peptide__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak count for MS/MS spectrum exceeds maximum {0}..
/// </summary>
public static string NistLibraryBase_CreateCache_Peak_count_for_MS_MS_spectrum_excedes_maximum__0__ {
get {
return ResourceManager.GetString("NistLibraryBase_CreateCache_Peak_count_for_MS_MS_spectrum_excedes_maximum__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to peptide+charge.
/// </summary>
public static string NistLibraryBase_CreateCache_peptide_charge {
get {
return ResourceManager.GetString("NistLibraryBase_CreateCache_peptide_charge", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected end of file..
/// </summary>
public static string NistLibraryBase_CreateCache_Unexpected_end_of_file {
get {
return ResourceManager.GetString("NistLibraryBase_CreateCache_Unexpected_end_of_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected end of file in peaks for {0}..
/// </summary>
public static string NistLibraryBase_CreateCache_Unexpected_end_of_file_in_peaks_for__0__ {
get {
return ResourceManager.GetString("NistLibraryBase_CreateCache_Unexpected_end_of_file_in_peaks_for__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Building binary cache for {0} library.
/// </summary>
public static string NistLibraryBase_Load_Building_binary_cache_for__0__library {
get {
return ResourceManager.GetString("NistLibraryBase_Load_Building_binary_cache_for__0__library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed loading library '{0}'..
/// </summary>
public static string NistLibraryBase_Load_Failed_loading_library__0__ {
get {
return ResourceManager.GetString("NistLibraryBase_Load_Failed_loading_library__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid precursor charge found. File may be corrupted..
/// </summary>
public static string NistLibraryBase_Load_Invalid_precursor_charge_found_File_may_be_corrupted {
get {
return ResourceManager.GetString("NistLibraryBase_Load_Invalid_precursor_charge_found_File_may_be_corrupted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading {0} library.
/// </summary>
public static string NistLibraryBase_Load_Loading__0__library {
get {
return ResourceManager.GetString("NistLibraryBase_Load_Loading__0__library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file '{0}' is not a valid library..
/// </summary>
public static string NistLibraryBase_Load_The_file___0___is_not_a_valid_library_ {
get {
return ResourceManager.GetString("NistLibraryBase_Load_The_file___0___is_not_a_valid_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure trying to read peaks.
/// </summary>
public static string NistLibraryBase_ReadSpectrum_Failure_trying_to_read_peaks {
get {
return ResourceManager.GetString("NistLibraryBase_ReadSpectrum_Failure_trying_to_read_peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} (line {1}): {2}.
/// </summary>
public static string NistLibraryBase_ThrowIOException__0__line__1__2__ {
get {
return ResourceManager.GetString("NistLibraryBase_ThrowIOException__0__line__1__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to TFRatio.
/// </summary>
public static string NistLibSpecBase_PEP_RANK_TFRATIO_TFRatio {
get {
return ResourceManager.GetString("NistLibSpecBase_PEP_RANK_TFRATIO_TFRatio", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No centroided data available for file "{0}". Adjust your Full-Scan settings..
/// </summary>
public static string NoCentroidedDataException_NoCentroidedDataException_No_centroided_data_available_for_file___0_____Adjust_your_Full_Scan_settings_ {
get {
return ResourceManager.GetString("NoCentroidedDataException_NoCentroidedDataException_No_centroided_data_available_" +
"for_file___0_____Adjust_your_Full_Scan_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No scans in {0} match the current filter settings..
/// </summary>
public static string NoFullScanDataException_NoFullScanDataException_No_scans_in__0__match_the_current_filter_settings_ {
get {
return ResourceManager.GetString("NoFullScanDataException_NoFullScanDataException_No_scans_in__0__match_the_current" +
"_filter_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not contain SRM/MRM chromatograms. To extract chromatograms from its spectra, go to Settings > Transition Settings > Full-Scan and choose options appropriate to the acquisition method used..
/// </summary>
public static string NoFullScanFilteringException_NoFullScanFilteringException_The_file__0__does_not_contain_SRM_MRM_chromatograms__To_extract_chromatograms_from_its_spectra__go_to_Settings___Transition_Settings___Full_Scan_and_choose_options_appropriate_to_the_acquisition_method_used_ {
get {
return ResourceManager.GetString(@"NoFullScanFilteringException_NoFullScanFilteringException_The_file__0__does_not_contain_SRM_MRM_chromatograms__To_extract_chromatograms_from_its_spectra__go_to_Settings___Transition_Settings___Full_Scan_and_choose_options_appropriate_to_the_acquisition_method_used_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap NoPeak {
get {
object obj = ResourceManager.GetObject("NoPeak", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to No SRM/MRM data found in {0}..
/// </summary>
public static string NoSrmDataException_NoSrmDataException_No_SRM_MRM_data_found_in__0__ {
get {
return ResourceManager.GetString("NoSrmDataException_NoSrmDataException_No_SRM_MRM_data_found_in__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Note {
get {
object obj = ResourceManager.GetObject("Note", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to {0} (not found).
/// </summary>
public static string NotFoundChromGraphItem_NotFoundChromGraphItem__0__not_found {
get {
return ResourceManager.GetString("NotFoundChromGraphItem_NotFoundChromGraphItem__0__not_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to OK.
/// </summary>
public static string OK {
get {
return ResourceManager.GetString("OK", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempted modification of a read-only collection..
/// </summary>
public static string OneOrManyList_Add_Attempted_modification_of_a_read_only_collection {
get {
return ResourceManager.GetString("OneOrManyList_Add_Attempted_modification_of_a_read_only_collection", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The index {0} must be 0 for a single entry list..
/// </summary>
public static string OneOrManyList_ValidateIndex_The_index__0__must_be_0_for_a_single_entry_list {
get {
return ResourceManager.GetString("OneOrManyList_ValidateIndex_The_index__0__must_be_0_for_a_single_entry_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The index {0} must be between 0 and {1}..
/// </summary>
public static string OneOrManyList_ValidateIndex_The_index__0__must_be_between_0_and__1__ {
get {
return ResourceManager.GetString("OneOrManyList_ValidateIndex_The_index__0__must_be_between_0_and__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Open {
get {
object obj = ResourceManager.GetObject("Open", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to No remote accounts have been specified. If you have an existing Unifi account you can enter your login information now..
/// </summary>
public static string OpenDataSourceDialog_EnsureRemoteAccount_No_remote_accounts_have_been_specified__If_you_have_an_existing_Unifi_account_you_can_enter_your_login_information_now_ {
get {
return ResourceManager.GetString("OpenDataSourceDialog_EnsureRemoteAccount_No_remote_accounts_have_been_specified__" +
"If_you_have_an_existing_Unifi_account_you_can_enter_your_login_information_now_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to My Network Place.
/// </summary>
public static string OpenDataSourceDialog_lookInComboBox_SelectionChangeCommitted_My_Network_Place {
get {
return ResourceManager.GetString("OpenDataSourceDialog_lookInComboBox_SelectionChangeCommitted_My_Network_Place", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error.
/// </summary>
public static string OpenDataSourceDialog_Open_Error {
get {
return ResourceManager.GetString("OpenDataSourceDialog_Open_Error", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please select one or more data sources..
/// </summary>
public static string OpenDataSourceDialog_Open_Please_select_one_or_more_data_sources {
get {
return ResourceManager.GetString("OpenDataSourceDialog_Open_Please_select_one_or_more_data_sources", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Any spectra format.
/// </summary>
public static string OpenDataSourceDialog_OpenDataSourceDialog_Any_spectra_format {
get {
return ResourceManager.GetString("OpenDataSourceDialog_OpenDataSourceDialog_Any_spectra_format", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Desktop.
/// </summary>
public static string OpenDataSourceDialog_OpenDataSourceDialog_Desktop {
get {
return ResourceManager.GetString("OpenDataSourceDialog_OpenDataSourceDialog_Desktop", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to My Computer.
/// </summary>
public static string OpenDataSourceDialog_OpenDataSourceDialog_My_Computer {
get {
return ResourceManager.GetString("OpenDataSourceDialog_OpenDataSourceDialog_My_Computer", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to My Documents.
/// </summary>
public static string OpenDataSourceDialog_OpenDataSourceDialog_My_Documents {
get {
return ResourceManager.GetString("OpenDataSourceDialog_OpenDataSourceDialog_My_Documents", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to My Recent Documents.
/// </summary>
public static string OpenDataSourceDialog_OpenDataSourceDialog_My_Recent_Documents {
get {
return ResourceManager.GetString("OpenDataSourceDialog_OpenDataSourceDialog_My_Recent_Documents", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remote Accounts.
/// </summary>
public static string OpenDataSourceDialog_OpenDataSourceDialog_Remote_Accounts {
get {
return ResourceManager.GetString("OpenDataSourceDialog_OpenDataSourceDialog_Remote_Accounts", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to access failure.
/// </summary>
public static string OpenDataSourceDialog_populateComboBoxFromDirectory_access_failure {
get {
return ResourceManager.GetString("OpenDataSourceDialog_populateComboBoxFromDirectory_access_failure", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Local Drive.
/// </summary>
public static string OpenDataSourceDialog_populateComboBoxFromDirectory_Local_Drive {
get {
return ResourceManager.GetString("OpenDataSourceDialog_populateComboBoxFromDirectory_Local_Drive", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Network Share.
/// </summary>
public static string OpenDataSourceDialog_populateComboBoxFromDirectory_Network_Share {
get {
return ResourceManager.GetString("OpenDataSourceDialog_populateComboBoxFromDirectory_Network_Share", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Optical Drive.
/// </summary>
public static string OpenDataSourceDialog_populateComboBoxFromDirectory_Optical_Drive {
get {
return ResourceManager.GetString("OpenDataSourceDialog_populateComboBoxFromDirectory_Optical_Drive", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removable Drive.
/// </summary>
public static string OpenDataSourceDialog_populateComboBoxFromDirectory_Removable_Drive {
get {
return ResourceManager.GetString("OpenDataSourceDialog_populateComboBoxFromDirectory_Removable_Drive", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to access failure.
/// </summary>
public static string OpenDataSourceDialog_populateListViewFromDirectory_access_failure {
get {
return ResourceManager.GetString("OpenDataSourceDialog_populateListViewFromDirectory_access_failure", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to retrieve the contents of this directory..
/// </summary>
public static string OpenDataSourceDialog_populateListViewFromDirectory_An_error_occurred_attempting_to_retrieve_the_contents_of_this_directory {
get {
return ResourceManager.GetString("OpenDataSourceDialog_populateListViewFromDirectory_An_error_occurred_attempting_t" +
"o_retrieve_the_contents_of_this_directory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Local Drive.
/// </summary>
public static string OpenDataSourceDialog_populateListViewFromDirectory_Local_Drive {
get {
return ResourceManager.GetString("OpenDataSourceDialog_populateListViewFromDirectory_Local_Drive", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Network Share.
/// </summary>
public static string OpenDataSourceDialog_populateListViewFromDirectory_Network_Share {
get {
return ResourceManager.GetString("OpenDataSourceDialog_populateListViewFromDirectory_Network_Share", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Optical Drive.
/// </summary>
public static string OpenDataSourceDialog_populateListViewFromDirectory_Optical_Drive {
get {
return ResourceManager.GetString("OpenDataSourceDialog_populateListViewFromDirectory_Optical_Drive", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removable Drive.
/// </summary>
public static string OpenDataSourceDialog_populateListViewFromDirectory_Removable_Drive {
get {
return ResourceManager.GetString("OpenDataSourceDialog_populateListViewFromDirectory_Removable_Drive", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retry.
/// </summary>
public static string OpenDataSourceDialog_populateListViewFromDirectory_Retry {
get {
return ResourceManager.GetString("OpenDataSourceDialog_populateListViewFromDirectory_Retry", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Some source paths are invalid.
/// </summary>
public static string OpenDataSourceDialog_sourcePathTextBox_KeyUp_Some_source_paths_are_invalid {
get {
return ResourceManager.GetString("OpenDataSourceDialog_sourcePathTextBox_KeyUp_Some_source_paths_are_invalid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap OpenFolder {
get {
object obj = ResourceManager.GetObject("OpenFolder", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to The number of optimization steps {0} is not between {1} and {2}..
/// </summary>
public static string OptimizableRegression_Validate_The_number_of_optimization_steps__0__is_not_between__1__and__2__ {
get {
return ResourceManager.GetString("OptimizableRegression_Validate_The_number_of_optimization_steps__0__is_not_betwee" +
"n__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The optimization step size {0} is not greater than zero..
/// </summary>
public static string OptimizableRegression_Validate_The_optimization_step_size__0__is_not_greater_than_zero {
get {
return ResourceManager.GetString("OptimizableRegression_Validate_The_optimization_step_size__0__is_not_greater_than" +
"_zero", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to convert {0} optimizations to new format..
/// </summary>
public static string OptimizationDb_ConvertFromOldFormat_Failed_to_convert__0__optimizations_to_new_format_ {
get {
return ResourceManager.GetString("OptimizationDb_ConvertFromOldFormat_Failed_to_convert__0__optimizations_to_new_fo" +
"rmat_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Optimization Libraries.
/// </summary>
public static string OptimizationDb_FILTER_OPTDB_Optimization_Libraries {
get {
return ResourceManager.GetString("OptimizationDb_FILTER_OPTDB_Optimization_Libraries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library path cannot be null..
/// </summary>
public static string OptimizationDb_GetOptimizationDb_Library_path_cannot_be_null_ {
get {
return ResourceManager.GetString("OptimizationDb_GetOptimizationDb_Library_path_cannot_be_null_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading optimization library {0}.
/// </summary>
public static string OptimizationDb_GetOptimizationDb_Loading_optimization_library__0_ {
get {
return ResourceManager.GetString("OptimizationDb_GetOptimizationDb_Loading_optimization_library__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} could not be created. Perhaps you do not have sufficient privileges..
/// </summary>
public static string OptimizationDb_GetOptimizationDb_The_file__0__could_not_be_created__Perhaps_you_do_not_have_sufficient_privileges_ {
get {
return ResourceManager.GetString("OptimizationDb_GetOptimizationDb_The_file__0__could_not_be_created__Perhaps_you_d" +
"o_not_have_sufficient_privileges_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} could not be opened. {1}.
/// </summary>
public static string OptimizationDb_GetOptimizationDb_The_file__0__could_not_be_opened___1_ {
get {
return ResourceManager.GetString("OptimizationDb_GetOptimizationDb_The_file__0__could_not_be_opened___1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} could not be opened (conversion from old format failed). {1}.
/// </summary>
public static string OptimizationDb_GetOptimizationDb_The_file__0__could_not_be_opened__conversion_from_old_format_failed____1_ {
get {
return ResourceManager.GetString("OptimizationDb_GetOptimizationDb_The_file__0__could_not_be_opened__conversion_fro" +
"m_old_format_failed____1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} does not exist..
/// </summary>
public static string OptimizationDb_GetOptimizationDb_The_file__0__does_not_exist_ {
get {
return ResourceManager.GetString("OptimizationDb_GetOptimizationDb_The_file__0__does_not_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} is not a valid optimization library file..
/// </summary>
public static string OptimizationDb_GetOptimizationDb_The_file__0__is_not_a_valid_optimization_library_file_ {
get {
return ResourceManager.GetString("OptimizationDb_GetOptimizationDb_The_file__0__is_not_a_valid_optimization_library" +
"_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The path containing {0} does not exist..
/// </summary>
public static string OptimizationDb_GetOptimizationDb_The_path_containing__0__does_not_exist_ {
get {
return ResourceManager.GetString("OptimizationDb_GetOptimizationDb_The_path_containing__0__does_not_exist_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You do not have privilieges to access the file {0}..
/// </summary>
public static string OptimizationDb_GetOptimizationDb_You_do_not_have_privilieges_to_access_the_file__0__ {
get {
return ResourceManager.GetString("OptimizationDb_GetOptimizationDb_You_do_not_have_privilieges_to_access_the_file__" +
"0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot compare OptimizationKey to an object of a different type.
/// </summary>
public static string OptimizationKey_CompareTo_Cannot_compare_OptimizationKey_to_an_object_of_a_different_type {
get {
return ResourceManager.GetString("OptimizationKey_CompareTo_Cannot_compare_OptimizationKey_to_an_object_of_a_differ" +
"ent_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected use of optimization library before successful initialization..
/// </summary>
public static string OptimizationLibrary_RequireUsable_Unexpected_use_of_optimization_library_before_successful_initialization_ {
get {
return ResourceManager.GetString("OptimizationLibrary_RequireUsable_Unexpected_use_of_optimization_library_before_s" +
"uccessful_initialization_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Optimization Database:.
/// </summary>
public static string OptimizationLibraryList_Label_Optimization_Database {
get {
return ResourceManager.GetString("OptimizationLibraryList_Label_Optimization_Database", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Optimization Databases.
/// </summary>
public static string OptimizationLibraryList_Title_Edit_Optimization_Databases {
get {
return ResourceManager.GetString("OptimizationLibraryList_Title_Edit_Optimization_Databases", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None.
/// </summary>
public static string OptimizedMethodTypeExtension_LOCALIZED_VALUES_None {
get {
return ResourceManager.GetString("OptimizedMethodTypeExtension_LOCALIZED_VALUES_None", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor.
/// </summary>
public static string OptimizedMethodTypeExtension_LOCALIZED_VALUES_Precursor {
get {
return ResourceManager.GetString("OptimizedMethodTypeExtension_LOCALIZED_VALUES_Precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition.
/// </summary>
public static string OptimizedMethodTypeExtension_LOCALIZED_VALUES_Transition {
get {
return ResourceManager.GetString("OptimizedMethodTypeExtension_LOCALIZED_VALUES_Transition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing scan time value on scan {0}. Scan times are required for overlap-based demultiplexing..
/// </summary>
public static string OverlapDeconvSolverHandler_BuildDeconvBlock_Missing_scan_time_value_on_scan__0___Scan_times_are_required_for_overlap_based_demultiplexing_ {
get {
return ResourceManager.GetString("OverlapDeconvSolverHandler_BuildDeconvBlock_Missing_scan_time_value_on_scan__0___" +
"Scan_times_are_required_for_overlap_based_demultiplexing_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overlap deconvolution window scheme is rank deficient at scan {2}. Rank is {0} while matrix has dimension {1}. A non-degenerate overlapping window scheme is required..
/// </summary>
public static string OverlapDeconvSolverHandler_BuildDeconvBlock_Overlap_deconvolution_window_scheme_is_rank_deficient_at_scan__2___Rank_is__0__while_matrix_has_dimension__1____A_non_degenerate_overlapping_window_scheme_is_required_ {
get {
return ResourceManager.GetString("OverlapDeconvSolverHandler_BuildDeconvBlock_Overlap_deconvolution_window_scheme_i" +
"s_rank_deficient_at_scan__2___Rank_is__0__while_matrix_has_dimension__1____A_non" +
"_degenerate_overlapping_window_scheme_is_required_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempt to insert slice of deconvolution matrix failed due to out of range error..
/// </summary>
public static string OverlapDemultiplexer_attempt_to_insert_slice_of_deconvolution_matrix_failed_out_of_range {
get {
return ResourceManager.GetString("OverlapDemultiplexer_attempt_to_insert_slice_of_deconvolution_matrix_failed_out_o" +
"f_range", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempt to take slice of deconvolution matrix failed due to out of range error..
/// </summary>
public static string OverlapDemultiplexer_attempt_to_take_slice_of_deconvolution_matrix_failed_out_of_range {
get {
return ResourceManager.GetString("OverlapDemultiplexer_attempt_to_take_slice_of_deconvolution_matrix_failed_out_of_" +
"range", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to OverlapDemultiplexer:InitializeFile Improperly-formed overlap multiplexing file.
/// </summary>
public static string OverlapDemultiplexer_InitializeFile_OverlapDemultiplexer_InitializeFile_Improperly_formed_overlap_multiplexing_file {
get {
return ResourceManager.GetString("OverlapDemultiplexer_InitializeFile_OverlapDemultiplexer_InitializeFile_Improperl" +
"y_formed_overlap_multiplexing_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Number of regions {0} in overlap demultiplexer approximation must be less than number of scans {1}..
/// </summary>
public static string OverlapDemultiplexer_RowStart_Number_of_regions__0__in_overlap_demultiplexer_approximation_must_be_less_than_number_of_scans__1__ {
get {
return ResourceManager.GetString("OverlapDemultiplexer_RowStart_Number_of_regions__0__in_overlap_demultiplexer_appr" +
"oximation_must_be_less_than_number_of_scans__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The overlapiIsolation window scheme is missing some contiguous isolation windows..
/// </summary>
public static string OverlapDemultiplexer_the_isolation_window_overlap_scheme_does_not_cover_all_isolation_windows {
get {
return ResourceManager.GetString("OverlapDemultiplexer_the_isolation_window_overlap_scheme_does_not_cover_all_isola" +
"tion_windows", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Panorama {
get {
object obj = ResourceManager.GetObject("Panorama", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Error: An unknown error occurred trying to verify access to Panorama folder '{0}' on the server {1}.
///{2}.
/// </summary>
public static string PanoramaHelper_ValidateFolder_Exception_ {
get {
return ResourceManager.GetString("PanoramaHelper_ValidateFolder_Exception_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Unable to verify access to Panorama folder.
///{0}.
/// </summary>
public static string PanoramaHelper_ValidateFolder_PanoramaServerException_ {
get {
return ResourceManager.GetString("PanoramaHelper_ValidateFolder_PanoramaServerException_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: An unknown error occurred trying to verify Panorama server information.
///{0}.
/// </summary>
public static string PanoramaHelper_ValidateServer_Exception_ {
get {
return ResourceManager.GetString("PanoramaHelper_ValidateServer_Exception_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Unable to verify Panorama server information.
///{0}.
/// </summary>
public static string PanoramaHelper_ValidateServer_PanoramaServerException_ {
get {
return ResourceManager.GetString("PanoramaHelper_ValidateServer_PanoramaServerException_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PanoramaPublish {
get {
object obj = ResourceManager.GetObject("PanoramaPublish", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Unknown error attempting to upload to Panorama.
///{0}.
/// </summary>
public static string PanoramaPublishHelper_PublishDocToPanorama_ {
get {
return ResourceManager.GetString("PanoramaPublishHelper_PublishDocToPanorama_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: An import error occurred on the Panorama server {0}..
/// </summary>
public static string PanoramaPublishHelper_PublishDocToPanorama_Error__An_import_error_occurred_on_the_Panorama_server__0__ {
get {
return ResourceManager.GetString("PanoramaPublishHelper_PublishDocToPanorama_Error__An_import_error_occurred_on_the" +
"_Panorama_server__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Document import was cancelled on the Panorama server {0}..
/// </summary>
public static string PanoramaPublishHelper_PublishDocToPanorama_Error__Document_import_was_cancelled_on_the_Panorama_server__0__ {
get {
return ResourceManager.GetString("PanoramaPublishHelper_PublishDocToPanorama_Error__Document_import_was_cancelled_o" +
"n_the_Panorama_server__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error details can be found at {0}.
/// </summary>
public static string PanoramaPublishHelper_PublishDocToPanorama_Error_details_can_be_found_at__0_ {
get {
return ResourceManager.GetString("PanoramaPublishHelper_PublishDocToPanorama_Error_details_can_be_found_at__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Job details can be found at {0}..
/// </summary>
public static string PanoramaPublishHelper_PublishDocToPanorama_Job_details_can_be_found_at__0__ {
get {
return ResourceManager.GetString("PanoramaPublishHelper_PublishDocToPanorama_Job_details_can_be_found_at__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Uploading document to Panorama.
/// </summary>
public static string PanoramaPublishHelper_PublishDocToPanorama_Uploading_document_to_Panorama {
get {
return ResourceManager.GetString("PanoramaPublishHelper_PublishDocToPanorama_Uploading_document_to_Panorama", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} is not a Panorama folder.
/// </summary>
public static string PanoramaUtil_VerifyFolder__0__is_not_a_Panorama_folder {
get {
return ResourceManager.GetString("PanoramaUtil_VerifyFolder__0__is_not_a_Panorama_folder", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Folder {0} does not exist on the Panorama server {1}.
/// </summary>
public static string PanoramaUtil_VerifyFolder_Folder__0__does_not_exist_on_the_Panorama_server__1_ {
get {
return ResourceManager.GetString("PanoramaUtil_VerifyFolder_Folder__0__does_not_exist_on_the_Panorama_server__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User {0} does not have permissions to upload to the Panorama folder {1}.
/// </summary>
public static string PanoramaUtil_VerifyFolder_User__0__does_not_have_permissions_to_upload_to_the_Panorama_folder__1_ {
get {
return ResourceManager.GetString("PanoramaUtil_VerifyFolder_User__0__does_not_have_permissions_to_upload_to_the_Pan" +
"orama_folder__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} at position {1}.
/// </summary>
public static string ParseExceptionDetail_ToString__at_position__0_ {
get {
return ResourceManager.GetString("ParseExceptionDetail_ToString__at_position__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Paste {
get {
object obj = ResourceManager.GetObject("Paste", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to '{0}' is not a capital letter that corresponds to an amino acid..
/// </summary>
public static string PasteDlg_AddFasta__0__is_not_a_capital_letter_that_corresponds_to_an_amino_acid {
get {
return ResourceManager.GetString("PasteDlg_AddFasta__0__is_not_a_capital_letter_that_corresponds_to_an_amino_acid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An unexpected error occurred:.
/// </summary>
public static string PasteDlg_AddFasta_An_unexpected_error_occurred {
get {
return ResourceManager.GetString("PasteDlg_AddFasta_An_unexpected_error_occurred", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An unexpected error occurred: {0} ({1}).
/// </summary>
public static string PasteDlg_AddFasta_An_unexpected_error_occurred__0__1__ {
get {
return ResourceManager.GetString("PasteDlg_AddFasta_An_unexpected_error_occurred__0__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is no name for this protein.
/// </summary>
public static string PasteDlg_AddFasta_There_is_no_name_for_this_protein {
get {
return ResourceManager.GetString("PasteDlg_AddFasta_There_is_no_name_for_this_protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This must start with '>'.
/// </summary>
public static string PasteDlg_AddFasta_This_must_start_with {
get {
return ResourceManager.GetString("PasteDlg_AddFasta_This_must_start_with", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to OK.
/// </summary>
public static string PasteDlg_AddPeptides_OK {
get {
return ResourceManager.GetString("PasteDlg_AddPeptides_OK", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This peptide sequence was not found in the protein sequence.
/// </summary>
public static string PasteDlg_AddPeptides_This_peptide_sequence_was_not_found_in_the_protein_sequence {
get {
return ResourceManager.GetString("PasteDlg_AddPeptides_This_peptide_sequence_was_not_found_in_the_protein_sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to interpret peptide modifications.
/// </summary>
public static string PasteDlg_AddPeptides_Unable_to_interpret_peptide_modifications {
get {
return ResourceManager.GetString("PasteDlg_AddPeptides_Unable_to_interpret_peptide_modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Would you like to use the Unimod definitions for the following modifications?.
/// </summary>
public static string PasteDlg_AddPeptides_Would_you_like_to_use_the_Unimod_definitions_for_the_following_modifications {
get {
return ResourceManager.GetString("PasteDlg_AddPeptides_Would_you_like_to_use_the_Unimod_definitions_for_the_followi" +
"ng_modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid protein sequence: {0}.
/// </summary>
public static string PasteDlg_AddProteins_Invalid_protein_sequence__0__ {
get {
return ResourceManager.GetString("PasteDlg_AddProteins_Invalid_protein_sequence__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing protein sequence.
/// </summary>
public static string PasteDlg_AddProteins_Missing_protein_sequence {
get {
return ResourceManager.GetString("PasteDlg_AddProteins_Missing_protein_sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This protein was not found in the background proteome database..
/// </summary>
public static string PasteDlg_AddProteins_This_protein_was_not_found_in_the_background_proteome_database {
get {
return ResourceManager.GetString("PasteDlg_AddProteins_This_protein_was_not_found_in_the_background_proteome_databa" +
"se", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor m/z must be a number..
/// </summary>
public static string PasteDlg_AddTransitionList_The_precursor_m_z_must_be_a_number_ {
get {
return ResourceManager.GetString("PasteDlg_AddTransitionList_The_precursor_m_z_must_be_a_number_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The product m/z must be a number..
/// </summary>
public static string PasteDlg_AddTransitionList_The_product_m_z_must_be_a_number_ {
get {
return ResourceManager.GetString("PasteDlg_AddTransitionList_The_product_m_z_must_be_a_number_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The easiest way to use this window is to copy from Excel (or any text editor if the data is CSV formatted) and paste into the grid.
///
///Note that you can adjust column order in Skyline by dragging the column headers left or right.
///
///Most peptide transition lists can be imported with the "File|Import|Transition List..." menu item or even pasted directly into the Targets window..
/// </summary>
public static string PasteDlg_btnTransitionListHelp_Click_ {
get {
return ResourceManager.GetString("PasteDlg_btnTransitionListHelp_Click_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Notes on molecule ion formulas:
///
///If your transition list format combines formulas and adducts in a single column (e.g. "C8H10N4O2[M+Na]") then use the "Ion Formula" columns, and disregard the "Adduct" columns. If your transition list puts the neutral formula and adduct in seperate columns, then use the "Ion Formula" columns for neutral formulas, and the "Adduct" columns for adducts..
/// </summary>
public static string PasteDlg_btnTransitionListHelp_Click_2_ {
get {
return ResourceManager.GetString("PasteDlg_btnTransitionListHelp_Click_2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The easiest way to use this window is to copy from Excel (or any text editor if the data is CSV formatted) and paste into the grid.
///
///Note that you can adjust column order in Skyline by dragging the column headers left or right. For molecules, you can also select which columns to enable with the "Columns..." button.
///
///Most peptide transition lists can be imported with the "File|Import|Transition List..." menu item or even pasted directly into the Targets window. You can also do this with molecule transit [rest of string was truncated]";.
/// </summary>
public static string PasteDlg_btnTransitionListHelp_Click_SmallMol_ {
get {
return ResourceManager.GetString("PasteDlg_btnTransitionListHelp_Click_SmallMol_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Supported values for {0} are: {1}.
/// </summary>
public static string PasteDlg_btnTransitionListHelp_Click_Supported_values_for__0__are___1_ {
get {
return ResourceManager.GetString("PasteDlg_btnTransitionListHelp_Click_Supported_values_for__0__are___1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition List Help.
/// </summary>
public static string PasteDlg_btnTransitionListHelp_Click_Transition_List_Help {
get {
return ResourceManager.GetString("PasteDlg_btnTransitionListHelp_Click_Transition_List_Help", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is no sequence for this protein.
/// </summary>
public static string PasteDlg_CheckSequence_There_is_no_sequence_for_this_protein {
get {
return ResourceManager.GetString("PasteDlg_CheckSequence_There_is_no_sequence_for_this_protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insert.
/// </summary>
public static string PasteDlg_Description_Insert {
get {
return ResourceManager.GetString("PasteDlg_Description_Insert", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insert FASTA.
/// </summary>
public static string PasteDlg_Description_Insert_FASTA {
get {
return ResourceManager.GetString("PasteDlg_Description_Insert_FASTA", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insert peptide list.
/// </summary>
public static string PasteDlg_Description_Insert_peptide_list {
get {
return ResourceManager.GetString("PasteDlg_Description_Insert_peptide_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insert protein list.
/// </summary>
public static string PasteDlg_Description_Insert_protein_list {
get {
return ResourceManager.GetString("PasteDlg_Description_Insert_protein_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insert transition list.
/// </summary>
public static string PasteDlg_Description_Insert_transition_list {
get {
return ResourceManager.GetString("PasteDlg_Description_Insert_transition_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule List {0}.
/// </summary>
public static string PasteDlg_GetMoleculePeptideGroup_Molecule_List__0_ {
get {
return ResourceManager.GetString("PasteDlg_GetMoleculePeptideGroup_Molecule_List__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product m/z {0} isn't close enough to the nearest possible m/z {1} (delta{2})..
/// </summary>
public static string PasteDlg_GetMoleculeTransition_Product_m_z__0__isn_t_close_enough_to_the_nearest_possible_m_z__1___delta_2___ {
get {
return ResourceManager.GetString("PasteDlg_GetMoleculeTransition_Product_m_z__0__isn_t_close_enough_to_the_nearest_" +
"possible_m_z__1___delta_2___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor m/z {0} is not measureable with your current instrument settings..
/// </summary>
public static string PasteDlg_GetMoleculeTransitionGroup_The_precursor_m_z__0__is_not_measureable_with_your_current_instrument_settings_ {
get {
return ResourceManager.GetString("PasteDlg_GetMoleculeTransitionGroup_The_precursor_m_z__0__is_not_measureable_with" +
"_your_current_instrument_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide sequence cannot be blank..
/// </summary>
public static string PasteDlg_ListPeptideSequences_The_peptide_sequence_cannot_be_blank {
get {
return ResourceManager.GetString("PasteDlg_ListPeptideSequences_The_peptide_sequence_cannot_be_blank", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The structure of this crosslinked peptide is not supported by Skyline.
/// </summary>
public static string PasteDlg_ListPeptideSequences_The_structure_of_this_crosslinked_peptide_is_not_supported_by_Skyline {
get {
return ResourceManager.GetString("PasteDlg_ListPeptideSequences_The_structure_of_this_crosslinked_peptide_is_not_su" +
"pported_by_Skyline", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This peptide sequence contains invalid characters..
/// </summary>
public static string PasteDlg_ListPeptideSequences_This_peptide_sequence_contains_invalid_characters {
get {
return ResourceManager.GetString("PasteDlg_ListPeptideSequences_This_peptide_sequence_contains_invalid_characters", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error on line {0}: Precursor m/z {1} does not agree with value {2} as calculated from ion formula and charge state (delta = {3}, Transition Settings | Instrument | Method match tolerance m/z = {4}). Correct the m/z value in the table, or leave it blank and Skyline will calculate it for you..
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Error_on_line__0___Precursor_m_z__1__does_not_agree_with_value__2__as_calculated_from_ion_formula_and_charge_state__delta____3___Transition_Settings___Instrument___Method_match_tolerance_m_z____4_____Correct_the_m_z_value_in_the_table__or_leave_it_blank_and_Skyline_will_calculate_it_for_you_ {
get {
return ResourceManager.GetString(@"PasteDlg_ReadPrecursorOrProductColumns_Error_on_line__0___Precursor_m_z__1__does_not_agree_with_value__2__as_calculated_from_ion_formula_and_charge_state__delta____3___Transition_Settings___Instrument___Method_match_tolerance_m_z____4_____Correct_the_m_z_value_in_the_table__or_leave_it_blank_and_Skyline_will_calculate_it_for_you_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error on line {0}: Product m/z {1} does not agree with value {2} as calculated from ion formula and charge state (delta = {3}, Transition Settings | Instrument | Method match tolerance m/z = {4}). Correct the m/z value in the table, or leave it blank and Skyline will calculate it for you..
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Error_on_line__0___Product_m_z__1__does_not_agree_with_value__2__as_calculated_from_ion_formula_and_charge_state__delta____3___Transition_Settings___Instrument___Method_match_tolerance_m_z____4_____Correct_the_m_z_value_in_the_table__or_leave_it_blank_and_Skyline_will_calculate_it_for_you_ {
get {
return ResourceManager.GetString(@"PasteDlg_ReadPrecursorOrProductColumns_Error_on_line__0___Product_m_z__1__does_not_agree_with_value__2__as_calculated_from_ion_formula_and_charge_state__delta____3___Transition_Settings___Instrument___Method_match_tolerance_m_z____4_____Correct_the_m_z_value_in_the_table__or_leave_it_blank_and_Skyline_will_calculate_it_for_you_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid charge value {0}.
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Invalid_charge_value__0_ {
get {
return ResourceManager.GetString("PasteDlg_ReadPrecursorOrProductColumns_Invalid_charge_value__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid collision energy value {0}.
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Invalid_collision_energy_value__0_ {
get {
return ResourceManager.GetString("PasteDlg_ReadPrecursorOrProductColumns_Invalid_collision_energy_value__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid compensation voltage {0}.
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Invalid_compensation_voltage__0_ {
get {
return ResourceManager.GetString("PasteDlg_ReadPrecursorOrProductColumns_Invalid_compensation_voltage__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid cone voltage value {0}.
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Invalid_cone_voltage_value__0_ {
get {
return ResourceManager.GetString("PasteDlg_ReadPrecursorOrProductColumns_Invalid_cone_voltage_value__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid declustering potential {0}.
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Invalid_declustering_potential__0_ {
get {
return ResourceManager.GetString("PasteDlg_ReadPrecursorOrProductColumns_Invalid_declustering_potential__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid drift time high energy offset value {0}.
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Invalid_drift_time_high_energy_offset_value__0_ {
get {
return ResourceManager.GetString("PasteDlg_ReadPrecursorOrProductColumns_Invalid_drift_time_high_energy_offset_valu" +
"e__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid drift time value {0}.
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Invalid_drift_time_value__0_ {
get {
return ResourceManager.GetString("PasteDlg_ReadPrecursorOrProductColumns_Invalid_drift_time_value__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid m/z value {0}.
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Invalid_m_z_value__0_ {
get {
return ResourceManager.GetString("PasteDlg_ReadPrecursorOrProductColumns_Invalid_m_z_value__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid retention time value {0}.
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Invalid_retention_time_value__0_ {
get {
return ResourceManager.GetString("PasteDlg_ReadPrecursorOrProductColumns_Invalid_retention_time_value__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid retention time window value {0}.
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Invalid_retention_time_window_value__0_ {
get {
return ResourceManager.GetString("PasteDlg_ReadPrecursorOrProductColumns_Invalid_retention_time_window_value__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid S-Lens value {0}.
/// </summary>
public static string PasteDlg_ReadPrecursorOrProductColumns_Invalid_S_Lens_value__0_ {
get {
return ResourceManager.GetString("PasteDlg_ReadPrecursorOrProductColumns_Invalid_S_Lens_value__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No errors.
/// </summary>
public static string PasteDlg_ShowNoErrors_No_errors {
get {
return ResourceManager.GetString("PasteDlg_ShowNoErrors_No_errors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collisional Cross Section (sq A).
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Collisional_Cross_Section__sq_A_ {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Collisional_Cross_Section__sq_A_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cone Voltage.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Cone_Voltage {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Cone_Voltage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Explicit Collision Energy.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Explicit_Collision_Energy {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Explicit_Collision_Energy", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Explicit Compensation Voltage.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Explicit_Compensation_Voltage {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Explicit_Compensation_Voltage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Explicit Declustering Potential.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Explicit_Declustering_Potential {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Explicit_Declustering_Potential", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Explicit Drift Time (msec).
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Explicit_Drift_Time__msec_ {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Explicit_Drift_Time__msec_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Explicit Drift Time High Energy Offset (msec).
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Explicit_Drift_Time_High_Energy_Offset__msec_ {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Explicit_Drift_Time_High_Energy_Offset__msec_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Explicit Ion Mobility.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Explicit_Ion_Mobility {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Explicit_Ion_Mobility", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Explicit Ion Mobility High Energy Offset.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Explicit_Ion_Mobility_High_Energy_Offset {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Explicit_Ion_Mobility_High_Energy_Offset", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Explicit Ion Mobility Units.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Explicit_Ion_Mobility_Units {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Explicit_Ion_Mobility_Units", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Explicit Retention Time.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Explicit_Retention_Time {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Explicit_Retention_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Explicit Retention Time Window.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Explicit_Retention_Time_Window {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Explicit_Retention_Time_Window", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Label Type.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Label_Type {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Label_Type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule List Name.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Molecule_List_Name {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Molecule_List_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Note.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Note {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Note", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Peptide {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Possible loss of data could occur if you switch to {0}. Do you want to continue?.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Possible_loss_of_data_could_occur_if_you_switch_to__0___Do_you_want_to_continue_ {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Possible_loss_of_data_could_occur_if_you_switch_to__0" +
"___Do_you_want_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor Adduct.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Precursor_Adduct {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Precursor_Adduct", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor Charge.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Precursor_Charge {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Precursor_Charge", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor Formula.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Precursor_Formula {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Precursor_Formula", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor m/z.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Precursor_m_z {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Precursor_m_z", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor Name.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Precursor_Name {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Precursor_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product Adduct.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Product_Adduct {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Product_Adduct", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product Charge.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Product_Charge {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Product_Charge", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product Formula.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Product_Formula {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Product_Formula", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product m/z.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Product_m_z {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Product_m_z", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product Name.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Product_Name {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Product_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product Neutral Loss.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Product_Neutral_Loss {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Product_Neutral_Loss", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Protein description.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Protein_description {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Protein_description", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Protein name.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_Protein_name {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_Protein_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to S-Lens.
/// </summary>
public static string PasteDlg_UpdateMoleculeType_S_Lens {
get {
return ResourceManager.GetString("PasteDlg_UpdateMoleculeType_S_Lens", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error on line {0}: Precursor formula and m/z value do not agree for any charge state..
/// </summary>
public static string PasteDlg_ValidateEntry_Error_on_line__0___Precursor_formula_and_m_z_value_do_not_agree_for_any_charge_state_ {
get {
return ResourceManager.GetString("PasteDlg_ValidateEntry_Error_on_line__0___Precursor_formula_and_m_z_value_do_not_" +
"agree_for_any_charge_state_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error on line {0}: Precursor needs values for any two of: Formula, m/z or Charge..
/// </summary>
public static string PasteDlg_ValidateEntry_Error_on_line__0___Precursor_needs_values_for_any_two_of__Formula__m_z_or_Charge_ {
get {
return ResourceManager.GetString("PasteDlg_ValidateEntry_Error_on_line__0___Precursor_needs_values_for_any_two_of__" +
"Formula__m_z_or_Charge_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error on line {0}: Product formula and m/z value do not agree for any charge state..
/// </summary>
public static string PasteDlg_ValidateEntry_Error_on_line__0___Product_formula_and_m_z_value_do_not_agree_for_any_charge_state_ {
get {
return ResourceManager.GetString("PasteDlg_ValidateEntry_Error_on_line__0___Product_formula_and_m_z_value_do_not_ag" +
"ree_for_any_charge_state_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error on line {0}: Product needs values for any two of: Formula, m/z or Charge..
/// </summary>
public static string PasteDlg_ValidateEntry_Error_on_line__0___Product_needs_values_for_any_two_of__Formula__m_z_or_Charge_ {
get {
return ResourceManager.GetString("PasteDlg_ValidateEntry_Error_on_line__0___Product_needs_values_for_any_two_of__Fo" +
"rmula__m_z_or_Charge_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to filter them from the pasted list?.
/// </summary>
public static string PasteFilteredPeptidesDlg_Peptides_Do_you_want_to_filter_them_from_the_pasted_list {
get {
return ResourceManager.GetString("PasteFilteredPeptidesDlg_Peptides_Do_you_want_to_filter_them_from_the_pasted_list" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following peptides did not meet the current filter criteria:.
/// </summary>
public static string PasteFilteredPeptidesDlg_Peptides_The_following_peptides_did_not_meet_the_current_filter_criteria_ {
get {
return ResourceManager.GetString("PasteFilteredPeptidesDlg_Peptides_The_following_peptides_did_not_meet_the_current" +
"_filter_criteria_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must select an empty directory for the tutorial files..
/// </summary>
public static string PathChooserDlg_OkDialog_You_must_select_an_empty_directory_for_the_tutorial_files_ {
get {
return ResourceManager.GetString("PathChooserDlg_OkDialog_You_must_select_an_empty_directory_for_the_tutorial_files" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to PCA Plot.
/// </summary>
public static string PcaPlot_RefreshData_PCA_Plot {
get {
return ResourceManager.GetString("PcaPlot_RefreshData_PCA_Plot", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Across .
/// </summary>
public static string PcaPlot_UpdateGraph__Across_ {
get {
return ResourceManager.GetString("PcaPlot_UpdateGraph__Across_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to PCA on rows.
/// </summary>
public static string PcaPlot_UpdateGraph_PCA_on_rows {
get {
return ResourceManager.GetString("PcaPlot_UpdateGraph_PCA_on_rows", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Principal Component {0}.
/// </summary>
public static string PcaPlot_UpdateGraph_Principal_Component__0_ {
get {
return ResourceManager.GetString("PcaPlot_UpdateGraph_Principal_Component__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Peak {
get {
object obj = ResourceManager.GetObject("Peak", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PeakBlank {
get {
object obj = ResourceManager.GetObject("PeakBlank", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Must select a model for comparison..
/// </summary>
public static string PeakBoundaryCompareTest_DoTest_Must_select_a_model_for_comparison_ {
get {
return ResourceManager.GetString("PeakBoundaryCompareTest_DoTest_Must_select_a_model_for_comparison_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The first line does not contain any of the possible separators comma, tab or space..
/// </summary>
public static string PeakBoundaryImporter_DetermineCorrectSeparator_The_first_line_does_not_contain_any_of_the_possible_separators_comma__tab_or_space_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_DetermineCorrectSeparator_The_first_line_does_not_contain_an" +
"y_of_the_possible_separators_comma__tab_or_space_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The first line does not contain any of the possible separators semicolon, tab or space..
/// </summary>
public static string PeakBoundaryImporter_DetermineCorrectSeparator_The_first_line_does_not_contain_any_of_the_possible_separators_semicolon__tab_or_space_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_DetermineCorrectSeparator_The_first_line_does_not_contain_an" +
"y_of_the_possible_separators_semicolon__tab_or_space_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to find the necessary headers {0} in the first line.
/// </summary>
public static string PeakBoundaryImporter_Import_Failed_to_find_the_necessary_headers__0__in_the_first_line {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_Failed_to_find_the_necessary_headers__0__in_the_first" +
"_line", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to read the first line of the file.
/// </summary>
public static string PeakBoundaryImporter_Import_Failed_to_read_the_first_line_of_the_file {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_Failed_to_read_the_first_line_of_the_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Importing Peak Boundaries.
/// </summary>
public static string PeakBoundaryImporter_Import_Importing_Peak_Boundaries {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_Importing_Peak_Boundaries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Line {0} field count {1} differs from the first line, which has {2}.
/// </summary>
public static string PeakBoundaryImporter_Import_Line__0__field_count__1__differs_from_the_first_line__which_has__2_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_Line__0__field_count__1__differs_from_the_first_line_" +
"_which_has__2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing end time on line {0}.
/// </summary>
public static string PeakBoundaryImporter_Import_Missing_end_time_on_line__0_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_Missing_end_time_on_line__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing start time on line {0}.
/// </summary>
public static string PeakBoundaryImporter_Import_Missing_start_time_on_line__0_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_Missing_start_time_on_line__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide has unrecognized modifications {0} at line {1}.
/// </summary>
public static string PeakBoundaryImporter_Import_Peptide_has_unrecognized_modifications__0__at_line__1_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_Peptide_has_unrecognized_modifications__0__at_line__1" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sample {0} on line {1} does not match the file {2}..
/// </summary>
public static string PeakBoundaryImporter_Import_Sample__0__on_line__1__does_not_match_the_file__2__ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_Sample__0__on_line__1__does_not_match_the_file__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The decoy value {0} on line {1} is invalid: must be 0 or 1..
/// </summary>
public static string PeakBoundaryImporter_Import_The_decoy_value__0__on_line__1__is_invalid__must_be_0_or_1_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_The_decoy_value__0__on_line__1__is_invalid__must_be_0" +
"_or_1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' on line {1} is not a valid charge state..
/// </summary>
public static string PeakBoundaryImporter_Import_The_value___0___on_line__1__is_not_a_valid_charge_state_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_The_value___0___on_line__1__is_not_a_valid_charge_sta" +
"te_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' on line {1} is not a valid end time..
/// </summary>
public static string PeakBoundaryImporter_Import_The_value___0___on_line__1__is_not_a_valid_end_time_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_The_value___0___on_line__1__is_not_a_valid_end_time_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' on line {1} is not a valid start time..
/// </summary>
public static string PeakBoundaryImporter_Import_The_value___0___on_line__1__is_not_a_valid_start_time_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_The_value___0___on_line__1__is_not_a_valid_start_time" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' on line {1} is not a valid time..
/// </summary>
public static string PeakBoundaryImporter_Import_The_value___0___on_line__1__is_not_a_valid_time_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_Import_The_value___0___on_line__1__is_not_a_valid_time_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Continue peak boundary import ignoring these charge states?.
/// </summary>
public static string PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ignoring_these_charge_states_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ign" +
"oring_these_charge_states_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Continue peak boundary import ignoring this charge state?.
/// </summary>
public static string PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ignoring_this_charge_state_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ign" +
"oring_this_charge_state_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Continue peak boundary import ignoring this file?.
/// </summary>
public static string PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ignoring_this_file_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ign" +
"oring_this_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Continue peak boundary import ignoring this peptide?.
/// </summary>
public static string PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ignoring_this_peptide_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ign" +
"oring_this_peptide_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following {0} peptide, file, and charge state combinations were not recognized:.
/// </summary>
public static string PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following__0__peptide__file__and_charge_state_combinations_were_not_recognized_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following__0__peptide__file__" +
"and_charge_state_combinations_were_not_recognized_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following file name in the peak boundaries file was not recognized:.
/// </summary>
public static string PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following_file_name_in_the_peak_boundaries_file_was_not_recognized_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following_file_name_in_the_pe" +
"ak_boundaries_file_was_not_recognized_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following peptide, file, and charge state combination was not recognized:.
/// </summary>
public static string PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following_peptide__file__and_charge_state_combination_was_not_recognized_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following_peptide__file__and_" +
"charge_state_combination_was_not_recognized_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following peptide in the peak boundaries file was not recognized:.
/// </summary>
public static string PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following_peptide_in_the_peak_boundaries_file_was_not_recognized_ {
get {
return ResourceManager.GetString("PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following_peptide_in_the_peak" +
"_boundaries_file_was_not_recognized_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to read a score annotation for peptide {0} of file {1}.
/// </summary>
public static string PeakBoundsMatch_PeakBoundsMatch_Unable_to_read_a_score_annotation_for_peptide__0__of_file__1_ {
get {
return ResourceManager.GetString("PeakBoundsMatch_PeakBoundsMatch_Unable_to_read_a_score_annotation_for_peptide__0_" +
"_of_file__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to read apex retention time value for peptide {0} of file {1}..
/// </summary>
public static string PeakBoundsMatch_PeakBoundsMatch_Unable_to_read_apex_retention_time_value_for_peptide__0__of_file__1__ {
get {
return ResourceManager.GetString("PeakBoundsMatch_PeakBoundsMatch_Unable_to_read_apex_retention_time_value_for_pept" +
"ide__0__of_file__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to read q value annotation for peptide {0} of file {1}.
/// </summary>
public static string PeakBoundsMatch_QValue_Unable_to_read_q_value_annotation_for_peptide__0__of_file__1_ {
get {
return ResourceManager.GetString("PeakBoundsMatch_QValue_Unable_to_read_q_value_annotation_for_peptide__0__of_file_" +
"_1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to On line {0}, {1}.
/// </summary>
public static string PeakCalculatorGridViewDriver_ValidateRow_On_line__0____1_ {
get {
return ResourceManager.GetString("PeakCalculatorGridViewDriver_ValidateRow_On_line__0____1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to '{0}' is not a known name for a peak feature calculator.
/// </summary>
public static string PeakCalculatorWeight_Validate___0___is_not_a_known_name_for_a_peak_feature_calculator {
get {
return ResourceManager.GetString("PeakCalculatorWeight_Validate___0___is_not_a_known_name_for_a_peak_feature_calcul" +
"ator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculating peak group scores.
/// </summary>
public static string PeakFeatureEnumerator_GetPeakFeatures_Calculating_peak_group_scores {
get {
return ResourceManager.GetString("PeakFeatureEnumerator_GetPeakFeatures_Calculating_peak_group_scores", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak Scoring Models.
/// </summary>
public static string PeakScoringModelList_Label_Peak_Scoring_Models {
get {
return ResourceManager.GetString("PeakScoringModelList_Label_Peak_Scoring_Models", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Peak Scoring Models.
/// </summary>
public static string PeakScoringModelList_Title_Edit_Peak_Scoring_Models {
get {
return ResourceManager.GetString("PeakScoringModelList_Title_Edit_Peak_Scoring_Models", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Peptide {
get {
object obj = ResourceManager.GetObject("Peptide", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Explicit retention time window requires an explicit retention time value..
/// </summary>
public static string Peptide_ExplicitRetentionTimeWindow_Explicit_retention_time_window_requires_an_explicit_retention_time_value_ {
get {
return ResourceManager.GetString("Peptide_ExplicitRetentionTimeWindow_Explicit_retention_time_window_requires_an_ex" +
"plicit_retention_time_value_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete the molecule '{0}'?.
/// </summary>
public static string Peptide_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_the_molecule___0___ {
get {
return ResourceManager.GetString("Peptide_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_the_molecule___0___" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete the peptide '{0}'?.
/// </summary>
public static string Peptide_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_the_peptide___0___ {
get {
return ResourceManager.GetString("Peptide_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_the_peptide___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete these {0} molecules?.
/// </summary>
public static string Peptide_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__molecules_ {
get {
return ResourceManager.GetString("Peptide_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__molecules" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete these {0} peptides?.
/// </summary>
public static string Peptide_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__peptides_ {
get {
return ResourceManager.GetString("Peptide_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__peptides_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT standards can only be changed by modifying the iRT calculator.
/// </summary>
public static string Peptide_StandardType_iRT_standards_can_only_be_changed_by_modifying_the_iRT_calculator {
get {
return ResourceManager.GetString("Peptide_StandardType_iRT_standards_can_only_be_changed_by_modifying_the_iRT_calcu" +
"lator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Direct editing of this value is only supported for non-proteomic molecules..
/// </summary>
public static string Peptide_ThrowIfNotSmallMolecule_Direct_editing_of_this_value_is_only_supported_for_small_molecules_ {
get {
return ResourceManager.GetString("Peptide_ThrowIfNotSmallMolecule_Direct_editing_of_this_value_is_only_supported_fo" +
"r_small_molecules_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to (missed {5}).
/// </summary>
public static string Peptide_ToString__missed__5__ {
get {
return ResourceManager.GetString("Peptide_ToString__missed__5__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to (missed {0}).
/// </summary>
public static string Peptide_ToString_missed__0__ {
get {
return ResourceManager.GetString("Peptide_ToString_missed__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide sequence exceeds the bounds of the protein sequence..
/// </summary>
public static string Peptide_Validate_Peptide_sequence_exceeds_the_bounds_of_the_protein_sequence {
get {
return ResourceManager.GetString("Peptide_Validate_Peptide_sequence_exceeds_the_bounds_of_the_protein_sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides from protein sequences must have start and end values..
/// </summary>
public static string Peptide_Validate_Peptides_from_protein_sequences_must_have_start_and_end_values {
get {
return ResourceManager.GetString("Peptide_Validate_Peptides_from_protein_sequences_must_have_start_and_end_values", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides without a protein sequence do not support the start and end properties..
/// </summary>
public static string Peptide_Validate_Peptides_without_a_protein_sequence_do_not_support_the_start_and_end_properties {
get {
return ResourceManager.GetString("Peptide_Validate_Peptides_without_a_protein_sequence_do_not_support_the_start_and" +
"_end_properties", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide sequence {0} does not agree with the protein sequence {1} at ({2}:{3})..
/// </summary>
public static string Peptide_Validate_The_peptide_sequence__0__does_not_agree_with_the_protein_sequence__1__at__2__3__ {
get {
return ResourceManager.GetString("Peptide_Validate_The_peptide_sequence__0__does_not_agree_with_the_protein_sequenc" +
"e__1__at__2__3__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides.
/// </summary>
public static string PeptideAnnotationPairFinder_DisplayName_Peptides {
get {
return ResourceManager.GetString("PeptideAnnotationPairFinder_DisplayName_Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} CV.
/// </summary>
public static string PeptideAnnotationPairFinder_GetDisplayText__0__CV {
get {
return ResourceManager.GetString("PeptideAnnotationPairFinder_GetDisplayText__0__CV", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} CV in {1}.
/// </summary>
public static string PeptideAnnotationPairFinder_GetDisplayText__0__CV_in__1_ {
get {
return ResourceManager.GetString("PeptideAnnotationPairFinder_GetDisplayText__0__CV_in__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to process chromatograms for the molecule '{0}' because one chromatogram ends at time '{1}' and the other ends at time '{2}'..
/// </summary>
public static string PeptideChromDataSets_AddDataSet_Unable_to_process_chromatograms_for_the_molecule___0___because_one_chromatogram_ends_at_time___1___and_the_other_ends_at_time___2___ {
get {
return ResourceManager.GetString("PeptideChromDataSets_AddDataSet_Unable_to_process_chromatograms_for_the_molecule_" +
"__0___because_one_chromatogram_ends_at_time___1___and_the_other_ends_at_time___2" +
"___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected null peak list.
/// </summary>
public static string PeptideChromDataSets_MergePeakGroups_Unexpected_null_peak_list {
get {
return ResourceManager.GetString("PeptideChromDataSets_MergePeakGroups_Unexpected_null_peak_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PeptideDecoy {
get {
object obj = ResourceManager.GetObject("PeptideDecoy", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PeptideDecoyLib {
get {
object obj = ResourceManager.GetObject("PeptideDecoyLib", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to iRT.
/// </summary>
public static string PeptideDocNode_GetStandardTypeDisplayName_iRT {
get {
return ResourceManager.GetString("PeptideDocNode_GetStandardTypeDisplayName_iRT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Global Standard.
/// </summary>
public static string PeptideDocNode_GetStandardTypeDisplayName_Normalization {
get {
return ResourceManager.GetString("PeptideDocNode_GetStandardTypeDisplayName_Normalization", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to QC.
/// </summary>
public static string PeptideDocNode_GetStandardTypeDisplayName_QC {
get {
return ResourceManager.GetString("PeptideDocNode_GetStandardTypeDisplayName_QC", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} (rank {1}).
/// </summary>
public static string PeptideDocNodeToString__0__rank__1__ {
get {
return ResourceManager.GetString("PeptideDocNodeToString__0__rank__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Exclusions:.
/// </summary>
public static string PeptideExcludeList_Label_Exclusions {
get {
return ResourceManager.GetString("PeptideExcludeList_Label_Exclusions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Exclusions.
/// </summary>
public static string PeptideExcludeList_Title_Edit_Exclusions {
get {
return ResourceManager.GetString("PeptideExcludeList_Title_Edit_Exclusions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide exclusion must have a regular expression..
/// </summary>
public static string PeptideExcludeRegex_Validate_Peptide_exclusion_must_have_a_regular_expression {
get {
return ResourceManager.GetString("PeptideExcludeRegex_Validate_Peptide_exclusion_must_have_a_regular_expression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to excluded n-terminal amino acids.
/// </summary>
public static string PeptideFilter_DoValidate_excluded_n_terminal_amino_acids {
get {
return ResourceManager.GetString("PeptideFilter_DoValidate_excluded_n_terminal_amino_acids", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to maximum peptide length.
/// </summary>
public static string PeptideFilter_DoValidate_maximum_peptide_length {
get {
return ResourceManager.GetString("PeptideFilter_DoValidate_maximum_peptide_length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to minimum peptide length.
/// </summary>
public static string PeptideFilter_DoValidate_minimum_peptide_length {
get {
return ResourceManager.GetString("PeptideFilter_DoValidate_minimum_peptide_length", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide exclusion {0} has an invalid regular expression '{1}'..
/// </summary>
public static string PeptideFilter_DoValidate_The_peptide_exclusion__0__has_an_invalid_regular_expression__1__ {
get {
return ResourceManager.GetString("PeptideFilter_DoValidate_The_peptide_exclusion__0__has_an_invalid_regular_express" +
"ion__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid exclusion list..
/// </summary>
public static string PeptideFilter_ExcludeExprToRegEx_Invalid_exclusion_list {
get {
return ResourceManager.GetString("PeptideFilter_ExcludeExprToRegEx_Invalid_exclusion_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value {1} for {0} must be between {2} and {3}..
/// </summary>
public static string PeptideFilter_ValidateIntRange_The_value__1__for__0__must_be_between__2__and__3__ {
get {
return ResourceManager.GetString("PeptideFilter_ValidateIntRange_The_value__1__for__0__must_be_between__2__and__3__" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The sequence '{0}' is already present in the list..
/// </summary>
public static string PeptideGridViewDriver_DoCellValidating_The_sequence__0__is_already_present_in_the_list {
get {
return ResourceManager.GetString("PeptideGridViewDriver_DoCellValidating_The_sequence__0__is_already_present_in_the" +
"_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid decimal number format {0} on line {1}.
/// </summary>
public static string PeptideGridViewDriver_ValidateRow_Invalid_decimal_number_format__0__on_line__1_ {
get {
return ResourceManager.GetString("PeptideGridViewDriver_ValidateRow_Invalid_decimal_number_format__0__on_line__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing peptide sequence on line {0}.
/// </summary>
public static string PeptideGridViewDriver_ValidateRow_Missing_peptide_sequence_on_line__0_ {
get {
return ResourceManager.GetString("PeptideGridViewDriver_ValidateRow_Missing_peptide_sequence_on_line__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing value on line {0}.
/// </summary>
public static string PeptideGridViewDriver_ValidateRow_Missing_value_on_line__0_ {
get {
return ResourceManager.GetString("PeptideGridViewDriver_ValidateRow_Missing_value_on_line__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The pasted text must have two columns..
/// </summary>
public static string PeptideGridViewDriver_ValidateRow_The_pasted_text_must_have_two_columns_ {
get {
return ResourceManager.GetString("PeptideGridViewDriver_ValidateRow_The_pasted_text_must_have_two_columns_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The text {0} is not a valid peptide sequence on line {1}.
/// </summary>
public static string PeptideGridViewDriver_ValidateRow_The_text__0__is_not_a_valid_peptide_sequence_on_line__1_ {
get {
return ResourceManager.GetString("PeptideGridViewDriver_ValidateRow_The_text__0__is_not_a_valid_peptide_sequence_on" +
"_line__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The time {0} must be greater than zero on line {1}.
/// </summary>
public static string PeptideGridViewDriver_ValidateRow_The_time__0__must_be_greater_than_zero_on_line__1_ {
get {
return ResourceManager.GetString("PeptideGridViewDriver_ValidateRow_The_time__0__must_be_greater_than_zero_on_line_" +
"_1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The added lists contains {0} peptides which already appear in the {1} list..
/// </summary>
public static string PeptideGridViewDriver_ValidateUniquePeptides_The_added_lists_contains__0__peptides_which_already_appear_in_the__1__list {
get {
return ResourceManager.GetString("PeptideGridViewDriver_ValidateUniquePeptides_The_added_lists_contains__0__peptide" +
"s_which_already_appear_in_the__1__list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The added lists contains {0} peptides which appear multiple times..
/// </summary>
public static string PeptideGridViewDriver_ValidateUniquePeptides_The_added_lists_contains__0__peptides_which_appear_multiple_times {
get {
return ResourceManager.GetString("PeptideGridViewDriver_ValidateUniquePeptides_The_added_lists_contains__0__peptide" +
"s_which_appear_multiple_times", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following peptides already appear in the {0} list:.
/// </summary>
public static string PeptideGridViewDriver_ValidateUniquePeptides_The_following_peptides_already_appear_in_the__0__list {
get {
return ResourceManager.GetString("PeptideGridViewDriver_ValidateUniquePeptides_The_following_peptides_already_appea" +
"r_in_the__0__list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following peptides appear multiple times in the added list:.
/// </summary>
public static string PeptideGridViewDriver_ValidateUniquePeptides_The_following_peptides_appear_multiple_times_in_the_added_list {
get {
return ResourceManager.GetString("PeptideGridViewDriver_ValidateUniquePeptides_The_following_peptides_appear_multip" +
"le_times_in_the_added_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide '{0}' already appears in the {1} list..
/// </summary>
public static string PeptideGridViewDriver_ValidateUniquePeptides_The_peptide__0__already_appears_in_the__1__list {
get {
return ResourceManager.GetString("PeptideGridViewDriver_ValidateUniquePeptides_The_peptide__0__already_appears_in_t" +
"he__1__list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide '{0}' appears multiple times in the added list..
/// </summary>
public static string PeptideGridViewDriver_ValidateUniquePeptides_The_peptide__0__appears_multiple_times_in_the_added_list {
get {
return ResourceManager.GetString("PeptideGridViewDriver_ValidateUniquePeptides_The_peptide__0__appears_multiple_tim" +
"es_in_the_added_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to explain all transitions for {0} m/z {1} with a single set of modifications.
/// </summary>
public static string PeptideGroupBuilder_AppendTransition_Failed_to_explain_all_transitions_for_0__m_z__1__with_a_single_set_of_modifications {
get {
return ResourceManager.GetString("PeptideGroupBuilder_AppendTransition_Failed_to_explain_all_transitions_for_0__m_z" +
"__1__with_a_single_set_of_modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to explain all transitions for m/z {0} (peptide {1}) with a single precursor..
/// </summary>
public static string PeptideGroupBuilder_AppendTransition_Failed_to_explain_all_transitions_for_m_z__0___peptide__1___with_a_single_precursor {
get {
return ResourceManager.GetString("PeptideGroupBuilder_AppendTransition_Failed_to_explain_all_transitions_for_m_z__0" +
"___peptide__1___with_a_single_precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide {0} was not found in the sequence {1}..
/// </summary>
public static string PeptideGroupBuilder_AppendTransition_The_peptide__0__was_not_found_in_the_sequence__1__ {
get {
return ResourceManager.GetString("PeptideGroupBuilder_AppendTransition_The_peptide__0__was_not_found_in_the_sequenc" +
"e__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing iRT value for peptide {0}, precursor m/z {1}..
/// </summary>
public static string PeptideGroupBuilder_FinalizeTransitionGroups_Missing_iRT_value_for_peptide__0___precursor_m_z__1_ {
get {
return ResourceManager.GetString("PeptideGroupBuilder_FinalizeTransitionGroups_Missing_iRT_value_for_peptide__0___p" +
"recursor_m_z__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Two transitions of the same precursor, {0} (m/z {1}) , have different iRT values, {2} and {3}. iRT values must be assigned consistently in an imported transition list..
/// </summary>
public static string PeptideGroupBuilder_FinalizeTransitionGroups_Two_transitions_of_the_same_precursor___0___m_z__1_____have_different_iRT_values___2__and__3___iRT_values_must_be_assigned_consistently_in_an_imported_transition_list_ {
get {
return ResourceManager.GetString("PeptideGroupBuilder_FinalizeTransitionGroups_Two_transitions_of_the_same_precurso" +
"r___0___m_z__1_____have_different_iRT_values___2__and__3___iRT_values_must_be_as" +
"signed_consistently_in_an_imported_transition_list_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The current document settings would cause the number of peptides to exceed {0:n0}. The document settings must be more restrictive or add fewer proteins..
/// </summary>
public static string PeptideGroupDocNode_ChangeSettings_The_current_document_settings_would_cause_the_number_of_peptides_to_exceed__0_n0___The_document_settings_must_be_more_restrictive_or_add_fewer_proteins_ {
get {
return ResourceManager.GetString("PeptideGroupDocNode_ChangeSettings_The_current_document_settings_would_cause_the_" +
"number_of_peptides_to_exceed__0_n0___The_document_settings_must_be_more_restrict" +
"ive_or_add_fewer_proteins_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The current document settings would cause the number of targeted transitions to exceed {0:n0}. The document settings must be more restrictive or add fewer proteins..
/// </summary>
public static string PeptideGroupDocNode_ChangeSettings_The_current_document_settings_would_cause_the_number_of_targeted_transitions_to_exceed__0_n0___The_document_settings_must_be_more_restrictive_or_add_fewer_proteins_ {
get {
return ResourceManager.GetString("PeptideGroupDocNode_ChangeSettings_The_current_document_settings_would_cause_the_" +
"number_of_targeted_transitions_to_exceed__0_n0___The_document_settings_must_be_m" +
"ore_restrictive_or_add_fewer_proteins_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Peptides.
/// </summary>
public static string PeptideGroupTreeNode_ChildHeading__0__ {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_ChildHeading__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Molecules.
/// </summary>
public static string PeptideGroupTreeNode_ChildHeading__0__Molecules {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_ChildHeading__0__Molecules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} peptides.
/// </summary>
public static string PeptideGroupTreeNode_ChildUndoHeading__0__ {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_ChildUndoHeading__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} molecules.
/// </summary>
public static string PeptideGroupTreeNode_ChildUndoHeading__0__molecules {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_ChildUndoHeading__0__molecules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule List.
/// </summary>
public static string PeptideGroupTreeNode_Heading_Molecule_List {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_Heading_Molecule_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide List.
/// </summary>
public static string PeptideGroupTreeNode_Heading_Peptide_List {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_Heading_Peptide_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Protein.
/// </summary>
public static string PeptideGroupTreeNode_Heading_Protein {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_Heading_Protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <name: {0}>.
/// </summary>
public static string PeptideGroupTreeNode_ProteinModalDisplayText__name___0__ {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_ProteinModalDisplayText__name___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Accession.
/// </summary>
public static string PeptideGroupTreeNode_RenderTip_Accession {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_RenderTip_Accession", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Description.
/// </summary>
public static string PeptideGroupTreeNode_RenderTip_Description {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_RenderTip_Description", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Gene.
/// </summary>
public static string PeptideGroupTreeNode_RenderTip_Gene {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_RenderTip_Gene", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Name.
/// </summary>
public static string PeptideGroupTreeNode_RenderTip_Name {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_RenderTip_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Original Description.
/// </summary>
public static string PeptideGroupTreeNode_RenderTip_Original_Description {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_RenderTip_Original_Description", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Original Name.
/// </summary>
public static string PeptideGroupTreeNode_RenderTip_Original_Name {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_RenderTip_Original_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Preferred Name.
/// </summary>
public static string PeptideGroupTreeNode_RenderTip_Preferred_Name {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_RenderTip_Preferred_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Searched.
/// </summary>
public static string PeptideGroupTreeNode_RenderTip_Searched {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_RenderTip_Searched", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Species.
/// </summary>
public static string PeptideGroupTreeNode_RenderTip_Species {
get {
return ResourceManager.GetString("PeptideGroupTreeNode_RenderTip_Species", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PeptideIrt {
get {
object obj = ResourceManager.GetObject("PeptideIrt", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PeptideIrtLib {
get {
object obj = ResourceManager.GetObject("PeptideIrtLib", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PeptideLib {
get {
object obj = ResourceManager.GetObject("PeptideLib", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Libraries and library specifications do not match..
/// </summary>
public static string PeptideLibraries_DoValidate_Libraries_and_library_specifications_do_not_match_ {
get {
return ResourceManager.GetString("PeptideLibraries_DoValidate_Libraries_and_library_specifications_do_not_match_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library picked peptide count {0} must be between {1} and {2}..
/// </summary>
public static string PeptideLibraries_DoValidate_Library_picked_peptide_count__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("PeptideLibraries_DoValidate_Library_picked_peptide_count__0__must_be_between__1__" +
"and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Limiting peptides per protein requires a ranking method to be specified..
/// </summary>
public static string PeptideLibraries_DoValidate_Limiting_peptides_per_protein_requires_a_ranking_method_to_be_specified {
get {
return ResourceManager.GetString("PeptideLibraries_DoValidate_Limiting_peptides_per_protein_requires_a_ranking_meth" +
"od_to_be_specified", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The specified method of matching library spectra does not support peptide ranking..
/// </summary>
public static string PeptideLibraries_DoValidate_The_specified_method_of_matching_library_spectra_does_not_support_peptide_ranking {
get {
return ResourceManager.GetString("PeptideLibraries_DoValidate_The_specified_method_of_matching_library_spectra_does" +
"_not_support_peptide_ranking", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Specified libraries do not support the '{0}' peptide ranking..
/// </summary>
public static string PeptideLibraries_EnsureRankId_Specified_libraries_do_not_support_the___0___peptide_ranking {
get {
return ResourceManager.GetString("PeptideLibraries_EnsureRankId_Specified_libraries_do_not_support_the___0___peptid" +
"e_ranking", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempt to serialize list containing invalid type..
/// </summary>
public static string PeptideLibraries_WriteXml_Attempt_to_serialize_list_containing_invalid_type {
get {
return ResourceManager.GetString("PeptideLibraries_WriteXml_Attempt_to_serialize_list_containing_invalid_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PeptideList {
get {
object obj = ResourceManager.GetObject("PeptideList", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Modification type {0} not found..
/// </summary>
public static string PeptideModifications_ChangeModifications_Modification_type__0__not_found {
get {
return ResourceManager.GetString("PeptideModifications_ChangeModifications_Modification_type__0__not_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Maximum neutral losses {0} must be between {1} and {2}.
/// </summary>
public static string PeptideModifications_DoValidate_Maximum_neutral_losses__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("PeptideModifications_DoValidate_Maximum_neutral_losses__0__must_be_between__1__an" +
"d__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Maximum variable modifications {0} must be between {1} and {2}.
/// </summary>
public static string PeptideModifications_DoValidate_Maximum_variable_modifications__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("PeptideModifications_DoValidate_Maximum_variable_modifications__0__must_be_betwee" +
"n__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Heavy modifications found without '{0}' attribute..
/// </summary>
public static string PeptideModifications_ReadXml_Heavy_modifications_found_without__0__attribute {
get {
return ResourceManager.GetString("PeptideModifications_ReadXml_Heavy_modifications_found_without__0__attribute", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Internal standard type {0} not found..
/// </summary>
public static string PeptideModifications_ReadXml_Internal_standard_type__0__not_found {
get {
return ResourceManager.GetString("PeptideModifications_ReadXml_Internal_standard_type__0__not_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculating scheduling from trends requires a retention time window for measured data..
/// </summary>
public static string PeptidePrediction_CalcMaxTrendReplicates_Calculating_scheduling_from_trends_requires_a_retention_time_window_for_measured_data {
get {
return ResourceManager.GetString("PeptidePrediction_CalcMaxTrendReplicates_Calculating_scheduling_from_trends_requi" +
"res_a_retention_time_window_for_measured_data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The retention time window {0} for a scheduled method based on measured results must be between {1} and {2}..
/// </summary>
public static string PeptidePrediction_DoValidate_The_retention_time_window__0__for_a_scheduled_method_based_on_measured_results_must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("PeptidePrediction_DoValidate_The_retention_time_window__0__for_a_scheduled_method" +
"_based_on_measured_results_must_be_between__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PeptideQc {
get {
object obj = ResourceManager.GetObject("PeptideQc", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PeptideQcLib {
get {
object obj = ResourceManager.GetObject("PeptideQcLib", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Peptide.
/// </summary>
public static string PeptideRegressionTipProvider_RenderTip_Peptide {
get {
return ResourceManager.GetString("PeptideRegressionTipProvider_RenderTip_Peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must have imported results in order to train a model..
/// </summary>
public static string PeptideSettingsUI_comboPeakScoringModel_SelectedIndexChanged_The_document_must_have_imported_results_in_order_to_train_a_model_ {
get {
return ResourceManager.GetString("PeptideSettingsUI_comboPeakScoringModel_SelectedIndexChanged_The_document_must_ha" +
"ve_imported_results_in_order_to_train_a_model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unrecognized Model.
/// </summary>
public static string PeptideSettingsUI_ComboPeakScoringModelSelected_Unrecognized_Model {
get {
return ResourceManager.GetString("PeptideSettingsUI_ComboPeakScoringModelSelected_Unrecognized_Model", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to uncheck the ones that do not?.
/// </summary>
public static string PeptideSettingsUI_comboRank_SelectedIndexChanged_Do_you_want_to_uncheck_the_ones_that_do_not {
get {
return ResourceManager.GetString("PeptideSettingsUI_comboRank_SelectedIndexChanged_Do_you_want_to_uncheck_the_ones_" +
"that_do_not", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Not all libraries chosen support the '{0}' ranking for peptides..
/// </summary>
public static string PeptideSettingsUI_comboRank_SelectedIndexChanged_Not_all_libraries_chosen_support_the__0__ranking_for_peptides {
get {
return ResourceManager.GetString("PeptideSettingsUI_comboRank_SelectedIndexChanged_Not_all_libraries_chosen_support" +
"_the__0__ranking_for_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing peptide settings.
/// </summary>
public static string PeptideSettingsUI_OkDialog_Changing_peptide_settings {
get {
return ResourceManager.GetString("PeptideSettingsUI_OkDialog_Changing_peptide_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Finishing up building library.
/// </summary>
public static string PeptideSettingsUI_ShowBuildLibraryDlg_Finishing_up_building_library {
get {
return ResourceManager.GetString("PeptideSettingsUI_ShowBuildLibraryDlg_Finishing_up_building_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading {0}.
/// </summary>
public static string PeptideSettingsUI_ShowFilterMidasDlg_Loading__0_ {
get {
return ResourceManager.GetString("PeptideSettingsUI_ShowFilterMidasDlg_Loading__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading MIDAS Library.
/// </summary>
public static string PeptideSettingsUI_ShowFilterMidasDlg_Loading_MIDAS_Library {
get {
return ResourceManager.GetString("PeptideSettingsUI_ShowFilterMidasDlg_Loading_MIDAS_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Multiple MIDAS libraries in document. Select only one before filtering..
/// </summary>
public static string PeptideSettingsUI_ShowFilterMidasDlg_Multiple_MIDAS_libraries_in_document__Select_only_one_before_filtering_ {
get {
return ResourceManager.GetString("PeptideSettingsUI_ShowFilterMidasDlg_Multiple_MIDAS_libraries_in_document__Select" +
"_only_one_before_filtering_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide settings have been changed. Save changes?.
/// </summary>
public static string PeptideSettingsUI_ShowViewLibraryDlg_Peptide_settings_have_been_changed_Save_changes {
get {
return ResourceManager.GetString("PeptideSettingsUI_ShowViewLibraryDlg_Peptide_settings_have_been_changed_Save_chan" +
"ges", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Choose at least one internal standard type..
/// </summary>
public static string PeptideSettingsUI_ValidateNewSettings_Choose_at_least_one_internal_standard_type {
get {
return ResourceManager.GetString("PeptideSettingsUI_ValidateNewSettings_Choose_at_least_one_internal_standard_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to load background proteome {0}..
/// </summary>
public static string PeptideSettingsUI_ValidateNewSettings_Failed_to_load_background_proteome__0__ {
get {
return ResourceManager.GetString("PeptideSettingsUI_ValidateNewSettings_Failed_to_load_background_proteome__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to In order to use the 'Bilinear turning point' method of LOD calculation, 'Regression fit' must be set to 'Bilinear'..
/// </summary>
public static string PeptideSettingsUI_ValidateNewSettings_In_order_to_use_the__Bilinear_turning_point__method_of_LOD_calculation___Regression_fit__must_be_set_to__Bilinear__ {
get {
return ResourceManager.GetString("PeptideSettingsUI_ValidateNewSettings_In_order_to_use_the__Bilinear_turning_point" +
"__method_of_LOD_calculation___Regression_fit__must_be_set_to__Bilinear__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} is missing..
/// </summary>
public static string PeptideSettingsUI_ValidateNewSettings_The_file__0__is_missing_ {
get {
return ResourceManager.GetString("PeptideSettingsUI_ValidateNewSettings_The_file__0__is_missing_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} may not be a valid proteome file..
/// </summary>
public static string PeptideSettingsUI_ValidateNewSettings_The_file__0__may_not_be_a_valid_proteome_file {
get {
return ResourceManager.GetString("PeptideSettingsUI_ValidateNewSettings_The_file__0__may_not_be_a_valid_proteome_fi" +
"le", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculating....
/// </summary>
public static string PeptidesPerProteinDlg_UpdateRemaining_Calculating___ {
get {
return ResourceManager.GetString("PeptidesPerProteinDlg_UpdateRemaining_Calculating___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PeptideStandard {
get {
object obj = ResourceManager.GetObject("PeptideStandard", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PeptideStandardLib {
get {
object obj = ResourceManager.GetObject("PeptideStandardLib", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to CCS.
/// </summary>
public static string PeptideTipProvider_RenderTip_CCS {
get {
return ResourceManager.GetString("PeptideTipProvider_RenderTip_CCS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ion Mobility.
/// </summary>
public static string PeptideTipProvider_RenderTip_Ion_Mobility {
get {
return ResourceManager.GetString("PeptideTipProvider_RenderTip_Ion_Mobility", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor m/z.
/// </summary>
public static string PeptideTipProvider_RenderTip_Precursor_m_z {
get {
return ResourceManager.GetString("PeptideTipProvider_RenderTip_Precursor_m_z", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ion adducts.
/// </summary>
public static string PeptideToMoleculeText_Ion_adducts {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Ion_adducts", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ion charges.
/// </summary>
public static string PeptideToMoleculeText_Ion_charges {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Ion_charges", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modified Peptide Sequence.
/// </summary>
public static string PeptideToMoleculeText_Modified_Peptide_Sequence {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Modified_Peptide_Sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modified Sequence.
/// </summary>
public static string PeptideToMoleculeText_Modified_Sequence {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Modified_Sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule.
/// </summary>
public static string PeptideToMoleculeText_Molecule {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Molecule", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule List.
/// </summary>
public static string PeptideToMoleculeText_Molecule_List {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Molecule_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule Lists.
/// </summary>
public static string PeptideToMoleculeText_Molecule_Lists {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Molecule_Lists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecules.
/// </summary>
public static string PeptideToMoleculeText_Molecules {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Molecules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide.
/// </summary>
public static string PeptideToMoleculeText_Peptide {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide List.
/// </summary>
public static string PeptideToMoleculeText_Peptide_List {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Peptide_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide Sequence.
/// </summary>
public static string PeptideToMoleculeText_Peptide_Sequence {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Peptide_Sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides.
/// </summary>
public static string PeptideToMoleculeText_Peptides {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Protein.
/// </summary>
public static string PeptideToMoleculeText_Protein {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Proteins.
/// </summary>
public static string PeptideToMoleculeText_Proteins {
get {
return ResourceManager.GetString("PeptideToMoleculeText_Proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Precursors.
/// </summary>
public static string PeptideTreeNode_ChildHeading__0__ {
get {
return ResourceManager.GetString("PeptideTreeNode_ChildHeading__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} precursors.
/// </summary>
public static string PeptideTreeNode_ChildUndoHeading__0__ {
get {
return ResourceManager.GetString("PeptideTreeNode_ChildUndoHeading__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide.
/// </summary>
public static string PeptideTreeNode_Heading_Title {
get {
return ResourceManager.GetString("PeptideTreeNode_Heading_Title", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule.
/// </summary>
public static string PeptideTreeNode_Heading_Title_Molecule {
get {
return ResourceManager.GetString("PeptideTreeNode_Heading_Title_Molecule", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to First.
/// </summary>
public static string PeptideTreeNode_RenderTip_First {
get {
return ResourceManager.GetString("PeptideTreeNode_RenderTip_First", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Last.
/// </summary>
public static string PeptideTreeNode_RenderTip_Last {
get {
return ResourceManager.GetString("PeptideTreeNode_RenderTip_Last", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Neutral Mass.
/// </summary>
public static string PeptideTreeNode_RenderTip_Neutral_Mass {
get {
return ResourceManager.GetString("PeptideTreeNode_RenderTip_Neutral_Mass", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Next.
/// </summary>
public static string PeptideTreeNode_RenderTip_Next {
get {
return ResourceManager.GetString("PeptideTreeNode_RenderTip_Next", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Previous.
/// </summary>
public static string PeptideTreeNode_RenderTip_Previous {
get {
return ResourceManager.GetString("PeptideTreeNode_RenderTip_Previous", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Rank.
/// </summary>
public static string PeptideTreeNode_RenderTip_Rank {
get {
return ResourceManager.GetString("PeptideTreeNode_RenderTip_Rank", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Source.
/// </summary>
public static string PeptideTreeNode_RenderTip_Source {
get {
return ResourceManager.GetString("PeptideTreeNode_RenderTip_Source", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Permute isotope modifications.
/// </summary>
public static string PermuteIsotopeModificationsDlg_OkDialog_Permute_isotope_modifications {
get {
return ResourceManager.GetString("PermuteIsotopeModificationsDlg_OkDialog_Permute_isotope_modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Permuting Isotope Modifications.
/// </summary>
public static string PermuteIsotopeModificationsDlg_OkDialog_Permuting_Isotope_Modifications {
get {
return ResourceManager.GetString("PermuteIsotopeModificationsDlg_OkDialog_Permuting_Isotope_Modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Updating settings.
/// </summary>
public static string PermuteIsotopeModificationsDlg_OkDialog_Updating_settings {
get {
return ResourceManager.GetString("PermuteIsotopeModificationsDlg_OkDialog_Updating_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to External Tools.
/// </summary>
public static string PersistedViews_ExternalToolsGroup_External_Tools {
get {
return ResourceManager.GetString("PersistedViews_ExternalToolsGroup_External_Tools", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Main.
/// </summary>
public static string PersistedViews_MainGroup_Main {
get {
return ResourceManager.GetString("PersistedViews_MainGroup_Main", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to piecwise linear functions.
/// </summary>
public static string PiecewiseLinearRegressionFunction_GetRegressionDescription_piecwise_linear_functions {
get {
return ResourceManager.GetString("PiecewiseLinearRegressionFunction_GetRegressionDescription_piecwise_linear_functi" +
"ons", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to AreaRatio.
/// </summary>
public static string Pivoter_QualifyColumnInfo_AreaRatio {
get {
return ResourceManager.GetString("Pivoter_QualifyColumnInfo_AreaRatio", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to AreaRatioTo.
/// </summary>
public static string Pivoter_QualifyColumnInfo_AreaRatioTo {
get {
return ResourceManager.GetString("Pivoter_QualifyColumnInfo_AreaRatioTo", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to TotalAreaRatio.
/// </summary>
public static string Pivoter_QualifyColumnInfo_TotalAreaRatio {
get {
return ResourceManager.GetString("Pivoter_QualifyColumnInfo_TotalAreaRatio", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to TotalAreaRatioTo.
/// </summary>
public static string Pivoter_QualifyColumnInfo_TotalAreaRatioTo {
get {
return ResourceManager.GetString("Pivoter_QualifyColumnInfo_TotalAreaRatioTo", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A report must have at least one column..
/// </summary>
public static string PivotReportDlg_OkDialog_A_report_must_have_at_least_one_column {
get {
return ResourceManager.GetString("PivotReportDlg_OkDialog_A_report_must_have_at_least_one_column", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A report must have at least one column..
/// </summary>
public static string PivotReportDlg_ShowPreview_A_report_must_have_at_least_one_column_ {
get {
return ResourceManager.GetString("PivotReportDlg_ShowPreview_A_report_must_have_at_least_one_column_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} has been modified, since it was first opened..
/// </summary>
public static string PooledFileStream_Connect_The_file__0__has_been_modified_since_it_was_first_opened {
get {
return ResourceManager.GetString("PooledFileStream_Connect_The_file__0__has_been_modified_since_it_was_first_opened" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap PopupBtn {
get {
object obj = ResourceManager.GetObject("PopupBtn", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Auto-select filtered {0}.
/// </summary>
public static string PopupPickList_UpdateAutoManageUI_Auto_select_filtered__0_ {
get {
return ResourceManager.GetString("PopupPickList_UpdateAutoManageUI_Auto_select_filtered__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to off.
/// </summary>
public static string PopupPickList_UpdateAutoManageUI_off {
get {
return ResourceManager.GetString("PopupPickList_UpdateAutoManageUI_off", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete the precursor '{0}'?.
/// </summary>
public static string Precursor_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_the_precursor___0___ {
get {
return ResourceManager.GetString("Precursor_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_the_precursor___0" +
"___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete these {0} precursors?.
/// </summary>
public static string Precursor_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__precursors_ {
get {
return ResourceManager.GetString("Precursor_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__precurs" +
"ors_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Print {
get {
object obj = ResourceManager.GetObject("Print", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to A standard peptide was missing when trying to recalibrate..
/// </summary>
public static string ProcessedIrtAverages_RecalibrateStandards_A_standard_peptide_was_missing_when_trying_to_recalibrate_ {
get {
return ResourceManager.GetString("ProcessedIrtAverages_RecalibrateStandards_A_standard_peptide_was_missing_when_try" +
"ing_to_recalibrate_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error copying external tools from previous installation.
/// </summary>
public static string Program_CopyOldTools_Error_copying_external_tools_from_previous_installation {
get {
return ResourceManager.GetString("Program_CopyOldTools_Error_copying_external_tools_from_previous_installation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copying external tools from a previous installation.
/// </summary>
public static string Program_Main_Copying_external_tools_from_a_previous_installation {
get {
return ResourceManager.GetString("Program_Main_Copying_external_tools_from_a_previous_installation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Install 32-bit {0}.
/// </summary>
public static string Program_Main_Install_32_bit__0__ {
get {
return ResourceManager.GetString("Program_Main_Install_32_bit__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You are attempting to run a 64-bit version of {0} on a 32-bit OS. Please install the 32-bit version..
/// </summary>
public static string Program_Main_You_are_attempting_to_run_a_64_bit_version_of__0__on_a_32_bit_OS_Please_install_the_32_bit_version {
get {
return ResourceManager.GetString("Program_Main_You_are_attempting_to_run_a_64_bit_version_of__0__on_a_32_bit_OS_Ple" +
"ase_install_the_32_bit_version", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ProgramPathCollectors must have a program name.
/// </summary>
public static string ProgramPathContainer_Validate_ProgramPathCollectors_must_have_a_program_name {
get {
return ResourceManager.GetString("ProgramPathContainer_Validate_ProgramPathCollectors_must_have_a_program_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Property: .
/// </summary>
public static string Property_DisambiguationPrefix_Property__ {
get {
return ResourceManager.GetString("Property_DisambiguationPrefix_Property__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap prosit_logo_dark_blue {
get {
object obj = ResourceManager.GetObject("prosit_logo_dark_blue", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Protein {
get {
object obj = ResourceManager.GetObject("Protein", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete the molecule list '{0}'?.
/// </summary>
public static string Protein_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_the_molecule_list___0___ {
get {
return ResourceManager.GetString("Protein_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_the_molecule_list__" +
"_0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete the protein '{0}'?.
/// </summary>
public static string Protein_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_the_protein___0___ {
get {
return ResourceManager.GetString("Protein_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_the_protein___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete these {0} molecule lists?.
/// </summary>
public static string Protein_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__molecule_lists_ {
get {
return ResourceManager.GetString("Protein_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__molecule_" +
"lists_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete these {0} proteins?.
/// </summary>
public static string Protein_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__proteins_ {
get {
return ResourceManager.GetString("Protein_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__proteins_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap ProteinDecoy {
get {
object obj = ResourceManager.GetObject("ProteinDecoy", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Resolving protein details.
/// </summary>
public static string ProteinMetadataManager_LookupProteinMetadata_resolving_protein_details {
get {
return ResourceManager.GetString("ProteinMetadataManager_LookupProteinMetadata_resolving_protein_details", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap ProteinUI {
get {
object obj = ResourceManager.GetObject("ProteinUI", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap ProteoWizard {
get {
object obj = ResourceManager.GetObject("ProteoWizard", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Error retrieving server folders:.
/// </summary>
public static string PublishDocumentDlg_addSubFolders_Error_retrieving_server_folders {
get {
return ResourceManager.GetString("PublishDocumentDlg_addSubFolders_Error_retrieving_server_folders", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shared Files.
/// </summary>
public static string PublishDocumentDlg_btnBrowse_Click_Shared_Files {
get {
return ResourceManager.GetString("PublishDocumentDlg_btnBrowse_Click_Shared_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline Shared Documents.
/// </summary>
public static string PublishDocumentDlg_btnBrowse_Click_Skyline_Shared_Documents {
get {
return ResourceManager.GetString("PublishDocumentDlg_btnBrowse_Click_Skyline_Shared_Documents", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Upload Document.
/// </summary>
public static string PublishDocumentDlg_btnBrowse_Click_Upload_Document {
get {
return ResourceManager.GetString("PublishDocumentDlg_btnBrowse_Click_Upload_Document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please select a folder.
/// </summary>
public static string PublishDocumentDlg_OkDialog_Please_select_a_folder {
get {
return ResourceManager.GetString("PublishDocumentDlg_OkDialog_Please_select_a_folder", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please select a Skyline Shared file to upload..
/// </summary>
public static string PublishDocumentDlg_OkDialog_Please_select_a_Skyline_Shared_file_to_upload {
get {
return ResourceManager.GetString("PublishDocumentDlg_OkDialog_Please_select_a_Skyline_Shared_file_to_upload", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Selected file is not a Skyline Shared file..
/// </summary>
public static string PublishDocumentDlg_OkDialog_Selected_file_is_not_a_Skyline_Shared_file {
get {
return ResourceManager.GetString("PublishDocumentDlg_OkDialog_Selected_file_is_not_a_Skyline_Shared_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retrieving information from servers.
/// </summary>
public static string PublishDocumentDlg_PublishDocumentDlg_Load_Retrieving_information_on_servers {
get {
return ResourceManager.GetString("PublishDocumentDlg_PublishDocumentDlg_Load_Retrieving_information_on_servers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed attempting to retrieve information from the following servers:.
/// </summary>
public static string PublishDocumentDlg_PublishDocumentDlgLoad_Failed_attempting_to_retrieve_information_from_the_following_servers_ {
get {
return ResourceManager.GetString("PublishDocumentDlg_PublishDocumentDlgLoad_Failed_attempting_to_retrieve_informati" +
"on_from_the_following_servers_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Go to Tools > Options > Panorama tab to update the username and password..
/// </summary>
public static string PublishDocumentDlg_PublishDocumentDlgLoad_Go_to_Tools___Options___Panorama_tab_to_update_the_username_and_password_ {
get {
return ResourceManager.GetString("PublishDocumentDlg_PublishDocumentDlgLoad_Go_to_Tools___Options___Panorama_tab_to" +
"_update_the_username_and_password_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The selected server does not support version {0} of the skyd file format.
///Please contact the Panorama server administrator to upgrade the server..
/// </summary>
public static string PublishDocumentDlg_ServerSupportsSkydVersion_ {
get {
return ResourceManager.GetString("PublishDocumentDlg_ServerSupportsSkydVersion_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Click here to view the error details..
/// </summary>
public static string PublishDocumentDlg_UploadSharedZipFile_Click_here_to_view_the_error_details_ {
get {
return ResourceManager.GetString("PublishDocumentDlg_UploadSharedZipFile_Click_here_to_view_the_error_details_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error obtaining server information..
/// </summary>
public static string PublishDocumentDlg_UploadSharedZipFile_Error_obtaining_server_information {
get {
return ResourceManager.GetString("PublishDocumentDlg_UploadSharedZipFile_Error_obtaining_server_information", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Uploading File.
/// </summary>
public static string PublishDocumentDlg_UploadSharedZipFile_Uploading_File {
get {
return ResourceManager.GetString("PublishDocumentDlg_UploadSharedZipFile_Uploading_File", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You do not have permission to upload to the given folder..
/// </summary>
public static string PublishDocumentDlg_UploadSharedZipFile_You_do_not_have_permission_to_upload_to_the_given_folder {
get {
return ResourceManager.GetString("PublishDocumentDlg_UploadSharedZipFile_You_do_not_have_permission_to_upload_to_th" +
"e_given_folder", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to download the following packages:.
/// </summary>
public static string PythonInstaller_DownloadPackages_Failed_to_download_the_following_packages_ {
get {
return ResourceManager.GetString("PythonInstaller_DownloadPackages_Failed_to_download_the_following_packages_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Download failed. Check your network connection or contact Skyline developers..
/// </summary>
public static string PythonInstaller_DownloadPip_Download_failed__Check_your_network_connection_or_contact_Skyline_developers_ {
get {
return ResourceManager.GetString("PythonInstaller_DownloadPip_Download_failed__Check_your_network_connection_or_con" +
"tact_Skyline_developers_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check your network connection or contact the tool provider for installation support..
/// </summary>
public static string PythonInstaller_DownloadPython_Check_your_network_connection_or_contact_the_tool_provider_for_installation_support_ {
get {
return ResourceManager.GetString("PythonInstaller_DownloadPython_Check_your_network_connection_or_contact_the_tool_" +
"provider_for_installation_support_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Download failed..
/// </summary>
public static string PythonInstaller_DownloadPython_Download_failed_ {
get {
return ResourceManager.GetString("PythonInstaller_DownloadPython_Download_failed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Installing Packages.
/// </summary>
public static string PythonInstaller_GetPackages_Installing_Packages {
get {
return ResourceManager.GetString("PythonInstaller_GetPackages_Installing_Packages", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Package installation completed..
/// </summary>
public static string PythonInstaller_GetPackages_Package_installation_completed_ {
get {
return ResourceManager.GetString("PythonInstaller_GetPackages_Package_installation_completed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Installing Pip.
/// </summary>
public static string PythonInstaller_GetPip_Installing_Pip {
get {
return ResourceManager.GetString("PythonInstaller_GetPip_Installing_Pip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Installing Python.
/// </summary>
public static string PythonInstaller_GetPython_Installing_Python {
get {
return ResourceManager.GetString("PythonInstaller_GetPython_Installing_Python", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Python installation completed..
/// </summary>
public static string PythonInstaller_GetPython_Python_installation_completed_ {
get {
return ResourceManager.GetString("PythonInstaller_GetPython_Python_installation_completed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Install.
/// </summary>
public static string PythonInstaller_InstallPackages_Install {
get {
return ResourceManager.GetString("PythonInstaller_InstallPackages_Install", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Package installation failed. Error log output in immediate window..
/// </summary>
public static string PythonInstaller_InstallPackages_Package_installation_failed__Error_log_output_in_immediate_window_ {
get {
return ResourceManager.GetString("PythonInstaller_InstallPackages_Package_installation_failed__Error_log_output_in_" +
"immediate_window_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Package Installation was not completed. Canceling tool installation..
/// </summary>
public static string PythonInstaller_InstallPackages_Package_Installation_was_not_completed__Canceling_tool_installation_ {
get {
return ResourceManager.GetString("PythonInstaller_InstallPackages_Package_Installation_was_not_completed__Canceling" +
"_tool_installation_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Pip installation complete..
/// </summary>
public static string PythonInstaller_InstallPackages_Pip_installation_complete_ {
get {
return ResourceManager.GetString("PythonInstaller_InstallPackages_Pip_installation_complete_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Python package installation cannot continue. Canceling tool installation..
/// </summary>
public static string PythonInstaller_InstallPackages_Python_package_installation_cannot_continue__Canceling_tool_installation_ {
get {
return ResourceManager.GetString("PythonInstaller_InstallPackages_Python_package_installation_cannot_continue__Canc" +
"eling_tool_installation_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline uses the Python tool setuptools and the Python package manager Pip to install packages from source. Click install to begin the installation process..
/// </summary>
public static string PythonInstaller_InstallPackages_Skyline_uses_the_Python_tool_setuptools_and_the_Python_package_manager_Pip_to_install_packages_from_source__Click_install_to_begin_the_installation_process_ {
get {
return ResourceManager.GetString("PythonInstaller_InstallPackages_Skyline_uses_the_Python_tool_setuptools_and_the_P" +
"ython_package_manager_Pip_to_install_packages_from_source__Click_install_to_begi" +
"n_the_installation_process_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown error installing packages..
/// </summary>
public static string PythonInstaller_InstallPackages_Unknown_error_installing_packages_ {
get {
return ResourceManager.GetString("PythonInstaller_InstallPackages_Unknown_error_installing_packages_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Pip installation failed. Error log output in immediate window..
/// </summary>
public static string PythonInstaller_InstallPip_Pip_installation_failed__Error_log_output_in_immediate_window__ {
get {
return ResourceManager.GetString("PythonInstaller_InstallPip_Pip_installation_failed__Error_log_output_in_immediate" +
"_window__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown error installing pip..
/// </summary>
public static string PythonInstaller_InstallPip_Unknown_error_installing_pip_ {
get {
return ResourceManager.GetString("PythonInstaller_InstallPip_Unknown_error_installing_pip_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Python installation failed. Canceling tool installation..
/// </summary>
public static string PythonInstaller_InstallPython_Python_installation_failed__Canceling_tool_installation_ {
get {
return ResourceManager.GetString("PythonInstaller_InstallPython_Python_installation_failed__Canceling_tool_installa" +
"tion_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires Python {0}. Click install to begin the installation process..
/// </summary>
public static string PythonInstaller_PythonInstaller_Load_This_tool_requires_Python__0___Click_install_to_begin_the_installation_process_ {
get {
return ResourceManager.GetString("PythonInstaller_PythonInstaller_Load_This_tool_requires_Python__0___Click_install" +
"_to_begin_the_installation_process_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires Python {0} and the following packages. Select packages to install and then click Install to begin the installation process..
/// </summary>
public static string PythonInstaller_PythonInstaller_Load_This_tool_requires_Python__0__and_the_following_packages__Select_packages_to_install_and_then_click_Install_to_begin_the_installation_process_ {
get {
return ResourceManager.GetString("PythonInstaller_PythonInstaller_Load_This_tool_requires_Python__0__and_the_follow" +
"ing_packages__Select_packages_to_install_and_then_click_Install_to_begin_the_ins" +
"tallation_process_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires the following Python packages. Select packages to install and then click Install to begin the installation process..
/// </summary>
public static string PythonInstaller_PythonInstaller_Load_This_tool_requires_the_following_Python_packages__Select_packages_to_install_and_then_click_Install_to_begin_the_installation_process_ {
get {
return ResourceManager.GetString("PythonInstaller_PythonInstaller_Load_This_tool_requires_the_following_Python_pack" +
"ages__Select_packages_to_install_and_then_click_Install_to_begin_the_installatio" +
"n_process_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ratio {0} To {1}.
/// </summary>
public static string RatioPropertyAccessor_PeptideProperty_Ratio__0__To__1_ {
get {
return ResourceManager.GetString("RatioPropertyAccessor_PeptideProperty_Ratio__0__To__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ratio {0} To Global Standards.
/// </summary>
public static string RatioPropertyAccessor_PeptideRatioProperty_Ratio__0__To_Global_Standards {
get {
return ResourceManager.GetString("RatioPropertyAccessor_PeptideRatioProperty_Ratio__0__To_Global_Standards", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ratio To Global Standards.
/// </summary>
public static string RatioPropertyAccessor_PeptideRatioProperty_Ratio_To_Global_Standards {
get {
return ResourceManager.GetString("RatioPropertyAccessor_PeptideRatioProperty_Ratio_To_Global_Standards", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Total Area Ratio To {0}.
/// </summary>
public static string RatioPropertyAccessor_PrecursorRatioProperty_Total_Area_Ratio_To__0_ {
get {
return ResourceManager.GetString("RatioPropertyAccessor_PrecursorRatioProperty_Total_Area_Ratio_To__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Total Area Ratio To Global Standards.
/// </summary>
public static string RatioPropertyAccessor_PrecursorRatioProperty_Total_Area_Ratio_To_Global_Standards {
get {
return ResourceManager.GetString("RatioPropertyAccessor_PrecursorRatioProperty_Total_Area_Ratio_To_Global_Standards" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Area Ratio To {0}.
/// </summary>
public static string RatioPropertyAccessor_TransitionRatioProperty_Area_Ratio_To__0_ {
get {
return ResourceManager.GetString("RatioPropertyAccessor_TransitionRatioProperty_Area_Ratio_To__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Area Ratio To Global Standards.
/// </summary>
public static string RatioPropertyAccessor_TransitionRatioProperty_Area_Ratio_To_Global_Standards {
get {
return ResourceManager.GetString("RatioPropertyAccessor_TransitionRatioProperty_Area_Ratio_To_Global_Standards", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ratio to surrogate {0}.
/// </summary>
public static string RatioToSurrogate_ToString_Ratio_to_surrogate__0_ {
get {
return ResourceManager.GetString("RatioToSurrogate_ToString_Ratio_to_surrogate__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ratio to surrogate {0} ({1}).
/// </summary>
public static string RatioToSurrogate_ToString_Ratio_to_surrogate__0____1__ {
get {
return ResourceManager.GetString("RatioToSurrogate_ToString_Ratio_to_surrogate__0____1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected use of iRT calculator before successful initialization..
/// </summary>
public static string RCalcIrt_RequireUsable_Unexpected_use_of_iRT_calculator_before_successful_initialization {
get {
return ResourceManager.GetString("RCalcIrt_RequireUsable_Unexpected_use_of_iRT_calculator_before_successful_initial" +
"ization", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected use of iRT calculator before successful initialization..
/// </summary>
public static string RCalcIrt_RequireUsable_Unexpected_use_of_iRT_calculator_before_successful_initialization_ {
get {
return ResourceManager.GetString("RCalcIrt_RequireUsable_Unexpected_use_of_iRT_calculator_before_successful_initial" +
"ization_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dot Product {0} To {1}.
/// </summary>
public static string RDotPPropertyAccessor_PeptideProperty_Dot_Product__0__To__1_ {
get {
return ResourceManager.GetString("RDotPPropertyAccessor_PeptideProperty_Dot_Product__0__To__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dot Product To {0}.
/// </summary>
public static string RDotPPropertyAccessor_PrecursorProperty_Dot_Product_To__0_ {
get {
return ResourceManager.GetString("RDotPPropertyAccessor_PrecursorProperty_Dot_Product_To__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap RedX {
get {
object obj = ResourceManager.GetObject("RedX", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap RedXTransparentBackground {
get {
object obj = ResourceManager.GetObject("RedXTransparentBackground", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Add la&bel type:.
/// </summary>
public static string RefineDlg_cbAdd_CheckedChanged_Add_label_type {
get {
return ResourceManager.GetString("RefineDlg_cbAdd_CheckedChanged_Add_label_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursors of the chosen isotope label type will be added if they are missing.
/// </summary>
public static string RefineDlg_cbAdd_CheckedChanged_Precursors_of_the_chosen_isotope_label_type_will_be_added_if_they_are_missing {
get {
return ResourceManager.GetString("RefineDlg_cbAdd_CheckedChanged_Precursors_of_the_chosen_isotope_label_type_will_b" +
"e_added_if_they_are_missing", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1.
/// </summary>
public static string RefineDlg_MSLevel_1 {
get {
return ResourceManager.GetString("RefineDlg_MSLevel_1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 2.
/// </summary>
public static string RefineDlg_MSLevel_2 {
get {
return ResourceManager.GetString("RefineDlg_MSLevel_2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Total ion current.
/// </summary>
public static string RefineDlg_NormalizationMethod_Total_ion_current {
get {
return ResourceManager.GetString("RefineDlg_NormalizationMethod_Total_ion_current", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must be less than min peak found ratio..
/// </summary>
public static string RefineDlg_OkDialog__0__must_be_less_than_min_peak_found_ratio {
get {
return ResourceManager.GetString("RefineDlg_OkDialog__0__must_be_less_than_min_peak_found_ratio", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The label type '{0}' cannot be added. There are no modifications for this type..
/// </summary>
public static string RefineDlg_OkDialog_The_label_type__0__cannot_be_added_There_are_no_modifications_for_this_type {
get {
return ResourceManager.GetString("RefineDlg_OkDialog_The_label_type__0__cannot_be_added_There_are_no_modifications_" +
"for_this_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to all.
/// </summary>
public static string RefineDlg_RefineDlg_all {
get {
return ResourceManager.GetString("RefineDlg_RefineDlg_all", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to best.
/// </summary>
public static string RefineDlg_RefineDlg_best {
get {
return ResourceManager.GetString("RefineDlg_RefineDlg_best", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursors.
/// </summary>
public static string RefineDlg_RefineDlg_Precursors {
get {
return ResourceManager.GetString("RefineDlg_RefineDlg_Precursors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Products.
/// </summary>
public static string RefineDlg_RefineDlg_Products {
get {
return ResourceManager.GetString("RefineDlg_RefineDlg_Products", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to continue?.
/// </summary>
public static string RefineListDlg_OkDialog_Do_you_want_to_continue {
get {
return ResourceManager.GetString("RefineListDlg_OkDialog_Do_you_want_to_continue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None of the specified peptides are in the document..
/// </summary>
public static string RefineListDlg_OkDialog_None_of_the_specified_peptides_are_in_the_document {
get {
return ResourceManager.GetString("RefineListDlg_OkDialog_None_of_the_specified_peptides_are_in_the_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Of the specified {0} peptides {1} are not in the document. Do you want to continue?.
/// </summary>
public static string RefineListDlg_OkDialog_Of_the_specified__0__peptides__1__are_not_in_the_document_Do_you_want_to_continue {
get {
return ResourceManager.GetString("RefineListDlg_OkDialog_Of_the_specified__0__peptides__1__are_not_in_the_document_" +
"Do_you_want_to_continue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following peptides are not in the document:.
/// </summary>
public static string RefineListDlg_OkDialog_The_following_peptides_are_not_in_the_document {
get {
return ResourceManager.GetString("RefineListDlg_OkDialog_The_following_peptides_are_not_in_the_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following sequences are not valid peptides:.
/// </summary>
public static string RefineListDlg_OkDialog_The_following_sequences_are_not_valid_peptides {
get {
return ResourceManager.GetString("RefineListDlg_OkDialog_The_following_sequences_are_not_valid_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide '{0}' is not in the document..
/// </summary>
public static string RefineListDlg_OkDialog_The_peptide___0___is_not_in_the_document {
get {
return ResourceManager.GetString("RefineListDlg_OkDialog_The_peptide___0___is_not_in_the_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide '{0}' is not in the document. Do you want to continue?.
/// </summary>
public static string RefineListDlg_OkDialog_The_peptide__0__is_not_in_the_document_Do_you_want_to_continue {
get {
return ResourceManager.GetString("RefineListDlg_OkDialog_The_peptide__0__is_not_in_the_document_Do_you_want_to_cont" +
"inue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The sequence '{0}' is not a valid peptide..
/// </summary>
public static string RefineListDlg_OkDialog_The_sequence__0__is_not_a_valid_peptide {
get {
return ResourceManager.GetString("RefineListDlg_OkDialog_The_sequence__0__is_not_a_valid_peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to continue?.
/// </summary>
public static string RefineListDlgProtein_OkDialog_Do_you_want_to_continue {
get {
return ResourceManager.GetString("RefineListDlgProtein_OkDialog_Do_you_want_to_continue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None of the specified proteins are in the document..
/// </summary>
public static string RefineListDlgProtein_OkDialog_None_of_the_specified_proteins_are_in_the_document_ {
get {
return ResourceManager.GetString("RefineListDlgProtein_OkDialog_None_of_the_specified_proteins_are_in_the_document_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Of the specified {0} proteins {1} are not in the document. Do you want to continue?.
/// </summary>
public static string RefineListDlgProtein_OkDialog_Of_the_specified__0__proteins__1__are_not_in_the_document__Do_you_want_to_continue_ {
get {
return ResourceManager.GetString("RefineListDlgProtein_OkDialog_Of_the_specified__0__proteins__1__are_not_in_the_do" +
"cument__Do_you_want_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following proteins are not in the document:.
/// </summary>
public static string RefineListDlgProtein_OkDialog_The_following_proteins_are_not_in_the_document_ {
get {
return ResourceManager.GetString("RefineListDlgProtein_OkDialog_The_following_proteins_are_not_in_the_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The protein '{0}' is not in the document. Do you want to continue?.
/// </summary>
public static string RefineListDlgProtein_OkDialog_The_protein___0___is_not_in_the_document__Do_you_want_to_continue_ {
get {
return ResourceManager.GetString("RefineListDlgProtein_OkDialog_The_protein___0___is_not_in_the_document__Do_you_wa" +
"nt_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Converted To Molecules.
/// </summary>
public static string RefinementSettings_ConvertToSmallMolecules_Converted_To_Small_Molecules {
get {
return ResourceManager.GetString("RefinementSettings_ConvertToSmallMolecules_Converted_To_Small_Molecules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document does not contain the given reference type..
/// </summary>
public static string RefinementSettings_GetLabelIndex_The_document_does_not_contain_the_given_reference_type_ {
get {
return ResourceManager.GetString("RefinementSettings_GetLabelIndex_The_document_does_not_contain_the_given_referenc" +
"e_type_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document does not have a global standard to normalize by..
/// </summary>
public static string RefinementSettings_Refine_The_document_does_not_have_a_global_standard_to_normalize_by_ {
get {
return ResourceManager.GetString("RefinementSettings_Refine_The_document_does_not_have_a_global_standard_to_normali" +
"ze_by_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must contain at least 2 replicates to refine based on consistency..
/// </summary>
public static string RefinementSettings_Refine_The_document_must_contain_at_least_2_replicates_to_refine_based_on_consistency_ {
get {
return ResourceManager.GetString("RefinementSettings_Refine_The_document_must_contain_at_least_2_replicates_to_refi" +
"ne_based_on_consistency_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to intercept.
/// </summary>
public static string Regression_intercept {
get {
return ResourceManager.GetString("Regression_intercept", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to slope.
/// </summary>
public static string Regression_slope {
get {
return ResourceManager.GetString("Regression_slope", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Bilinear.
/// </summary>
public static string RegressionFit_BILINEAR_Bilinear {
get {
return ResourceManager.GetString("RegressionFit_BILINEAR_Bilinear", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} (at {1} points minimum).
/// </summary>
public static string RegressionGraphPane_RegressionGraphPane__0___at__1__points_minimum_ {
get {
return ResourceManager.GetString("RegressionGraphPane_RegressionGraphPane__0___at__1__points_minimum_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Current.
/// </summary>
public static string RegressionGraphPane_RegressionGraphPane_Current {
get {
return ResourceManager.GetString("RegressionGraphPane_RegressionGraphPane_Current", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing.
/// </summary>
public static string RegressionGraphPane_RegressionGraphPane_Missing {
get {
return ResourceManager.GetString("RegressionGraphPane_RegressionGraphPane_Missing", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Outliers.
/// </summary>
public static string RegressionGraphPane_RegressionGraphPane_Outliers {
get {
return ResourceManager.GetString("RegressionGraphPane_RegressionGraphPane_Outliers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Regression.
/// </summary>
public static string RegressionGraphPane_RegressionGraphPane_Regression {
get {
return ResourceManager.GetString("RegressionGraphPane_RegressionGraphPane_Regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Values.
/// </summary>
public static string RegressionGraphPane_RegressionGraphPane_Values {
get {
return ResourceManager.GetString("RegressionGraphPane_RegressionGraphPane_Values", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fixed points (linear).
/// </summary>
public static string RegressionOption_All_Fixed_points__linear_ {
get {
return ResourceManager.GetString("RegressionOption_All_Fixed_points__linear_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fixed points (logarithmic).
/// </summary>
public static string RegressionOption_All_Fixed_points__logarithmic_ {
get {
return ResourceManager.GetString("RegressionOption_All_Fixed_points__logarithmic_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Score.
/// </summary>
public static string RegressionUnconversion_CalculatorScoreFormat {
get {
return ResourceManager.GetString("RegressionUnconversion_CalculatorScoreFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Score ({1}).
/// </summary>
public static string RegressionUnconversion_CalculatorScoreValueFormat {
get {
return ResourceManager.GetString("RegressionUnconversion_CalculatorScoreValueFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed attempting to reintegrate peaks..
/// </summary>
public static string ReintegrateDlg_OkDialog_Failed_attempting_to_reintegrate_peaks_ {
get {
return ResourceManager.GetString("ReintegrateDlg_OkDialog_Failed_attempting_to_reintegrate_peaks_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reintegrating.
/// </summary>
public static string ReintegrateDlg_OkDialog_Reintegrating {
get {
return ResourceManager.GetString("ReintegrateDlg_OkDialog_Reintegrating", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The current peak scoring model is incompatible with one or more peptides in the document. Please train a new model..
/// </summary>
public static string ReintegrateDlg_OkDialog_The_current_peak_scoring_model_is_incompatible_with_one_or_more_peptides_in_the_document___Please_train_a_new_model_ {
get {
return ResourceManager.GetString("ReintegrateDlg_OkDialog_The_current_peak_scoring_model_is_incompatible_with_one_o" +
"r_more_peptides_in_the_document___Please_train_a_new_model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must train and select a model in order to reintegrate peaks..
/// </summary>
public static string ReintegrateDlg_OkDialog_You_must_train_and_select_a_model_in_order_to_reintegrate_peaks_ {
get {
return ResourceManager.GetString("ReintegrateDlg_OkDialog_You_must_train_and_select_a_model_in_order_to_reintegrate" +
"_peaks_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Matching.
/// </summary>
public static string RelativeRTExtension_LOCALIZED_VALUES_Matching {
get {
return ResourceManager.GetString("RelativeRTExtension_LOCALIZED_VALUES_Matching", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overlapping.
/// </summary>
public static string RelativeRTExtension_LOCALIZED_VALUES_Overlapping {
get {
return ResourceManager.GetString("RelativeRTExtension_LOCALIZED_VALUES_Overlapping", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Preceding.
/// </summary>
public static string RelativeRTExtension_LOCALIZED_VALUES_Preceding {
get {
return ResourceManager.GetString("RelativeRTExtension_LOCALIZED_VALUES_Preceding", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown.
/// </summary>
public static string RelativeRTExtension_LOCALIZED_VALUES_Unknown {
get {
return ResourceManager.GetString("RelativeRTExtension_LOCALIZED_VALUES_Unknown", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remote Accounts.
/// </summary>
public static string RemoteAccountList_Label_Remote_Accounts {
get {
return ResourceManager.GetString("RemoteAccountList_Label_Remote_Accounts", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Remote Accounts.
/// </summary>
public static string RemoteAccountList_Title_Edit_Remote_Accounts {
get {
return ResourceManager.GetString("RemoteAccountList_Title_Edit_Remote_Accounts", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There was an error communicating with the server: .
/// </summary>
public static string RemoteSession_FetchContents_There_was_an_error_communicating_with_the_server__ {
get {
return ResourceManager.GetString("RemoteSession_FetchContents_There_was_an_error_communicating_with_the_server__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No peaks are selected.
/// </summary>
public static string RemovePeaksAction_RemovePeaks_No_peaks_are_selected {
get {
return ResourceManager.GetString("RemovePeaksAction_RemovePeaks_No_peaks_are_selected", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove peaks.
/// </summary>
public static string RemovePeaksAction_RemovePeaks_Remove_peaks {
get {
return ResourceManager.GetString("RemovePeaksAction_RemovePeaks_Remove_peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Removing Peaks.
/// </summary>
public static string RemovePeaksAction_RemovePeaks_Removing_Peaks {
get {
return ResourceManager.GetString("RemovePeaksAction_RemovePeaks_Removing_Peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to remove these {0} peaks from {1} molecules?.
/// </summary>
public static string RemovePeptides_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__peaks_from__1__molecules_ {
get {
return ResourceManager.GetString("RemovePeptides_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__" +
"peaks_from__1__molecules_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to remove these {0} peaks from {1} peptides?.
/// </summary>
public static string RemovePeptides_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__peaks_from__1__peptides_ {
get {
return ResourceManager.GetString("RemovePeptides_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__" +
"peaks_from__1__peptides_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to remove these {0} peaks from one molecule?.
/// </summary>
public static string RemovePeptides_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__peaks_from_one_molecule_ {
get {
return ResourceManager.GetString("RemovePeptides_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__" +
"peaks_from_one_molecule_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to remove these {0} peaks from one peptide?.
/// </summary>
public static string RemovePeptides_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__peaks_from_one_peptide_ {
get {
return ResourceManager.GetString("RemovePeptides_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__" +
"peaks_from_one_peptide_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to remove this molecule peak?.
/// </summary>
public static string RemovePeptides_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_this_molecule_peak_ {
get {
return ResourceManager.GetString("RemovePeptides_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_this_molec" +
"ule_peak_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to remove this peptide peak?.
/// </summary>
public static string RemovePeptides_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_this_peptide_peak_ {
get {
return ResourceManager.GetString("RemovePeptides_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_this_pepti" +
"de_peak_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove Molecule Peaks....
/// </summary>
public static string RemovePeptides_MenuItemText_Remove_Molecule_Peaks___ {
get {
return ResourceManager.GetString("RemovePeptides_MenuItemText_Remove_Molecule_Peaks___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove Peptide Peaks....
/// </summary>
public static string RemovePeptides_MenuItemText_Remove_Peptide_Peaks___ {
get {
return ResourceManager.GetString("RemovePeptides_MenuItemText_Remove_Peptide_Peaks___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to remove these {0} peaks from {1} precursors?.
/// </summary>
public static string RemovePrecursors_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__peaks_from__1__precursors_ {
get {
return ResourceManager.GetString("RemovePrecursors_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0" +
"__peaks_from__1__precursors_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to remove these {0} peaks from one precursor?.
/// </summary>
public static string RemovePrecursors_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__peaks_from_one_precursor_ {
get {
return ResourceManager.GetString("RemovePrecursors_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0" +
"__peaks_from_one_precursor_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to remove this precursor peak?.
/// </summary>
public static string RemovePrecursors_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_this_precursor_peak_ {
get {
return ResourceManager.GetString("RemovePrecursors_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_this_pre" +
"cursor_peak_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove Precursor Peaks....
/// </summary>
public static string RemovePrecursors_MenuItemText_Remove_Precursor_Peaks___ {
get {
return ResourceManager.GetString("RemovePrecursors_MenuItemText_Remove_Precursor_Peaks___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to remove these {0} peaks from {1} transitions?.
/// </summary>
public static string RemoveTransitions_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__peaks_from__1__transitions_ {
get {
return ResourceManager.GetString("RemoveTransitions_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__" +
"0__peaks_from__1__transitions_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to remove these {0} peaks from one transition?.
/// </summary>
public static string RemoveTransitions_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__0__peaks_from_one_transition_ {
get {
return ResourceManager.GetString("RemoveTransitions_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_these__" +
"0__peaks_from_one_transition_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to remove this transition peak?.
/// </summary>
public static string RemoveTransitions_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_this_transition_peak_ {
get {
return ResourceManager.GetString("RemoveTransitions_GetConfirmRemoveMessage_Are_you_sure_you_want_to_remove_this_tr" +
"ansition_peak_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove Transition Peaks....
/// </summary>
public static string RemoveTransitions_MenuItemText_Remove_Transition_Peaks___ {
get {
return ResourceManager.GetString("RemoveTransitions_MenuItemText_Remove_Transition_Peaks___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add FASTA File.
/// </summary>
public static string RenameProteinsDlg_btnFASTA_Click_Add_FASTA_File {
get {
return ResourceManager.GetString("RenameProteinsDlg_btnFASTA_Click_Add_FASTA_File", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} is not a current protein.
/// </summary>
public static string RenameProteinsDlg_OkDialog__0__is_not_a_current_protein {
get {
return ResourceManager.GetString("RenameProteinsDlg_OkDialog__0__is_not_a_current_protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot rename {0} more than once. Please remove either {1} or {2}.
/// </summary>
public static string RenameProteinsDlg_OkDialog_Cannot_rename__0__more_than_once__Please_remove_either__1__or__2__ {
get {
return ResourceManager.GetString("RenameProteinsDlg_OkDialog_Cannot_rename__0__more_than_once__Please_remove_either" +
"__1__or__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit name {0}.
/// </summary>
public static string RenameProteinsDlg_OkDialog_Edit_name__0__ {
get {
return ResourceManager.GetString("RenameProteinsDlg_OkDialog_Edit_name__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No protein metadata available.
/// </summary>
public static string RenameProteinsDlg_UseAccessionOrPreferredNameorGene_No_protein_metadata_available {
get {
return ResourceManager.GetString("RenameProteinsDlg_UseAccessionOrPreferredNameorGene_No_protein_metadata_available" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed reading the file {0}. {1}.
/// </summary>
public static string RenameProteinsDlg_UseFastaFile_Failed_reading_the_file__0__1__ {
get {
return ResourceManager.GetString("RenameProteinsDlg_UseFastaFile_Failed_reading_the_file__0__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No protein sequence matches found between the current document and the FASTA file {0}.
/// </summary>
public static string RenameProteinsDlg_UseFastaFile_No_protein_sequence_matches_found_between_the_current_document_and_the_FASTA_file__0_ {
get {
return ResourceManager.GetString("RenameProteinsDlg_UseFastaFile_No_protein_sequence_matches_found_between_the_curr" +
"ent_document_and_the_FASTA_file__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document contains a naming conflict. The name {0} is currently used by multiple protein sequences..
/// </summary>
public static string RenameProteinsDlg_UseFastaFile_The_document_contains_a_naming_conflict_The_name__0__is_currently_used_by_multiple_protein_sequences {
get {
return ResourceManager.GetString("RenameProteinsDlg_UseFastaFile_The_document_contains_a_naming_conflict_The_name__" +
"0__is_currently_used_by_multiple_protein_sequences", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please use a different name..
/// </summary>
public static string RenameResultDlg_OkDialog_Please_use_a_different_name {
get {
return ResourceManager.GetString("RenameResultDlg_OkDialog_Please_use_a_different_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The name {0} is already in use..
/// </summary>
public static string RenameResultDlg_ReplicateName_The_name__0__is_already_in_use {
get {
return ResourceManager.GetString("RenameResultDlg_ReplicateName_The_name__0__is_already_in_use", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Replicate {
get {
object obj = ResourceManager.GetObject("Replicate", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to There is already a replicate named '{0}'..
/// </summary>
public static string Replicate_Name_There_is_already_a_replicate_named___0___ {
get {
return ResourceManager.GetString("Replicate_Name_There_is_already_a_replicate_named___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicate.
/// </summary>
public static string ReplicateGroupOp_ReplicateAxisTitle {
get {
return ResourceManager.GetString("ReplicateGroupOp_ReplicateAxisTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error report will be posted..
/// </summary>
public static string ReportErrorDlg_ReportErrorDlg_An_error_report_will_be_posted {
get {
return ResourceManager.GetString("ReportErrorDlg_ReportErrorDlg_An_error_report_will_be_posted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An unexpected error has occurred, as shown below..
/// </summary>
public static string ReportErrorDlg_ReportErrorDlg_An_unexpected_error_has_occurred_as_shown_below {
get {
return ResourceManager.GetString("ReportErrorDlg_ReportErrorDlg_An_unexpected_error_has_occurred_as_shown_below", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Close.
/// </summary>
public static string ReportErrorDlg_ReportErrorDlg_Close {
get {
return ResourceManager.GetString("ReportErrorDlg_ReportErrorDlg_Close", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Report the error to help improve Skyline..
/// </summary>
public static string ReportShutdownDlg_ReportShutdownDlg_Report_the_error_to_help_improve_Skyline_ {
get {
return ResourceManager.GetString("ReportShutdownDlg_ReportShutdownDlg_Report_the_error_to_help_improve_Skyline_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline had an unexpected error the last time you ran it..
/// </summary>
public static string ReportShutdownDlg_ReportShutdownDlg_Skyline_had_an_unexpected_error_the_last_time_you_ran_it_ {
get {
return ResourceManager.GetString("ReportShutdownDlg_ReportShutdownDlg_Skyline_had_an_unexpected_error_the_last_time" +
"_you_ran_it_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected Shutdown.
/// </summary>
public static string ReportShutdownDlg_ReportShutdownDlg_Unexpected_Shutdown {
get {
return ResourceManager.GetString("ReportShutdownDlg_ReportShutdownDlg_Unexpected_Shutdown", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The name '{0}' is not a valid table name..
/// </summary>
public static string ReportSpec_GetTable_The_name__0__is_not_a_valid_table_name {
get {
return ResourceManager.GetString("ReportSpec_GetTable_The_name__0__is_not_a_valid_table_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to find the table for the column {0}..
/// </summary>
public static string ReportSpec_ReadColumns_Failed_to_find_the_table_for_the_column__0__ {
get {
return ResourceManager.GetString("ReportSpec_ReadColumns_Failed_to_find_the_table_for_the_column__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing table name..
/// </summary>
public static string ReportSpec_ReadXml_Missing_table_name {
get {
return ResourceManager.GetString("ReportSpec_ReadXml_Missing_table_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The name '{0}' is not a valid table name..
/// </summary>
public static string ReportSpec_ReadXml_The_name__0__is_not_a_valid_table_name {
get {
return ResourceManager.GetString("ReportSpec_ReadXml_The_name__0__is_not_a_valid_table_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting {0} report.
/// </summary>
public static string ReportSpec_ReportToCsvString_Exporting__0__report {
get {
return ResourceManager.GetString("ReportSpec_ReportToCsvString_Exporting__0__report", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An unexpected error occurred while analyzing the current document..
/// </summary>
public static string ReportSpecList_EditItem_An_unexpected_error_occurred_while_analyzing_the_current_document {
get {
return ResourceManager.GetString("ReportSpecList_EditItem_An_unexpected_error_occurred_while_analyzing_the_current_" +
"document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak Boundaries.
/// </summary>
public static string ReportSpecList_GetDefaults_Peak_Boundaries {
get {
return ResourceManager.GetString("ReportSpecList_GetDefaults_Peak_Boundaries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide Ratio Results.
/// </summary>
public static string ReportSpecList_GetDefaults_Peptide_Ratio_Results {
get {
return ResourceManager.GetString("ReportSpecList_GetDefaults_Peptide_Ratio_Results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide RT Results.
/// </summary>
public static string ReportSpecList_GetDefaults_Peptide_RT_Results {
get {
return ResourceManager.GetString("ReportSpecList_GetDefaults_Peptide_RT_Results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition Results.
/// </summary>
public static string ReportSpecList_GetDefaults_Transition_Results {
get {
return ResourceManager.GetString("ReportSpecList_GetDefaults_Transition_Results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Report:.
/// </summary>
public static string ReportSpecList_Label_Report {
get {
return ResourceManager.GetString("ReportSpecList_Label_Report", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Reports.
/// </summary>
public static string ReportSpecList_Title_Edit_Reports {
get {
return ResourceManager.GetString("ReportSpecList_Title_Edit_Reports", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All results must be completely imported before they can be re-scored..
/// </summary>
public static string RescoreResultsDlg_Rescore_All_results_must_be_completely_imported_before_they_can_be_re_scored_ {
get {
return ResourceManager.GetString("RescoreResultsDlg_Rescore_All_results_must_be_completely_imported_before_they_can" +
"_be_re_scored_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There are not results in this document.
/// </summary>
public static string RescoreResultsDlg_Rescore_There_are_not_results_in_this_document {
get {
return ResourceManager.GetString("RescoreResultsDlg_Rescore_There_are_not_results_in_this_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to In certain cases, you may want to have Skyline re-calculate peaks and re-score them based on the existing chromatogram data. Chromatograms will not be re-imported from raw data files, but peak integration information may change..
/// </summary>
public static string RescoreResultsDlg_RescoreResultsDlg_In_certain_cases__you_may_want_to_have_Skyline_re_calculate_peaks_and_re_score_them_based_on_the_existing_chromatogram_data___Chromatograms_will_not_be_re_imported_from_raw_data_files__but_peak_integration_information_may_change_ {
get {
return ResourceManager.GetString(@"RescoreResultsDlg_RescoreResultsDlg_In_certain_cases__you_may_want_to_have_Skyline_re_calculate_peaks_and_re_score_them_based_on_the_existing_chromatogram_data___Chromatograms_will_not_be_re_imported_from_raw_data_files__but_peak_integration_information_may_change_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide Quantification.
/// </summary>
public static string Resources_ReportSpecList_GetDefaults_Peptide_Quantification {
get {
return ResourceManager.GetString("Resources.ReportSpecList_GetDefaults_Peptide_Quantification", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to DocNode peak info found for file with no match in document results..
/// </summary>
public static string Results_Validate_DocNode_peak_info_found_for_file_with_no_match_in_document_results {
get {
return ResourceManager.GetString("Results_Validate_DocNode_peak_info_found_for_file_with_no_match_in_document_resul" +
"ts", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to DocNode results count {0} does not match document results count {1}..
/// </summary>
public static string Results_Validate_DocNode_results_count__0__does_not_match_document_results_count__1__ {
get {
return ResourceManager.GetString("Results_Validate_DocNode_results_count__0__does_not_match_document_results_count_" +
"_1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Element not found.
/// </summary>
public static string ResultsGrid_ChangeChromInfo_Element_not_found {
get {
return ResourceManager.GetString("ResultsGrid_ChangeChromInfo_Element_not_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Acquired Time.
/// </summary>
public static string ResultsGrid_ResultsGrid_Acquired_Time {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Acquired_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Area.
/// </summary>
public static string ResultsGrid_ResultsGrid_Area {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Area", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Area Ratio.
/// </summary>
public static string ResultsGrid_ResultsGrid_Area_Ratio {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Area_Ratio", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Average Mass Error PPM.
/// </summary>
public static string ResultsGrid_ResultsGrid_Average_Mass_Error_PPM {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Average_Mass_Error_PPM", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Background.
/// </summary>
public static string ResultsGrid_ResultsGrid_Background {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Background", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Best Retention Time.
/// </summary>
public static string ResultsGrid_ResultsGrid_Best_Retention_Time {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Best_Retention_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit note.
/// </summary>
public static string ResultsGrid_ResultsGrid_CellEndEdit_Edit_note {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_CellEndEdit_Edit_note", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Count Truncated.
/// </summary>
public static string ResultsGrid_ResultsGrid_Count_Truncated {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Count_Truncated", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to End Time.
/// </summary>
public static string ResultsGrid_ResultsGrid_End_Time {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_End_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File Name.
/// </summary>
public static string ResultsGrid_ResultsGrid_File_Name {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_File_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fwhm.
/// </summary>
public static string ResultsGrid_ResultsGrid_Fwhm {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Fwhm", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Height.
/// </summary>
public static string ResultsGrid_ResultsGrid_Height {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Height", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Identified.
/// </summary>
public static string ResultsGrid_ResultsGrid_Identified {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Identified", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isotope Dot Product.
/// </summary>
public static string ResultsGrid_ResultsGrid_Isotope_Dot_Product {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Isotope_Dot_Product", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library Dot Product.
/// </summary>
public static string ResultsGrid_ResultsGrid_Library_Dot_Product {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Library_Dot_Product", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mass Error PPM.
/// </summary>
public static string ResultsGrid_ResultsGrid_Mass_Error_PPM {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Mass_Error_PPM", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Max End Time.
/// </summary>
public static string ResultsGrid_ResultsGrid_Max_End_Time {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Max_End_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Max Fwhm.
/// </summary>
public static string ResultsGrid_ResultsGrid_Max_Fwhm {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Max_Fwhm", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Max Height.
/// </summary>
public static string ResultsGrid_ResultsGrid_Max_Height {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Max_Height", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Min Start Time.
/// </summary>
public static string ResultsGrid_ResultsGrid_Min_Start_Time {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Min_Start_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modified Time.
/// </summary>
public static string ResultsGrid_ResultsGrid_Modified_Time {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Modified_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Opt Collision Energy.
/// </summary>
public static string ResultsGrid_ResultsGrid_Opt_Collision_Energy {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Opt_Collision_Energy", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Opt Compensation Voltage.
/// </summary>
public static string ResultsGrid_ResultsGrid_Opt_Compensation_Voltage {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Opt_Compensation_Voltage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Opt Declustering Potential.
/// </summary>
public static string ResultsGrid_ResultsGrid_Opt_Declustering_Potential {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Opt_Declustering_Potential", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Opt Step.
/// </summary>
public static string ResultsGrid_ResultsGrid_Opt_Step {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Opt_Step", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak Rank.
/// </summary>
public static string ResultsGrid_ResultsGrid_Peak_Rank {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Peak_Rank", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide Peak Found Ratio.
/// </summary>
public static string ResultsGrid_ResultsGrid_Peptide_Peak_Found_Ratio {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Peptide_Peak_Found_Ratio", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide Retention Time.
/// </summary>
public static string ResultsGrid_ResultsGrid_Peptide_Retention_Time {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Peptide_Retention_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor Peak Found Ratio.
/// </summary>
public static string ResultsGrid_ResultsGrid_Precursor_Peak_Found_Ratio {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Precursor_Peak_Found_Ratio", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor Replicate Note.
/// </summary>
public static string ResultsGrid_ResultsGrid_Precursor_Replicate_Note {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Precursor_Replicate_Note", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ratio Dot Product.
/// </summary>
public static string ResultsGrid_ResultsGrid_Ratio_Dot_Product {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Ratio_Dot_Product", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ratio to Global Standards.
/// </summary>
public static string ResultsGrid_ResultsGrid_Ratio_to_Global_Standards {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Ratio_to_Global_Standards", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ratio To Standard.
/// </summary>
public static string ResultsGrid_ResultsGrid_Ratio_To_Standard {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Ratio_To_Standard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ratio To Standard Dot Product.
/// </summary>
public static string ResultsGrid_ResultsGrid_Ratio_To_Standard_Dot_Product {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Ratio_To_Standard_Dot_Product", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicate Name.
/// </summary>
public static string ResultsGrid_ResultsGrid_Replicate_Name {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Replicate_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention Time.
/// </summary>
public static string ResultsGrid_ResultsGrid_Retention_Time {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Retention_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sample Name.
/// </summary>
public static string ResultsGrid_ResultsGrid_Sample_Name {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Sample_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Start Time.
/// </summary>
public static string ResultsGrid_ResultsGrid_Start_Time {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Start_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Total Area.
/// </summary>
public static string ResultsGrid_ResultsGrid_Total_Area {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Total_Area", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Total Area Ratio.
/// </summary>
public static string ResultsGrid_ResultsGrid_Total_Area_Ratio {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Total_Area_Ratio", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Total Background.
/// </summary>
public static string ResultsGrid_ResultsGrid_Total_Background {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Total_Background", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition Replicate Note.
/// </summary>
public static string ResultsGrid_ResultsGrid_Transition_Replicate_Note {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Transition_Replicate_Note", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Truncated.
/// </summary>
public static string ResultsGrid_ResultsGrid_Truncated {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_Truncated", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User Set.
/// </summary>
public static string ResultsGrid_ResultsGrid_User_Set {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_User_Set", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User Set Total.
/// </summary>
public static string ResultsGrid_ResultsGrid_User_Set_Total {
get {
return ResourceManager.GetString("ResultsGrid_ResultsGrid_User_Set_Total", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The retention time calculator {0} is not valid..
/// </summary>
public static string RetentionScoreCalculator_Validate_The_retention_time_calculator__0__is_not_valid {
get {
return ResourceManager.GetString("RetentionScoreCalculator_Validate_The_retention_time_calculator__0__is_not_valid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Retention Time Regression:.
/// </summary>
public static string RetentionTimeList_Label_Retention_Time_Regression {
get {
return ResourceManager.GetString("RetentionTimeList_Label_Retention_Time_Regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Retention Time Regressions.
/// </summary>
public static string RetentionTimeList_Title_Edit_Retention_Time_Regressions {
get {
return ResourceManager.GetString("RetentionTimeList_Title_Edit_Retention_Time_Regressions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Finding threshold.
/// </summary>
public static string RetentionTimeRegression_FindThreshold_Finding_threshold {
get {
return ResourceManager.GetString("RetentionTimeRegression_FindThreshold_Finding_threshold", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Recalculating regression.
/// </summary>
public static string RetentionTimeRegression_RecalcRegression_Recalculating_regression {
get {
return ResourceManager.GetString("RetentionTimeRegression_RecalcRegression_Recalculating_regression", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Slope and intercept must both have values or both not have values.
/// </summary>
public static string RetentionTimeRegression_RetentionTimeRegression_Slope_and_intercept_must_both_have_values_or_both_not_have_values {
get {
return ResourceManager.GetString("RetentionTimeRegression_RetentionTimeRegression_Slope_and_intercept_must_both_hav" +
"e_values_or_both_not_have_values", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid negative retention time window {0}..
/// </summary>
public static string RetentionTimeRegression_Validate_Invalid_negative_retention_time_window__0__ {
get {
return ResourceManager.GetString("RetentionTimeRegression_Validate_Invalid_negative_retention_time_window__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention time regression must specify a sequence to score calculator..
/// </summary>
public static string RetentionTimeRegression_Validate_Retention_time_regression_must_specify_a_sequence_to_score_calculator {
get {
return ResourceManager.GetString("RetentionTimeRegression_Validate_Retention_time_regression_must_specify_a_sequenc" +
"e_to_score_calculator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check your network connection or contact the tool provider for installation support..
/// </summary>
public static string RInstaller_DownloadPackages_Check_your_network_connection_or_contact_the_tool_provider_for_installation_support_ {
get {
return ResourceManager.GetString("RInstaller_DownloadPackages_Check_your_network_connection_or_contact_the_tool_pro" +
"vider_for_installation_support_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Download failed..
/// </summary>
public static string RInstaller_DownloadR_Download_failed_ {
get {
return ResourceManager.GetString("RInstaller_DownloadR_Download_failed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading packages.
/// </summary>
public static string RInstaller_GetPackages_Downloading_packages {
get {
return ResourceManager.GetString("RInstaller_GetPackages_Downloading_packages", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Installing Packages.
/// </summary>
public static string RInstaller_GetPAckages_Installing_Packages {
get {
return ResourceManager.GetString("RInstaller_GetPAckages_Installing_Packages", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Package installation complete..
/// </summary>
public static string RInstaller_GetPackages_Package_installation_complete_ {
get {
return ResourceManager.GetString("RInstaller_GetPackages_Package_installation_complete_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Installing R.
/// </summary>
public static string RInstaller_GetR_Installing_R {
get {
return ResourceManager.GetString("RInstaller_GetR_Installing_R", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to R installation complete..
/// </summary>
public static string RInstaller_GetR_R_installation_complete_ {
get {
return ResourceManager.GetString("RInstaller_GetR_R_installation_complete_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Download Canceled.
/// </summary>
public static string RInstaller_InstallPackages_Download_Canceled {
get {
return ResourceManager.GetString("RInstaller_InstallPackages_Download_Canceled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Failed to connect to the website {0}.
/// </summary>
public static string RInstaller_InstallPackages_Error__Failed_to_connect_to_the_website__0_ {
get {
return ResourceManager.GetString("RInstaller_InstallPackages_Error__Failed_to_connect_to_the_website__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: No internet connection..
/// </summary>
public static string RInstaller_InstallPackages_Error__No_internet_connection_ {
get {
return ResourceManager.GetString("RInstaller_InstallPackages_Error__No_internet_connection_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: Package installation did not complete. Output logged to the Immediate Window..
/// </summary>
public static string RInstaller_InstallPackages_Error__Package_installation_did_not_complete__Output_logged_to_the_Immediate_Window_ {
get {
return ResourceManager.GetString("RInstaller_InstallPackages_Error__Package_installation_did_not_complete__Output_l" +
"ogged_to_the_Immediate_Window_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error Installing Packages.
/// </summary>
public static string RInstaller_InstallPackages_Error_Installing_Packages {
get {
return ResourceManager.GetString("RInstaller_InstallPackages_Error_Installing_Packages", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Installing R packages requires an internet connection. Please check your connection and try again.
/// </summary>
public static string RInstaller_InstallPackages_Installing_R_packages_requires_an_internet_connection__Please_check_your_connection_and_try_again {
get {
return ResourceManager.GetString("RInstaller_InstallPackages_Installing_R_packages_requires_an_internet_connection_" +
"_Please_check_your_connection_and_try_again", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Output logged to the Immediate Window..
/// </summary>
public static string RInstaller_InstallPackages_Output_logged_to_the_Immediate_Window_ {
get {
return ResourceManager.GetString("RInstaller_InstallPackages_Output_logged_to_the_Immediate_Window_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Package installation failed. Error log output in immediate window..
/// </summary>
public static string RInstaller_InstallPackages_Package_installation_failed__Error_log_output_in_immediate_window_ {
get {
return ResourceManager.GetString("RInstaller_InstallPackages_Package_installation_failed__Error_log_output_in_immed" +
"iate_window_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following packages failed to install:.
/// </summary>
public static string RInstaller_InstallPackages_The_following_packages_failed_to_install_ {
get {
return ResourceManager.GetString("RInstaller_InstallPackages_The_following_packages_failed_to_install_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The package {0} failed to install:.
/// </summary>
public static string RInstaller_InstallPackages_The_package__0__failed_to_install_ {
get {
return ResourceManager.GetString("RInstaller_InstallPackages_The_package__0__failed_to_install_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown Error installing packages. Output logged to the Immediate Window..
/// </summary>
public static string RInstaller_InstallPackages_Unknown_Error_installing_packages__Output_logged_to_the_Immediate_Window_ {
get {
return ResourceManager.GetString("RInstaller_InstallPackages_Unknown_Error_installing_packages__Output_logged_to_th" +
"e_Immediate_Window_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown error installing packages. Tool Installation Failed..
/// </summary>
public static string RInstaller_InstallPackages_Unknown_error_installing_packages__Tool_Installation_Failed_ {
get {
return ResourceManager.GetString("RInstaller_InstallPackages_Unknown_error_installing_packages__Tool_Installation_F" +
"ailed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading R.
/// </summary>
public static string RInstaller_InstallR_Downloading_R {
get {
return ResourceManager.GetString("RInstaller_InstallR_Downloading_R", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to R installation was not completed. Cancelling tool installation..
/// </summary>
public static string RInstaller_InstallR_R_installation_was_not_completed__Cancelling_tool_installation_ {
get {
return ResourceManager.GetString("RInstaller_InstallR_R_installation_was_not_completed__Cancelling_tool_installatio" +
"n_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires the use of R {0}. Click Install to begin the installation process..
/// </summary>
public static string RInstaller_RInstaller_Load_This_tool_requires_the_use_of_R__0___Click_Install_to_begin_the_installation_process_ {
get {
return ResourceManager.GetString("RInstaller_RInstaller_Load_This_tool_requires_the_use_of_R__0___Click_Install_to_" +
"begin_the_installation_process_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires the use of R {0} and the following packages..
/// </summary>
public static string RInstaller_RInstaller_Load_This_tool_requires_the_use_of_R__0__and_the_following_packages_ {
get {
return ResourceManager.GetString("RInstaller_RInstaller_Load_This_tool_requires_the_use_of_R__0__and_the_following_" +
"packages_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This Tool requires the use of the following R Packages..
/// </summary>
public static string RInstaller_RInstaller_Load_This_Tool_requires_the_use_of_the_following_R_Packages_ {
get {
return ResourceManager.GetString("RInstaller_RInstaller_Load_This_Tool_requires_the_use_of_the_following_R_Packages" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} aligned to {1}.
/// </summary>
public static string RtAlignment_AxisTitleAlignedTo {
get {
return ResourceManager.GetString("RtAlignment_AxisTitleAlignedTo", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed setting data to clipboard..
/// </summary>
public static string RTDetails_gridStatistics_KeyDown_Failed_setting_data_to_clipboard {
get {
return ResourceManager.GetString("RTDetails_gridStatistics_KeyDown_Failed_setting_data_to_clipboard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to FWB Time.
/// </summary>
public static string RtGraphValue_FWB_Time {
get {
return ResourceManager.GetString("RtGraphValue_FWB_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to FWHM Time.
/// </summary>
public static string RtGraphValue_FWHM_Time {
get {
return ResourceManager.GetString("RtGraphValue_FWHM_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention Time.
/// </summary>
public static string RtGraphValue_Retention_Time {
get {
return ResourceManager.GetString("RtGraphValue_Retention_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measured Time.
/// </summary>
public static string RTLinearRegressionGraphPane_RTLinearRegressionGraphPane_Measured_Time {
get {
return ResourceManager.GetString("RTLinearRegressionGraphPane_RTLinearRegressionGraphPane_Measured_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Score.
/// </summary>
public static string RTLinearRegressionGraphPane_RTLinearRegressionGraphPane_Score {
get {
return ResourceManager.GetString("RTLinearRegressionGraphPane_RTLinearRegressionGraphPane_Score", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculating....
/// </summary>
public static string RTLinearRegressionGraphPane_UpdateGraph_Calculating___ {
get {
return ResourceManager.GetString("RTLinearRegressionGraphPane_UpdateGraph_Calculating___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention Time.
/// </summary>
public static string RTPeptideGraphPane_UpdateAxes_Retention_Time {
get {
return ResourceManager.GetString("RTPeptideGraphPane_UpdateAxes_Retention_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Time.
/// </summary>
public static string RTPeptideGraphPane_UpdateAxes_Time {
get {
return ResourceManager.GetString("RTPeptideGraphPane_UpdateAxes_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measured Time.
/// </summary>
public static string RTReplicateGraphPane_RTReplicateGraphPane_Measured_Time {
get {
return ResourceManager.GetString("RTReplicateGraphPane_RTReplicateGraphPane_Measured_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No results available.
/// </summary>
public static string RTReplicateGraphPane_UpdateGraph_No_results_available {
get {
return ResourceManager.GetString("RTReplicateGraphPane_UpdateGraph_No_results_available", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Select a peptide to see the retention time graph.
/// </summary>
public static string RTReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_retention_time_graph {
get {
return ResourceManager.GetString("RTReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_retention_time_graph" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Step {0}.
/// </summary>
public static string RTReplicateGraphPane_UpdateGraph_Step__0__ {
get {
return ResourceManager.GetString("RTReplicateGraphPane_UpdateGraph_Step__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} Minute Window.
/// </summary>
public static string RTScheduleGraphPane_AddCurve__0__Minute_Window {
get {
return ResourceManager.GetString("RTScheduleGraphPane_AddCurve__0__Minute_Window", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scheduled Time.
/// </summary>
public static string RTScheduleGraphPane_RTScheduleGraphPane_Scheduled_Time {
get {
return ResourceManager.GetString("RTScheduleGraphPane_RTScheduleGraphPane_Scheduled_Time", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Concurrent Accumulations.
/// </summary>
public static string RTScheduleGraphPane_UpdateGraph_Concurrent_Accumulations {
get {
return ResourceManager.GetString("RTScheduleGraphPane_UpdateGraph_Concurrent_Accumulations", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Concurrent frames.
/// </summary>
public static string RTScheduleGraphPane_UpdateGraph_Concurrent_frames {
get {
return ResourceManager.GetString("RTScheduleGraphPane_UpdateGraph_Concurrent_frames", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Concurrent Precursors.
/// </summary>
public static string RTScheduleGraphPane_UpdateGraph_Concurrent_Precursors {
get {
return ResourceManager.GetString("RTScheduleGraphPane_UpdateGraph_Concurrent_Precursors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Concurrent Transitions.
/// </summary>
public static string RTScheduleGraphPane_UpdateGraph_Concurrent_Transitions {
get {
return ResourceManager.GetString("RTScheduleGraphPane_UpdateGraph_Concurrent_Transitions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Max sampling times (seconds).
/// </summary>
public static string RTScheduleGraphPane_UpdateGraph_Max_sampling_times {
get {
return ResourceManager.GetString("RTScheduleGraphPane_UpdateGraph_Max_sampling_times", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mean sampling times (seconds).
/// </summary>
public static string RTScheduleGraphPane_UpdateGraph_Mean_sampling_times {
get {
return ResourceManager.GetString("RTScheduleGraphPane_UpdateGraph_Mean_sampling_times", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Redundancy of targets.
/// </summary>
public static string RTScheduleGraphPane_UpdateGraph_Redundancy_of_targets {
get {
return ResourceManager.GetString("RTScheduleGraphPane_UpdateGraph_Redundancy_of_targets", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Rank of target.
/// </summary>
public static string RTScheduleGraphPane_UpdateGraph_Target {
get {
return ResourceManager.GetString("RTScheduleGraphPane_UpdateGraph_Target", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Targets per frame.
/// </summary>
public static string RTScheduleGraphPane_UpdateGraph_Targets_per_frame {
get {
return ResourceManager.GetString("RTScheduleGraphPane_UpdateGraph_Targets_per_frame", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The regression(s):.
/// </summary>
public static string RTScoreCalculatorList_AcceptList_The_regressions {
get {
return ResourceManager.GetString("RTScoreCalculatorList_AcceptList_The_regressions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to will be deleted because the calculators they depend on have changed. Do you want to continue?.
/// </summary>
public static string RTScoreCalculatorList_AcceptList_will_be_deleted_because_the_calculators_they_depend_on_have_changed_Do_you_want_to_continue {
get {
return ResourceManager.GetString("RTScoreCalculatorList_AcceptList_will_be_deleted_because_the_calculators_they_dep" +
"end_on_have_changed_Do_you_want_to_continue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Retention Time Calculators:.
/// </summary>
public static string RTScoreCalculatorList_Label_Retention_Time_Calculators {
get {
return ResourceManager.GetString("RTScoreCalculatorList_Label_Retention_Time_Calculators", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Retention Time Calculators.
/// </summary>
public static string RTScoreCalculatorList_Title_Edit_Retention_Time_Calculators {
get {
return ResourceManager.GetString("RTScoreCalculatorList_Title_Edit_Retention_Time_Calculators", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred applying the rule '{0}':.
/// </summary>
public static string RuleError_ToString_An_error_occurred_applying_the_rule___0___ {
get {
return ResourceManager.GetString("RuleError_ToString_An_error_occurred_applying_the_rule___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Save {
get {
object obj = ResourceManager.GetObject("Save", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to overwrite the existing settings?.
/// </summary>
public static string SaveSettingsDlg_OnClosing_Do_you_want_to_overwrite_the_existing_settings {
get {
return ResourceManager.GetString("SaveSettingsDlg_OnClosing_Do_you_want_to_overwrite_the_existing_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The name {0} already exists..
/// </summary>
public static string SaveSettingsDlg_OnClosing_The_name__0__already_exists {
get {
return ResourceManager.GetString("SaveSettingsDlg_OnClosing_The_name__0__already_exists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SavitzkyGolaySmoother: Invalid window size ({0}): argument must be positive and odd.
/// </summary>
public static string SavitzkyGolaySmoother_WindowSize_SavitzkyGolaySmoother__Invalid_window_size___0____argument_must_be_positive_and_odd {
get {
return ResourceManager.GetString("SavitzkyGolaySmoother_WindowSize_SavitzkyGolaySmoother__Invalid_window_size___0__" +
"__argument_must_be_positive_and_odd", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The data file {0} could not be found, either at its original location or in the document or document parent folder..
/// </summary>
public static string ScanProvider_GetScans_The_data_file__0__could_not_be_found__either_at_its_original_location_or_in_the_document_or_document_parent_folder_ {
get {
return ResourceManager.GetString("ScanProvider_GetScans_The_data_file__0__could_not_be_found__either_at_its_origina" +
"l_location_or_in_the_document_or_document_parent_folder_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The scan ID {0} was not found in the file {1}..
/// </summary>
public static string ScanProvider_GetScans_The_scan_ID__0__was_not_found_in_the_file__1__ {
get {
return ResourceManager.GetString("ScanProvider_GetScans_The_scan_ID__0__was_not_found_in_the_file__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Template file is not valid..
/// </summary>
public static string SchedulingGraphPropertyDlg_OkDialog_Template_file_is_not_valid_ {
get {
return ResourceManager.GetString("SchedulingGraphPropertyDlg_OkDialog_Template_file_is_not_valid_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The replicate {0} contains peptides without enough information to rank transitions for triggered acquisition..
/// </summary>
public static string SchedulingOptionsDlg_OkDialog_The_replicate__0__contains_peptides_without_enough_information_to_rank_transitions_for_triggered_acquisition_ {
get {
return ResourceManager.GetString("SchedulingOptionsDlg_OkDialog_The_replicate__0__contains_peptides_without_enough_" +
"information_to_rank_transitions_for_triggered_acquisition_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Using trends in scheduling requires at least {0} replicates..
/// </summary>
public static string SchedulingOptionsDlg_TrendsError_Using_trends_in_scheduling_requires_at_least__0__replicates {
get {
return ResourceManager.GetString("SchedulingOptionsDlg_TrendsError_Using_trends_in_scheduling_requires_at_least__0_" +
"_replicates", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Additional Settings.
/// </summary>
public static string SearchSettingsControl_Additional_Settings {
get {
return ResourceManager.GetString("SearchSettingsControl_Additional_Settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to save your current settings before switching?.
/// </summary>
public static string SelectSettingsHandler_ToolStripMenuItemClick_Do_you_want_to_save_your_current_settings_before_switching {
get {
return ResourceManager.GetString("SelectSettingsHandler_ToolStripMenuItemClick_Do_you_want_to_save_your_current_set" +
"tings_before_switching", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor isotope {0} is outside the isotope distribution {1} to {2}..
/// </summary>
public static string SequenceMassCalc_GetFragmentMass_Precursor_isotope__0__is_outside_the_isotope_distribution__1__to__2__ {
get {
return ResourceManager.GetString("SequenceMassCalc_GetFragmentMass_Precursor_isotope__0__is_outside_the_isotope_dis" +
"tribution__1__to__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No formula found for the amino acid '{0}'.
/// </summary>
public static string SequenceMassCalc_GetHeavyFormula_No_formula_found_for_the_amino_acid___0__ {
get {
return ResourceManager.GetString("SequenceMassCalc_GetHeavyFormula_No_formula_found_for_the_amino_acid___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modification definition {0} missing close bracket..
/// </summary>
public static string SequenceMassCalc_NormalizeModifiedSequence_Modification_definition__0__missing_close_bracket_ {
get {
return ResourceManager.GetString("SequenceMassCalc_NormalizeModifiedSequence_Modification_definition__0__missing_cl" +
"ose_bracket_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The modification {0} is not valid. Expected a numeric delta mass..
/// </summary>
public static string SequenceMassCalc_NormalizeModifiedSequence_The_modification__0__is_not_valid___Expected_a_numeric_delta_mass_ {
get {
return ResourceManager.GetString("SequenceMassCalc_NormalizeModifiedSequence_The_modification__0__is_not_valid___Ex" +
"pected_a_numeric_delta_mass_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The expression '{0}' is not a valid chemical formula..
/// </summary>
public static string SequenceMassCalc_ParseModMass_The_expression__0__is_not_a_valid_chemical_formula {
get {
return ResourceManager.GetString("SequenceMassCalc_ParseModMass_The_expression__0__is_not_a_valid_chemical_formula", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Targets by Accession.
/// </summary>
public static string SequenceTreeForm_UpdateTitle_Targets_by_Accession {
get {
return ResourceManager.GetString("SequenceTreeForm_UpdateTitle_Targets_by_Accession", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Targets by Gene.
/// </summary>
public static string SequenceTreeForm_UpdateTitle_Targets_by_Gene {
get {
return ResourceManager.GetString("SequenceTreeForm_UpdateTitle_Targets_by_Gene", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Targets by Preferred Name.
/// </summary>
public static string SequenceTreeForm_UpdateTitle_Targets_by_Preferred_Name {
get {
return ResourceManager.GetString("SequenceTreeForm_UpdateTitle_Targets_by_Preferred_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure loading {0}..
/// </summary>
public static string SerializableSettingsList_ImportFile_Failure_loading__0__ {
get {
return ResourceManager.GetString("SerializableSettingsList_ImportFile_Failure_loading__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unsupported file version {0}.
/// </summary>
public static string Serializer_ReadHeader_Unsupported_file_version__0_ {
get {
return ResourceManager.GetString("Serializer_ReadHeader_Unsupported_file_version__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A Panorama server must be specified..
/// </summary>
public static string Server_ReadXml_A_Panorama_server_must_be_specified {
get {
return ResourceManager.GetString("Server_ReadXml_A_Panorama_server_must_be_specified", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Server URL is corrupt..
/// </summary>
public static string Server_ReadXml_Server_URL_is_corrupt {
get {
return ResourceManager.GetString("Server_ReadXml_Server_URL_is_corrupt", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Servers.
/// </summary>
public static string ServerList_Label__Servers {
get {
return ResourceManager.GetString("ServerList_Label__Servers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Servers.
/// </summary>
public static string ServerList_Title_Edit_Servers {
get {
return ResourceManager.GetString("ServerList_Title_Edit_Servers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' is not valid for the argument {1} which must be either 'True' or 'False'..
/// </summary>
public static string Setting_Validate_The_value___0___is_not_valid_for_the_argument__1__which_must_be_either__True__or__False__ {
get {
return ResourceManager.GetString("Setting_Validate_The_value___0___is_not_valid_for_the_argument__1__which_must_be_" +
"either__True__or__False__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None.
/// </summary>
public static string SettingsList_ELEMENT_NONE_None {
get {
return ResourceManager.GetString("SettingsList_ELEMENT_NONE_None", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <Add...>.
/// </summary>
public static string SettingsListComboDriver_Add {
get {
return ResourceManager.GetString("SettingsListComboDriver_Add", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <Edit current...>.
/// </summary>
public static string SettingsListComboDriver_Edit_current {
get {
return ResourceManager.GetString("SettingsListComboDriver_Edit_current", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <Edit list...>.
/// </summary>
public static string SettingsListComboDriver_Edit_list {
get {
return ResourceManager.GetString("SettingsListComboDriver_Edit_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Incorrect number of columns ({0}) found on line {1}..
/// </summary>
public static string SettingsUIUtil_DoPasteText_Incorrect_number_of_columns__0__found_on_line__1__ {
get {
return ResourceManager.GetString("SettingsUIUtil_DoPasteText_Incorrect_number_of_columns__0__found_on_line__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to replace them?.
/// </summary>
public static string ShareListDlg_ImportFile_Do_you_want_to_replace_them {
get {
return ResourceManager.GetString("ShareListDlg_ImportFile_Do_you_want_to_replace_them", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure loading {0}..
/// </summary>
public static string ShareListDlg_ImportFile_Failure_loading__0__ {
get {
return ResourceManager.GetString("ShareListDlg_ImportFile_Failure_loading__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following names already exist:.
/// </summary>
public static string ShareListDlg_ImportFile_The_following_names_already_exist {
get {
return ResourceManager.GetString("ShareListDlg_ImportFile_The_following_names_already_exist", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The name '{0}' already exists. Do you want to replace it?.
/// </summary>
public static string ShareListDlg_ImportFile_The_name__0__already_exists_Do_you_want_to_replace_it {
get {
return ResourceManager.GetString("ShareListDlg_ImportFile_The_name__0__already_exists_Do_you_want_to_replace_it", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Save {0}.
/// </summary>
public static string ShareListDlg_Label_Save__0__ {
get {
return ResourceManager.GetString("ShareListDlg_Label_Save__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Select the {0} you want to save to a file..
/// </summary>
public static string ShareListDlg_Label_Select_the__0__you_want_to_save_to_a_file {
get {
return ResourceManager.GetString("ShareListDlg_Label_Select_the__0__you_want_to_save_to_a_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred:.
/// </summary>
public static string ShareListDlg_OkDialog_An_error_occurred {
get {
return ResourceManager.GetString("ShareListDlg_OkDialog_An_error_occurred", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline Settings.
/// </summary>
public static string ShareListDlg_ShareListDlg_Skyline_Settings {
get {
return ResourceManager.GetString("ShareListDlg_ShareListDlg_Skyline_Settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Current saved file ({0}).
/// </summary>
public static string ShareTypeDlg_ShareTypeDlg_Current_saved_file___0__ {
get {
return ResourceManager.GetString("ShareTypeDlg_ShareTypeDlg_Current_saved_file___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot open output file..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Cannot_open_output_file_ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Cannot_open_output_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error copying template file {0} to destination {1}..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Error_copying_template_file__0__to_destination__1__ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Error_copying_template_file__0__to_destinatio" +
"n__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exception raised during output serialization..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Exception_raised_during_output_serialization_ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Exception_raised_during_output_serialization_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input events are not contiguous..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Input_events_are_not_contiguous_ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Input_events_are_not_contiguous_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input events are not in ascending order.
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Input_events_are_not_in_ascending_order {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Input_events_are_not_in_ascending_order", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input string cannot be parsed..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Input_string_cannot_be_parsed_ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Input_string_cannot_be_parsed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input string is empty..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Input_string_is_empty_ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Input_string_is_empty_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid parameter. Cannot create output method..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Invalid_parameter__Cannot_create_output_method_ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Invalid_parameter__Cannot_create_output_metho" +
"d_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Number of events exceed the maximum allowed by LabSolutions (1000)..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Number_of_events_exceed_the_maximum_allowed_by_LabSolutions__1000__ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Number_of_events_exceed_the_maximum_allowed_b" +
"y_LabSolutions__1000__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Output file type is not supported..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Output_file_type_is_not_supported_ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Output_file_type_is_not_supported_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Output method does not contain any events..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Output_method_does_not_contain_any_events_ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Output_method_does_not_contain_any_events_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Output path is not specified..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Output_path_is_not_specified_ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Output_path_is_not_specified_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shimadzu method writer encountered an error:.
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Shimadzu_method_writer_encountered_an_error_ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Shimadzu_method_writer_encountered_an_error_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The transition count {0} exceeds the maximum allowed for this instrument type..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_The_transition_count__0__exceeds_the_maximum_allowed_for_this_instrument_type_ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_The_transition_count__0__exceeds_the_maximum_" +
"allowed_for_this_instrument_type_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected response {0} from Shimadzu method writer..
/// </summary>
public static string ShimadzuMethodExporter_ExportMethod_Unexpected_response__0__from_Shimadzu_method_writer_ {
get {
return ResourceManager.GetString("ShimadzuMethodExporter_ExportMethod_Unexpected_response__0__from_Shimadzu_method_" +
"writer_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot open output file..
/// </summary>
public static string ShimadzuNativeMassListExporter_ExportNativeList_Cannot_open_output_file_ {
get {
return ResourceManager.GetString("ShimadzuNativeMassListExporter_ExportNativeList_Cannot_open_output_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input events are not contiguous..
/// </summary>
public static string ShimadzuNativeMassListExporter_ExportNativeList_Input_events_are_not_contiguous_ {
get {
return ResourceManager.GetString("ShimadzuNativeMassListExporter_ExportNativeList_Input_events_are_not_contiguous_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input events are not in ascending order.
/// </summary>
public static string ShimadzuNativeMassListExporter_ExportNativeList_Input_events_are_not_in_ascending_order {
get {
return ResourceManager.GetString("ShimadzuNativeMassListExporter_ExportNativeList_Input_events_are_not_in_ascending" +
"_order", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input string cannot be parsed..
/// </summary>
public static string ShimadzuNativeMassListExporter_ExportNativeList_Input_string_cannot_be_parsed_ {
get {
return ResourceManager.GetString("ShimadzuNativeMassListExporter_ExportNativeList_Input_string_cannot_be_parsed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input string is empty..
/// </summary>
public static string ShimadzuNativeMassListExporter_ExportNativeList_Input_string_is_empty_ {
get {
return ResourceManager.GetString("ShimadzuNativeMassListExporter_ExportNativeList_Input_string_is_empty_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid parameter. Cannot create output method..
/// </summary>
public static string ShimadzuNativeMassListExporter_ExportNativeList_Invalid_parameter__Cannot_create_output_method_ {
get {
return ResourceManager.GetString("ShimadzuNativeMassListExporter_ExportNativeList_Invalid_parameter__Cannot_create_" +
"output_method_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Number of events exceed maximum allowed by LabSolutions (1000)..
/// </summary>
public static string ShimadzuNativeMassListExporter_ExportNativeList_Number_of_events_exceed_maximum_allowed_by_LabSolutions__1000__ {
get {
return ResourceManager.GetString("ShimadzuNativeMassListExporter_ExportNativeList_Number_of_events_exceed_maximum_a" +
"llowed_by_LabSolutions__1000__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shimadzu method converter encountered an error:.
/// </summary>
public static string ShimadzuNativeMassListExporter_ExportNativeList_Shimadzu_method_converter_encountered_an_error_ {
get {
return ResourceManager.GetString("ShimadzuNativeMassListExporter_ExportNativeList_Shimadzu_method_converter_encount" +
"ered_an_error_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The transition count {0} exceeds the maximum allowed for this instrument type.
/// </summary>
public static string ShimadzuNativeMassListExporter_ExportNativeList_The_transition_count__0__exceeds_the_maximum_allowed_for_this_instrument_type {
get {
return ResourceManager.GetString("ShimadzuNativeMassListExporter_ExportNativeList_The_transition_count__0__exceeds_" +
"the_maximum_allowed_for_this_instrument_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected response {0} from Shimadzu method converter.
/// </summary>
public static string ShimadzuNativeMassListExporter_ExportNativeList_Unexpected_response__0__from_Shimadzu_method_converter {
get {
return ResourceManager.GetString("ShimadzuNativeMassListExporter_ExportNativeList_Unexpected_response__0__from_Shim" +
"adzu_method_converter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Index is out of range.
/// </summary>
public static string SizedSet_Add_SizedSet_index_value_is_out_of_range {
get {
return ResourceManager.GetString("SizedSet_Add_SizedSet_index_value_is_out_of_range", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please provide an email address at which we can contact you if we have any further questions regarding the error.
///If you prefer you can choose to report anonymously..
/// </summary>
public static string SkippedReportErrorDlg_btnOK_Click_No_Email {
get {
return ResourceManager.GetString("SkippedReportErrorDlg_btnOK_Click_No_Email", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
public static System.Drawing.Icon Skyline {
get {
object obj = ResourceManager.GetObject("Skyline", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
public static System.Drawing.Icon Skyline_Daily {
get {
object obj = ResourceManager.GetObject("Skyline_Daily", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to peptides.
/// </summary>
public static string Skyline_peptides {
get {
return ResourceManager.GetString("Skyline_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to protein.
/// </summary>
public static string Skyline_protein {
get {
return ResourceManager.GetString("Skyline_protein", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Skyline_Release {
get {
object obj = ResourceManager.GetObject("Skyline_Release", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
public static System.Drawing.Icon Skyline_Release1 {
get {
object obj = ResourceManager.GetObject("Skyline_Release1", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
public static System.Drawing.Icon SkylineData {
get {
object obj = ResourceManager.GetObject("SkylineData", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Item in list '{0}'.
/// </summary>
public static string SkylineDataSchema_GetTypeDescription_Item_in_list___0__ {
get {
return ResourceManager.GetString("SkylineDataSchema_GetTypeDescription_Item_in_list___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document was modified in the middle of the operation..
/// </summary>
public static string SkylineDataSchema_VerifyDocumentCurrent_The_document_was_modified_in_the_middle_of_the_operation_ {
get {
return ResourceManager.GetString("SkylineDataSchema_VerifyDocumentCurrent_The_document_was_modified_in_the_middle_o" +
"f_the_operation_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
public static System.Drawing.Icon SkylineDoc {
get {
object obj = ResourceManager.GetObject("SkylineDoc", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete these {0} things?.
/// </summary>
public static string SkylineDocNode_GetGenericDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__things_ {
get {
return ResourceManager.GetString("SkylineDocNode_GetGenericDeleteConfirmation_Are_you_sure_you_want_to_delete_these" +
"__0__things_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap SkylineImg {
get {
object obj = ResourceManager.GetObject("SkylineImg", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Please save a new file to work with..
/// </summary>
public static string SkylineStartup_SaveFileDlg_Please_save_a_new_file_to_work_with_ {
get {
return ResourceManager.GetString("SkylineStartup_SaveFileDlg_Please_save_a_new_file_to_work_with_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Blank Document.
/// </summary>
public static string SkylineStartup_SkylineStartup_Blank_Document {
get {
return ResourceManager.GetString("SkylineStartup_SkylineStartup_Blank_Document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import DDA Peptide Search.
/// </summary>
public static string SkylineStartup_SkylineStartup_Import_DDA_Peptide_Search {
get {
return ResourceManager.GetString("SkylineStartup_SkylineStartup_Import_DDA_Peptide_Search", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import FASTA.
/// </summary>
public static string SkylineStartup_SkylineStartup_Import_FASTA {
get {
return ResourceManager.GetString("SkylineStartup_SkylineStartup_Import_FASTA", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Peptide List.
/// </summary>
public static string SkylineStartup_SkylineStartup_Import_Peptide_List {
get {
return ResourceManager.GetString("SkylineStartup_SkylineStartup_Import_Peptide_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Protein List.
/// </summary>
public static string SkylineStartup_SkylineStartup_Import_Protein_List {
get {
return ResourceManager.GetString("SkylineStartup_SkylineStartup_Import_Protein_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Transition List.
/// </summary>
public static string SkylineStartup_SkylineStartup_Import_Transition_List {
get {
return ResourceManager.GetString("SkylineStartup_SkylineStartup_Import_Transition_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Start a new Skyline document from a complete transition list with peptide sequences, precursor m/z values, and product m/z values, which you can paste into a grid..
/// </summary>
public static string SkylineStartup_SkylineStartup_Start_a_new_Skyline_document_from_a_complete_transition_list_with_peptide_sequences__precursor_m_z_values__and_product_m_z_values__which_you_can_paste_into_a_grid_ {
get {
return ResourceManager.GetString("SkylineStartup_SkylineStartup_Start_a_new_Skyline_document_from_a_complete_transi" +
"tion_list_with_peptide_sequences__precursor_m_z_values__and_product_m_z_values__" +
"which_you_can_paste_into_a_grid_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Start a new Skyline document with target proteins specified in a tabular list you can paste into a grid..
/// </summary>
public static string SkylineStartup_SkylineStartup_Start_a_new_Skyline_document_with_target_proteins_specified_in_a_tabular_list_you_can_paste_into_a_grid_ {
get {
return ResourceManager.GetString("SkylineStartup_SkylineStartup_Start_a_new_Skyline_document_with_target_proteins_s" +
"pecified_in_a_tabular_list_you_can_paste_into_a_grid_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Start a new Skyline document with target proteins specified in FASTA format..
/// </summary>
public static string SkylineStartup_SkylineStartup_Start_a_new_Skyline_document_with_target_proteins_specified_in_FASTA_format_ {
get {
return ResourceManager.GetString("SkylineStartup_SkylineStartup_Start_a_new_Skyline_document_with_target_proteins_s" +
"pecified_in_FASTA_format_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Start a new Skyline document with targets specified as a list of peptide sequences in a tabular list you can paste into a grid..
/// </summary>
public static string SkylineStartup_SkylineStartup_Start_a_new_Skyline_document_with_targets_specified_as_a_list_of_peptide_sequences_in_a_tabular_list_you_can_paste_into_a_grid_ {
get {
return ResourceManager.GetString("SkylineStartup_SkylineStartup_Start_a_new_Skyline_document_with_targets_specified" +
"_as_a_list_of_peptide_sequences_in_a_tabular_list_you_can_paste_into_a_grid_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use the Skyline Import Peptide Search wizard to build a spectral library from peptide search results on DDA data, and then import the raw data to quantify peptides using Skyline MS1 Filtering..
/// </summary>
public static string SkylineStartup_SkylineStartup_Use_the_Skyline_Import_Peptide_Search_wizard_to_build_a_spectral_library_from_peptide_search_results_on_DDA_data__and_then_import_the_raw_data_to_quantify_peptides_using_Skyline_MS1_Filtering_ {
get {
return ResourceManager.GetString("SkylineStartup_SkylineStartup_Use_the_Skyline_Import_Peptide_Search_wizard_to_bui" +
"ld_a_spectral_library_from_peptide_search_results_on_DDA_data__and_then_import_t" +
"he_raw_data_to_quantify_peptides_using_Skyline_MS1_Filtering_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Developer Build.
/// </summary>
public static string SkylineVersion_GetCurrentVersionName_Developer_Build {
get {
return ResourceManager.GetString("SkylineVersion_GetCurrentVersionName_Developer_Build", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Latest ({0}).
/// </summary>
public static string SkylineVersion_GetCurrentVersionName_Latest___0__ {
get {
return ResourceManager.GetString("SkylineVersion_GetCurrentVersionName_Latest___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline 19.1.
/// </summary>
public static string SkylineVersion_V19_1_Skyline_19_1 {
get {
return ResourceManager.GetString("SkylineVersion_V19_1_Skyline_19_1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline 20.1.
/// </summary>
public static string SkylineVersion_V20_1_Skyline_20_1 {
get {
return ResourceManager.GetString("SkylineVersion_V20_1_Skyline_20_1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline 20.2.
/// </summary>
public static string SkylineVersion_V20_2_Skyline_20_2 {
get {
return ResourceManager.GetString("SkylineVersion_V20_2_Skyline_20_2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline 3.6.
/// </summary>
public static string SkylineVersion_V3_6_Skyline_3_6 {
get {
return ResourceManager.GetString("SkylineVersion_V3_6_Skyline_3_6", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline 3.7.
/// </summary>
public static string SkylineVersion_V3_7_Skyline_3_7 {
get {
return ResourceManager.GetString("SkylineVersion_V3_7_Skyline_3_7", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline 4.1.
/// </summary>
public static string SkylineVersion_V4_1_Skyline_4_1 {
get {
return ResourceManager.GetString("SkylineVersion_V4_1_Skyline_4_1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline 4.2.
/// </summary>
public static string SkylineVersion_V4_2_Skyline_4_2 {
get {
return ResourceManager.GetString("SkylineVersion_V4_2_Skyline_4_2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change Document Reports.
/// </summary>
public static string SkylineViewContext_ChangeDocumentViewSpec_Change_Document_Reports {
get {
return ResourceManager.GetString("SkylineViewContext_ChangeDocumentViewSpec_Change_Document_Reports", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Delete items.
/// </summary>
public static string SkylineViewContext_DeleteDocNodes_Delete_items {
get {
return ResourceManager.GetString("SkylineViewContext_DeleteDocNodes_Delete_items", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule Lists.
/// </summary>
public static string SkylineViewContext_GetDocumentGridRowSources_Molecule_Lists {
get {
return ResourceManager.GetString("SkylineViewContext_GetDocumentGridRowSources_Molecule_Lists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecules.
/// </summary>
public static string SkylineViewContext_GetDocumentGridRowSources_Molecules {
get {
return ResourceManager.GetString("SkylineViewContext_GetDocumentGridRowSources_Molecules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides.
/// </summary>
public static string SkylineViewContext_GetDocumentGridRowSources_Peptides {
get {
return ResourceManager.GetString("SkylineViewContext_GetDocumentGridRowSources_Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursors.
/// </summary>
public static string SkylineViewContext_GetDocumentGridRowSources_Precursors {
get {
return ResourceManager.GetString("SkylineViewContext_GetDocumentGridRowSources_Precursors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Proteins.
/// </summary>
public static string SkylineViewContext_GetDocumentGridRowSources_Proteins {
get {
return ResourceManager.GetString("SkylineViewContext_GetDocumentGridRowSources_Proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicates.
/// </summary>
public static string SkylineViewContext_GetDocumentGridRowSources_Replicates {
get {
return ResourceManager.GetString("SkylineViewContext_GetDocumentGridRowSources_Replicates", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transitions.
/// </summary>
public static string SkylineViewContext_GetDocumentGridRowSources_Transitions {
get {
return ResourceManager.GetString("SkylineViewContext_GetDocumentGridRowSources_Transitions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mixed Transition List.
/// </summary>
public static string SkylineViewContext_GetTransitionListReportSpec_Mixed_Transition_List {
get {
return ResourceManager.GetString("SkylineViewContext_GetTransitionListReportSpec_Mixed_Transition_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide Transition List.
/// </summary>
public static string SkylineViewContext_GetTransitionListReportSpec_Peptide_Transition_List {
get {
return ResourceManager.GetString("SkylineViewContext_GetTransitionListReportSpec_Peptide_Transition_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Small Molecule Transition List.
/// </summary>
public static string SkylineViewContext_GetTransitionListReportSpec_Small_Molecule_Transition_List {
get {
return ResourceManager.GetString("SkylineViewContext_GetTransitionListReportSpec_Small_Molecule_Transition_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure loading {0}..
/// </summary>
public static string SkylineViewContext_ImportViews_Failure_loading__0__ {
get {
return ResourceManager.GetString("SkylineViewContext_ImportViews_Failure_loading__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No views were found in that file..
/// </summary>
public static string SkylineViewContext_ImportViews_No_views_were_found_in_that_file_ {
get {
return ResourceManager.GetString("SkylineViewContext_ImportViews_No_views_were_found_in_that_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change Document Reports.
/// </summary>
public static string SkylineViewContext_SaveViewSpecList_Change_Document_Reports {
get {
return ResourceManager.GetString("SkylineViewContext_SaveViewSpecList_Change_Document_Reports", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Accept peptides.
/// </summary>
public static string SkylineWindow_acceptPeptidesMenuItem_Click_Accept_peptides {
get {
return ResourceManager.GetString("SkylineWindow_acceptPeptidesMenuItem_Click_Accept_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All Replicates.
/// </summary>
public static string SkylineWindow_AddGroupByMenuItems_All_Replicates {
get {
return ResourceManager.GetString("SkylineWindow_AddGroupByMenuItems_All_Replicates", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add Fold Change.
/// </summary>
public static string SkylineWindow_AddGroupComparison_Add_Fold_Change {
get {
return ResourceManager.GetString("SkylineWindow_AddGroupComparison_Add_Fold_Change", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Imported peptide {0} with iRT library value is already being used as an iRT standard..
/// </summary>
public static string SkylineWindow_AddIrtPeptides_Imported_peptide__0__with_iRT_library_value_is_already_being_used_as_an_iRT_standard_ {
get {
return ResourceManager.GetString("SkylineWindow_AddIrtPeptides_Imported_peptide__0__with_iRT_library_value_is_alrea" +
"dy_being_used_as_an_iRT_standard_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add custom product ion {0}.
/// </summary>
public static string SkylineWindow_AddMolecule_Add_custom_product_ion__0_ {
get {
return ResourceManager.GetString("SkylineWindow_AddMolecule_Add_custom_product_ion__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add Transition.
/// </summary>
public static string SkylineWindow_AddMolecule_Add_Transition {
get {
return ResourceManager.GetString("SkylineWindow_AddMolecule_Add_Transition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Custom molecules cannot be added to a peptide list..
/// </summary>
public static string SkylineWindow_AddMolecule_Custom_molecules_cannot_be_added_to_a_peptide_list_ {
get {
return ResourceManager.GetString("SkylineWindow_AddMolecule_Custom_molecules_cannot_be_added_to_a_peptide_list_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Custom molecules cannot be added to a protein..
/// </summary>
public static string SkylineWindow_AddMolecule_Custom_molecules_cannot_be_added_to_a_protein_ {
get {
return ResourceManager.GetString("SkylineWindow_AddMolecule_Custom_molecules_cannot_be_added_to_a_protein_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor m/z for this molecule is out of range for your instrument settings..
/// </summary>
public static string SkylineWindow_AddMolecule_The_precursor_m_z_for_this_molecule_is_out_of_range_for_your_instrument_settings_ {
get {
return ResourceManager.GetString("SkylineWindow_AddMolecule_The_precursor_m_z_for_this_molecule_is_out_of_range_for" +
"_your_instrument_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add Precursor.
/// </summary>
public static string SkylineWindow_AddSmallMolecule_Add_Precursor {
get {
return ResourceManager.GetString("SkylineWindow_AddSmallMolecule_Add_Precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add molecule {0}.
/// </summary>
public static string SkylineWindow_AddSmallMolecule_Add_small_molecule__0_ {
get {
return ResourceManager.GetString("SkylineWindow_AddSmallMolecule_Add_small_molecule__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add Molecule and Precursor.
/// </summary>
public static string SkylineWindow_AddSmallMolecule_Add_Small_Molecule_and_Precursor {
get {
return ResourceManager.GetString("SkylineWindow_AddSmallMolecule_Add_Small_Molecule_and_Precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add molecule precursor {0}.
/// </summary>
public static string SkylineWindow_AddSmallMolecule_Add_small_molecule_precursor__0_ {
get {
return ResourceManager.GetString("SkylineWindow_AddSmallMolecule_Add_small_molecule_precursor__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add standard peptides.
/// </summary>
public static string SkylineWindow_AddStandardsToDocument_Add_standard_peptides {
get {
return ResourceManager.GetString("SkylineWindow_AddStandardsToDocument_Add_standard_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Align Times To {0}.
/// </summary>
public static string SkylineWindow_AlignTimesToFileFormat {
get {
return ResourceManager.GetString("SkylineWindow_AlignTimesToFileFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Applying Peak.
/// </summary>
public static string SkylineWindow_ApplyPeak_Applying_Peak {
get {
return ResourceManager.GetString("SkylineWindow_ApplyPeak_Applying_Peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to apply peak..
/// </summary>
public static string SkylineWindow_ApplyPeak_Failed_to_apply_peak_ {
get {
return ResourceManager.GetString("SkylineWindow_ApplyPeak_Failed_to_apply_peak_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No results found for the precursor {0} in the file {1}..
/// </summary>
public static string SkylineWindow_ApplyPeak_No_results_found_for_the_precursor__0__in_the_file__1__ {
get {
return ResourceManager.GetString("SkylineWindow_ApplyPeak_No_results_found_for_the_precursor__0__in_the_file__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Expected.
/// </summary>
public static string SkylineWindow_BuildAreaGraphMenu_Show_Expected {
get {
return ResourceManager.GetString("SkylineWindow_BuildAreaGraphMenu_Show_Expected", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show Library.
/// </summary>
public static string SkylineWindow_BuildAreaGraphMenu_Show_Library {
get {
return ResourceManager.GetString("SkylineWindow_BuildAreaGraphMenu_Show_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Apply Peak to .
/// </summary>
public static string SkylineWindow_BuildChromatogramMenu_Apply_Peak_to_ {
get {
return ResourceManager.GetString("SkylineWindow_BuildChromatogramMenu_Apply_Peak_to_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Store Panorama upload location.
/// </summary>
public static string SkylineWindow_ChangeDocPanoramaUri_Store_Panorama_upload_location {
get {
return ResourceManager.GetString("SkylineWindow_ChangeDocPanoramaUri_Store_Panorama_upload_location", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change settings.
/// </summary>
public static string SkylineWindow_ChangeSettings_Change_settings {
get {
return ResourceManager.GetString("SkylineWindow_ChangeSettings_Change_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Click OK to open the document anyway..
/// </summary>
public static string SkylineWindow_CheckResults_Click_OK_to_open_the_document_anyway {
get {
return ResourceManager.GetString("SkylineWindow_CheckResults_Click_OK_to_open_the_document_anyway", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The data file '{0}' is missing, and the following original instrument output could not be found:.
/// </summary>
public static string SkylineWindow_CheckResults_The_data_file___0___is_missing__and_the_following_original_instrument_output_could_not_be_found_ {
get {
return ResourceManager.GetString("SkylineWindow_CheckResults_The_data_file___0___is_missing__and_the_following_orig" +
"inal_instrument_output_could_not_be_found_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The Transition Settings Full-Scan retention time filter is set to use the predicted retention time, but no prediction algorithm has been specified.
///Go to the Peptide Settings Prediction tab to fix..
/// </summary>
public static string SkylineWindow_CheckRetentionTimeFilter_NoPredictionAlgorithm {
get {
return ResourceManager.GetString("SkylineWindow_CheckRetentionTimeFilter_NoPredictionAlgorithm", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The Transition Settings Full-Scan retention time filter is set to use the predicted retention time, but the prediction algorithm has not been calibrated. Do you want to generate full gradient chromatograms?.
/// </summary>
public static string SkylineWindow_CheckRetentionTimeFilter_NoReplicatesAvailableForPrediction {
get {
return ResourceManager.GetString("SkylineWindow_CheckRetentionTimeFilter_NoReplicatesAvailableForPrediction", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to save changes?.
/// </summary>
public static string SkylineWindow_CheckSaveDocument_Do_you_want_to_save_changes {
get {
return ResourceManager.GetString("SkylineWindow_CheckSaveDocument_Do_you_want_to_save_changes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No.
/// </summary>
public static string SkylineWindow_CheckSaveDocument_No {
get {
return ResourceManager.GetString("SkylineWindow_CheckSaveDocument_No", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Yes.
/// </summary>
public static string SkylineWindow_CheckSaveDocument_Yes {
get {
return ResourceManager.GetString("SkylineWindow_CheckSaveDocument_Yes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to
///
///{0} ran out of memory..
/// </summary>
public static string SkylineWindow_CompleteProgressUI_Ran_Out_Of_Memory {
get {
return ResourceManager.GetString("SkylineWindow_CompleteProgressUI_Ran_Out_Of_Memory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to
///
///You may be able to avoid this problem by installing a 64-bit version of {0}..
/// </summary>
public static string SkylineWindow_CompleteProgressUI_version_issue {
get {
return ResourceManager.GetString("SkylineWindow_CompleteProgressUI_version_issue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not find the spectral library {0} for this document. Without the library, no spectrum ID information will be available..
/// </summary>
public static string SkylineWindow_ConnectLibrarySpecs_Could_not_find_the_spectral_library__0__for_this_document__Without_the_library__no_spectrum_ID_information_will_be_available_ {
get {
return ResourceManager.GetString("SkylineWindow_ConnectLibrarySpecs_Could_not_find_the_spectral_library__0__for_thi" +
"s_document__Without_the_library__no_spectrum_ID_information_will_be_available_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Find Spectral Library.
/// </summary>
public static string SkylineWindow_ConnectLibrarySpecs_Find_Spectral_Library {
get {
return ResourceManager.GetString("SkylineWindow_ConnectLibrarySpecs_Find_Spectral_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Spectral Library.
/// </summary>
public static string SkylineWindow_ConnectLibrarySpecs_Spectral_Library {
get {
return ResourceManager.GetString("SkylineWindow_ConnectLibrarySpecs_Spectral_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Detection.
/// </summary>
public static string SkylineWindow_CreateGraphDetections_Counts {
get {
return ResourceManager.GetString("SkylineWindow_CreateGraphDetections_Counts", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mass Errors.
/// </summary>
public static string SkylineWindow_CreateGraphMassError_Mass_Errors {
get {
return ResourceManager.GetString("SkylineWindow_CreateGraphMassError_Mass_Errors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peak Areas.
/// </summary>
public static string SkylineWindow_CreateGraphPeakArea_Peak_Areas {
get {
return ResourceManager.GetString("SkylineWindow_CreateGraphPeakArea_Peak_Areas", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retention Times.
/// </summary>
public static string SkylineWindow_CreateGraphRetentionTime_Retention_Times {
get {
return ResourceManager.GetString("SkylineWindow_CreateGraphRetentionTime_Retention_Times", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Set regression {0}.
/// </summary>
public static string SkylineWindow_CreateRegression_Set_regression__0__ {
get {
return ResourceManager.GetString("SkylineWindow_CreateRegression_Set_regression__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The DocumentUI property may only be accessed on the UI thread..
/// </summary>
public static string SkylineWindow_DocumentUI_The_DocumentUI_property_may_only_be_accessed_on_the_UI_thread {
get {
return ResourceManager.GetString("SkylineWindow_DocumentUI_The_DocumentUI_property_may_only_be_accessed_on_the_UI_t" +
"hread", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Delete {0}.
/// </summary>
public static string SkylineWindow_EditDelete_Delete__0__ {
get {
return ResourceManager.GetString("SkylineWindow_EditDelete_Delete__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to items.
/// </summary>
public static string SkylineWindow_EditDelete_items {
get {
return ResourceManager.GetString("SkylineWindow_EditDelete_items", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Note.
/// </summary>
public static string SkylineWindow_EditNote_Edit_Note {
get {
return ResourceManager.GetString("SkylineWindow_EditNote_Edit_Note", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Apply Peak to Group.
/// </summary>
public static string SkylineWindow_editToolStripMenuItem_DropDownOpening_Apply_Peak_to_Group {
get {
return ResourceManager.GetString("SkylineWindow_editToolStripMenuItem_DropDownOpening_Apply_Peak_to_Group", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Lists.
/// </summary>
public static string SkylineWindow_expandAllMenuItem_DropDownOpening__Lists {
get {
return ResourceManager.GetString("SkylineWindow_expandAllMenuItem_DropDownOpening__Lists", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Molecules.
/// </summary>
public static string SkylineWindow_expandAllMenuItem_DropDownOpening__Molecules {
get {
return ResourceManager.GetString("SkylineWindow_expandAllMenuItem_DropDownOpening__Molecules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The number of targets exceeds the limit for this operation..
/// </summary>
public static string SkylineWindow_ExpandProteins_The_number_of_targets_exceeds_the_limit_for_this_operation_ {
get {
return ResourceManager.GetString("SkylineWindow_ExpandProteins_The_number_of_targets_exceeds_the_limit_for_this_ope" +
"ration_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is no isolation list data to export..
/// </summary>
public static string SkylineWindow_exportIsolationListMenuItem_Click_There_is_no_isolation_list_data_to_export {
get {
return ResourceManager.GetString("SkylineWindow_exportIsolationListMenuItem_Click_There_is_no_isolation_list_data_t" +
"o_export", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Background Proteome.
/// </summary>
public static string SkylineWindow_FindBackgroundProteome_Background_Proteome {
get {
return ResourceManager.GetString("SkylineWindow_FindBackgroundProteome_Background_Proteome", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Find Background Proteome.
/// </summary>
public static string SkylineWindow_FindBackgroundProteome_Find_Background_Proteome {
get {
return ResourceManager.GetString("SkylineWindow_FindBackgroundProteome_Find_Background_Proteome", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Proteome File.
/// </summary>
public static string SkylineWindow_FindBackgroundProteome_Proteome_File {
get {
return ResourceManager.GetString("SkylineWindow_FindBackgroundProteome_Proteome_File", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ion mobility library files.
/// </summary>
public static string SkylineWindow_FindIonMobilityDatabase_ion_mobility_library_files {
get {
return ResourceManager.GetString("SkylineWindow_FindIonMobilityDatabase_ion_mobility_library_files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The ion mobility library specified could not be opened:.
/// </summary>
public static string SkylineWindow_FindIonMobilityDatabase_The_ion_mobility_library_specified_could_not_be_opened_ {
get {
return ResourceManager.GetString("SkylineWindow_FindIonMobilityDatabase_The_ion_mobility_library_specified_could_no" +
"t_be_opened_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Find Ion Mobility Library.
/// </summary>
public static string SkylineWindow_FindIonMobilityLibrary_Find_Ion_Mobility_Library {
get {
return ResourceManager.GetString("SkylineWindow_FindIonMobilityLibrary_Find_Ion_Mobility_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ion Mobility Library.
/// </summary>
public static string SkylineWindow_FindIonMobilityLibrary_Ion_Mobility_Library {
get {
return ResourceManager.GetString("SkylineWindow_FindIonMobilityLibrary_Ion_Mobility_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Find iRT Calculator.
/// </summary>
public static string SkylineWindow_FindIrtDatabase_Find_iRT_Calculator {
get {
return ResourceManager.GetString("SkylineWindow_FindIrtDatabase_Find_iRT_Calculator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT Calculator.
/// </summary>
public static string SkylineWindow_FindIrtDatabase_iRT_Calculator {
get {
return ResourceManager.GetString("SkylineWindow_FindIrtDatabase_iRT_Calculator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to iRT Database Files.
/// </summary>
public static string SkylineWindow_FindIrtDatabase_iRT_Database_Files {
get {
return ResourceManager.GetString("SkylineWindow_FindIrtDatabase_iRT_Database_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The database file specified could not be opened:.
/// </summary>
public static string SkylineWindow_FindIrtDatabase_The_database_file_specified_could_not_be_opened {
get {
return ResourceManager.GetString("SkylineWindow_FindIrtDatabase_The_database_file_specified_could_not_be_opened", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Find Optimization Library.
/// </summary>
public static string SkylineWindow_FindOptimizationDatabase_Find_Optimization_Library {
get {
return ResourceManager.GetString("SkylineWindow_FindOptimizationDatabase_Find_Optimization_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Optimization Library.
/// </summary>
public static string SkylineWindow_FindOptimizationDatabase_Optimization_Library {
get {
return ResourceManager.GetString("SkylineWindow_FindOptimizationDatabase_Optimization_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Optimization Library Files.
/// </summary>
public static string SkylineWindow_FindOptimizationDatabase_Optimization_Library_Files {
get {
return ResourceManager.GetString("SkylineWindow_FindOptimizationDatabase_Optimization_Library_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The database file specified could not be opened:.
/// </summary>
public static string SkylineWindow_FindOptimizationDatabase_The_database_file_specified_could_not_be_opened_ {
get {
return ResourceManager.GetString("SkylineWindow_FindOptimizationDatabase_The_database_file_specified_could_not_be_o" +
"pened_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to continue?.
/// </summary>
public static string SkylineWindow_generateDecoysMenuItem_Click_Are_you_sure_you_want_to_continue {
get {
return ResourceManager.GetString("SkylineWindow_generateDecoysMenuItem_Click_Are_you_sure_you_want_to_continue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must contain peptides to generate decoys..
/// </summary>
public static string SkylineWindow_generateDecoysMenuItem_Click_The_document_must_contain_peptides_to_generate_decoys_ {
get {
return ResourceManager.GetString("SkylineWindow_generateDecoysMenuItem_Click_The_document_must_contain_peptides_to_" +
"generate_decoys_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This operation will replace the existing decoys..
/// </summary>
public static string SkylineWindow_generateDecoysMenuItem_Click_This_operation_will_replace_the_existing_decoys {
get {
return ResourceManager.GetString("SkylineWindow_generateDecoysMenuItem_Click_This_operation_will_replace_the_existi" +
"ng_decoys", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change peak end to {0:F01}.
/// </summary>
public static string SkylineWindow_graphChromatogram_ChangedPeakBounds_Change_peak_end_to__0_F01_ {
get {
return ResourceManager.GetString("SkylineWindow_graphChromatogram_ChangedPeakBounds_Change_peak_end_to__0_F01_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change peak start to {0:F01}.
/// </summary>
public static string SkylineWindow_graphChromatogram_ChangedPeakBounds_Change_peak_start_to__0_F01_ {
get {
return ResourceManager.GetString("SkylineWindow_graphChromatogram_ChangedPeakBounds_Change_peak_start_to__0_F01_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change peak to {0:F01}-{1:F01}.
/// </summary>
public static string SkylineWindow_graphChromatogram_ChangedPeakBounds_Change_peak_to__0_F01___1_F01_ {
get {
return ResourceManager.GetString("SkylineWindow_graphChromatogram_ChangedPeakBounds_Change_peak_to__0_F01___1_F01_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change peaks.
/// </summary>
public static string SkylineWindow_graphChromatogram_ChangedPeakBounds_Change_peaks {
get {
return ResourceManager.GetString("SkylineWindow_graphChromatogram_ChangedPeakBounds_Change_peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove peak.
/// </summary>
public static string SkylineWindow_graphChromatogram_ChangedPeakBounds_Remove_peak {
get {
return ResourceManager.GetString("SkylineWindow_graphChromatogram_ChangedPeakBounds_Remove_peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The raw file must be re-imported in order to show full scans: {0}.
/// </summary>
public static string SkylineWindow_graphChromatogram_ClickedChromatogram_The_raw_file_must_be_re_imported_in_order_to_show_full_scans___0_ {
get {
return ResourceManager.GetString("SkylineWindow_graphChromatogram_ClickedChromatogram_The_raw_file_must_be_re_impor" +
"ted_in_order_to_show_full_scans___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Pick peak {0:F01}.
/// </summary>
public static string SkylineWindow_graphChromatogram_PickedPeak_Pick_peak__0_F01_ {
get {
return ResourceManager.GetString("SkylineWindow_graphChromatogram_PickedPeak_Pick_peak__0_F01_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while attempting to load the iRT database {0}. iRT standards cannot be automatically added to the document..
/// </summary>
public static string SkylineWindow_HandleStandardsChanged_An_error_occurred_while_attempting_to_load_the_iRT_database__0___iRT_standards_cannot_be_automatically_added_to_the_document_ {
get {
return ResourceManager.GetString("SkylineWindow_HandleStandardsChanged_An_error_occurred_while_attempting_to_load_t" +
"he_iRT_database__0___iRT_standards_cannot_be_automatically_added_to_the_document" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Opening a document inside a ZIP file is not supported..
/// </summary>
public static string SkylineWindow_HasFileToOpen_Opening_a_document_inside_a_ZIP_file_is_not_supported_ {
get {
return ResourceManager.GetString("SkylineWindow_HasFileToOpen_Opening_a_document_inside_a_ZIP_file_is_not_supported" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The path to the file to open is too long..
/// </summary>
public static string SkylineWindow_HasFileToOpen_The_path_to_the_file_to_open_is_too_long_ {
get {
return ResourceManager.GetString("SkylineWindow_HasFileToOpen_The_path_to_the_file_to_open_is_too_long_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unzip the file {0} first and then open the extracted file {1}..
/// </summary>
public static string SkylineWindow_HasFileToOpen_Unzip_the_file__0__first_and_then_open_the_extracted_file__1__ {
get {
return ResourceManager.GetString("SkylineWindow_HasFileToOpen_Unzip_the_file__0__first_and_then_open_the_extracted_" +
"file__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Annotations.
/// </summary>
public static string SkylineWindow_ImportAnnotations_Import_Annotations {
get {
return ResourceManager.GetString("SkylineWindow_ImportAnnotations_Import_Annotations", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is an existing library with the same name {0} as the document library to be created. Overwrite?.
/// </summary>
public static string SkylineWindow_ImportAssayLibrary_There_is_an_existing_library_with_the_same_name__0__as_the_document_library_to_be_created__Overwrite_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportAssayLibrary_There_is_an_existing_library_with_the_same_name_" +
"_0__as_the_document_library_to_be_created__Overwrite_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must save the Skyline document in order to import an assay library..
/// </summary>
public static string SkylineWindow_ImportAssayLibrary_You_must_save_the_Skyline_document_in_order_to_import_an_assay_library_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportAssayLibrary_You_must_save_the_Skyline_document_in_order_to_i" +
"mport_an_assay_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Assay Library.
/// </summary>
public static string SkylineWindow_importAssayLibraryMenuItem_Click_Assay_Library {
get {
return ResourceManager.GetString("SkylineWindow_importAssayLibraryMenuItem_Click_Assay_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Assay Library.
/// </summary>
public static string SkylineWindow_importAssayLibraryMenuItem_Click_Import_Assay_Library {
get {
return ResourceManager.GetString("SkylineWindow_importAssayLibraryMenuItem_Click_Import_Assay_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed importing file {0}. {1}.
/// </summary>
public static string SkylineWindow_importDocumentMenuItem_Click_Failed_importing_file__0__1__ {
get {
return ResourceManager.GetString("SkylineWindow_importDocumentMenuItem_Click_Failed_importing_file__0__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed importing files:.
/// </summary>
public static string SkylineWindow_importDocumentMenuItem_Click_Failed_importing_files {
get {
return ResourceManager.GetString("SkylineWindow_importDocumentMenuItem_Click_Failed_importing_files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Skyline Document.
/// </summary>
public static string SkylineWindow_importDocumentMenuItem_Click_Import_Skyline_Document {
get {
return ResourceManager.GetString("SkylineWindow_importDocumentMenuItem_Click_Import_Skyline_Document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to OK.
/// </summary>
public static string SkylineWindow_ImportFasta_OK {
get {
return ResourceManager.GetString("SkylineWindow_ImportFasta_OK", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This operation discarded {0} proteins with no peptides matching the current filter settings..
/// </summary>
public static string SkylineWindow_ImportFasta_This_operation_discarded__0__proteins_with_no_peptides_matching_the_current_filter_settings_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportFasta_This_operation_discarded__0__proteins_with_no_peptides_" +
"matching_the_current_filter_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected document change during operation..
/// </summary>
public static string SkylineWindow_ImportFasta_Unexpected_document_change_during_operation {
get {
return ResourceManager.GetString("SkylineWindow_ImportFasta_Unexpected_document_change_during_operation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Would you like to use the Unimod definitions for the following modifications?.
/// </summary>
public static string SkylineWindow_ImportFasta_Would_you_like_to_use_the_Unimod_definitions_for_the_following_modifications {
get {
return ResourceManager.GetString("SkylineWindow_ImportFasta_Would_you_like_to_use_the_Unimod_definitions_for_the_fo" +
"llowing_modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed reading the file {0}. {1}.
/// </summary>
public static string SkylineWindow_ImportFastaFile_Failed_reading_the_file__0__1__ {
get {
return ResourceManager.GetString("SkylineWindow_ImportFastaFile_Failed_reading_the_file__0__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import FASTA.
/// </summary>
public static string SkylineWindow_ImportFastaFile_Import_FASTA {
get {
return ResourceManager.GetString("SkylineWindow_ImportFastaFile_Import_FASTA", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Skyline document data.
/// </summary>
public static string SkylineWindow_ImportFiles_Import_Skyline_document_data {
get {
return ResourceManager.GetString("SkylineWindow_ImportFiles_Import_Skyline_document_data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Importing {0}.
/// </summary>
public static string SkylineWindow_ImportFiles_Importing__0__ {
get {
return ResourceManager.GetString("SkylineWindow_ImportFiles_Importing__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} transitions contained errors..
/// </summary>
public static string SkylineWindow_ImportMassList__0__transitions_contained_errors_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList__0__transitions_contained_errors_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} transitions contained errors. Skip these {0} transitions and import the rest?.
/// </summary>
public static string SkylineWindow_ImportMassList__0__transitions_contained_errors__Skip_these__0__transitions_and_import_the_rest_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList__0__transitions_contained_errors__Skip_these__0__tra" +
"nsitions_and_import_the_rest_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Create....
/// </summary>
public static string SkylineWindow_ImportMassList__Create___ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList__Create___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Keep.
/// </summary>
public static string SkylineWindow_ImportMassList__Keep {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList__Keep", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Overwrite.
/// </summary>
public static string SkylineWindow_ImportMassList__Overwrite {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList__Overwrite", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Skip.
/// </summary>
public static string SkylineWindow_ImportMassList__Skip {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList__Skip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add.
/// </summary>
public static string SkylineWindow_ImportMassList_Add {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_Add", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding iRT values.
/// </summary>
public static string SkylineWindow_ImportMassList_Adding_iRT_values_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_Adding_iRT_values_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Analyzing input {0}.
/// </summary>
public static string SkylineWindow_ImportMassList_Analyzing_input__0_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_Analyzing_input__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed reading the file. Peptide {0} matches an existing iRT standard peptide..
/// </summary>
public static string SkylineWindow_ImportMassList_Failed_reading_the_file___Peptide__0__matches_an_existing_iRT_standard_peptide_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_Failed_reading_the_file___Peptide__0__matches_an_exi" +
"sting_iRT_standard_peptide_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Finishing up import.
/// </summary>
public static string SkylineWindow_ImportMassList_Finishing_up_import {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_Finishing_up_import", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Keep the existing iRT value or overwrite with the imported value?.
/// </summary>
public static string SkylineWindow_ImportMassList_Keep_the_existing_iRT_value_or_overwrite_with_the_imported_value_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_Keep_the_existing_iRT_value_or_overwrite_with_the_im" +
"ported_value_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Keep the existing iRT values or overwrite with imported values?.
/// </summary>
public static string SkylineWindow_ImportMassList_Keep_the_existing_iRT_values_or_overwrite_with_imported_values_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_Keep_the_existing_iRT_values_or_overwrite_with_impor" +
"ted_values_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file does not contain intensities. Valid column names for intensities are:.
/// </summary>
public static string SkylineWindow_ImportMassList_The_file_does_not_contain_intensities__Valid_column_names_for_intensities_are_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_The_file_does_not_contain_intensities__Valid_column_" +
"names_for_intensities_are_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file does not contain iRTs. Valid column names for iRTs are:.
/// </summary>
public static string SkylineWindow_ImportMassList_The_file_does_not_contain_iRTs__Valid_column_names_for_iRTs_are_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_The_file_does_not_contain_iRTs__Valid_column_names_f" +
"or_iRTs_are_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The iRT calculator already contains {0} of the imported peptides..
/// </summary>
public static string SkylineWindow_ImportMassList_The_iRT_calculator_already_contains__0__of_the_imported_peptides_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_The_iRT_calculator_already_contains__0__of_the_impor" +
"ted_peptides_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The transition list appears to contain iRT library values. Add these iRT values to the iRT calculator?.
/// </summary>
public static string SkylineWindow_ImportMassList_The_transition_list_appears_to_contain_iRT_library_values___Add_these_iRT_values_to_the_iRT_calculator_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_The_transition_list_appears_to_contain_iRT_library_v" +
"alues___Add_these_iRT_values_to_the_iRT_calculator_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The transition list appears to contain iRT values, but the document does not have an iRT calculator. Create a new calculator and add these iRT values?.
/// </summary>
public static string SkylineWindow_ImportMassList_The_transition_list_appears_to_contain_iRT_values__but_the_document_does_not_have_an_iRT_calculator___Create_a_new_calculator_and_add_these_iRT_values_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_The_transition_list_appears_to_contain_iRT_values__b" +
"ut_the_document_does_not_have_an_iRT_calculator___Create_a_new_calculator_and_ad" +
"d_these_iRT_values_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The transition list appears to contain spectral library intensities. Create a document library from these intensities?.
/// </summary>
public static string SkylineWindow_ImportMassList_The_transition_list_appears_to_contain_spectral_library_intensities___Create_a_document_library_from_these_intensities_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_The_transition_list_appears_to_contain_spectral_libr" +
"ary_intensities___Create_a_document_library_from_these_intensities_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There is an existing library with the same name {0} as the document library to be created. Overwrite this library or skip import of library intensities?.
/// </summary>
public static string SkylineWindow_ImportMassList_There_is_an_existing_library_with_the_same_name__0__as_the_document_library_to_be_created___Overwrite_this_library_or_skip_import_of_library_intensities_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_There_is_an_existing_library_with_the_same_name__0__" +
"as_the_document_library_to_be_created___Overwrite_this_library_or_skip_import_of" +
"_library_intensities_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected document change during operation: {0}.
/// </summary>
public static string SkylineWindow_ImportMassList_Unexpected_document_change_during_operation___0_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_Unexpected_document_change_during_operation___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must save the Skyline document in order to create a spectral library from a transition list..
/// </summary>
public static string SkylineWindow_ImportMassList_You_must_save_the_Skyline_document_in_order_to_create_a_spectral_library_from_a_transition_list_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassList_You_must_save_the_Skyline_document_in_order_to_creat" +
"e_a_spectral_library_from_a_transition_list_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Creating Spectral Library.
/// </summary>
public static string SkylineWindow_ImportMassListIntensities_Creating_Spectral_Library {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassListIntensities_Creating_Spectral_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The standard peptides do not appear to be on the iRT-C18 scale. Would you like to recalibrate them to this scale?.
/// </summary>
public static string SkylineWindow_ImportMassListIrts_The_standard_peptides_do_not_appear_to_be_on_the_iRT_C18_scale__Would_you_like_to_recalibrate_them_to_this_scale_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportMassListIrts_The_standard_peptides_do_not_appear_to_be_on_the" +
"_iRT_C18_scale__Would_you_like_to_recalibrate_them_to_this_scale_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data columns not found in first line..
/// </summary>
public static string SkylineWindow_importMassListMenuItem_Click_Data_columns_not_found_in_first_line {
get {
return ResourceManager.GetString("SkylineWindow_importMassListMenuItem_Click_Data_columns_not_found_in_first_line", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import transition list.
/// </summary>
public static string SkylineWindow_importMassListMenuItem_Click_Import_transition_list {
get {
return ResourceManager.GetString("SkylineWindow_importMassListMenuItem_Click_Import_transition_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Transition List.
/// </summary>
public static string SkylineWindow_importMassListMenuItem_Click_Import_Transition_List_title {
get {
return ResourceManager.GetString("SkylineWindow_importMassListMenuItem_Click_Import_Transition_List_title", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition List.
/// </summary>
public static string SkylineWindow_importMassListMenuItem_Click_Transition_List {
get {
return ResourceManager.GetString("SkylineWindow_importMassListMenuItem_Click_Transition_List", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Continue peak boundary import ignoring these files?.
/// </summary>
public static string SkylineWindow_ImportPeakBoundaries_Continue_peak_boundary_import_ignoring_these_files_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportPeakBoundaries_Continue_peak_boundary_import_ignoring_these_f" +
"iles_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Continue peak boundary import ignoring these peptides?.
/// </summary>
public static string SkylineWindow_ImportPeakBoundaries_Continue_peak_boundary_import_ignoring_these_peptides_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportPeakBoundaries_Continue_peak_boundary_import_ignoring_these_p" +
"eptides_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import Peak Boundaries.
/// </summary>
public static string SkylineWindow_ImportPeakBoundaries_Import_PeakBoundaries {
get {
return ResourceManager.GetString("SkylineWindow_ImportPeakBoundaries_Import_PeakBoundaries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following {0} file names in the peak boundaries file were not recognized:.
/// </summary>
public static string SkylineWindow_ImportPeakBoundaries_The_following__0__file_names_in_the_peak_boundaries_file_were_not_recognized_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportPeakBoundaries_The_following__0__file_names_in_the_peak_bound" +
"aries_file_were_not_recognized_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following {0} peptides in the peak boundaries file were not recognized:.
/// </summary>
public static string SkylineWindow_ImportPeakBoundaries_The_following__0__peptides_in_the_peak_boundaries_file_were_not_recognized__ {
get {
return ResourceManager.GetString("SkylineWindow_ImportPeakBoundaries_The_following__0__peptides_in_the_peak_boundar" +
"ies_file_were_not_recognized__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected Document Change During Operation..
/// </summary>
public static string SkylineWindow_ImportPeakBoundaries_Unexpected_document_change_during_operation {
get {
return ResourceManager.GetString("SkylineWindow_ImportPeakBoundaries_Unexpected_document_change_during_operation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed reading the file {0}..
/// </summary>
public static string SkylineWindow_ImportPeakBoundariesFile_Failed_reading_the_file__0__ {
get {
return ResourceManager.GetString("SkylineWindow_ImportPeakBoundariesFile_Failed_reading_the_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} decoys do not have a matching target.
/// </summary>
public static string SkylineWindow_ImportResults__0__decoys_do_not_have_a_matching_target {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults__0__decoys_do_not_have_a_matching_target", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} decoys do not have the same number of transitions as their matching targets.
/// </summary>
public static string SkylineWindow_ImportResults__0__decoys_do_not_have_the_same_number_of_transitions_as_their_matching_targets {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults__0__decoys_do_not_have_the_same_number_of_transitions" +
"_as_their_matching_targets", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 decoy does not have a matching target.
/// </summary>
public static string SkylineWindow_ImportResults_1_decoy_does_not_have_a_matching_target {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_1_decoy_does_not_have_a_matching_target", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 decoy does not have the same number of transitions as its matching target.
/// </summary>
public static string SkylineWindow_ImportResults_1_decoy_does_not_have_the_same_number_of_transitions_as_its_matching_target {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_1_decoy_does_not_have_the_same_number_of_transitions_" +
"as_its_matching_target", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A maximum of {0} may be missing or outliers for a successful import..
/// </summary>
public static string SkylineWindow_ImportResults_A_maximum_of__0__may_be_missing_and_or_outliers_for_a_successful_import_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_A_maximum_of__0__may_be_missing_and_or_outliers_for_a" +
"_successful_import_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A regression for declustering potention must be selected in the Prediction tab of the Transition Settings in order to import optimization data for decluserting potential..
/// </summary>
public static string SkylineWindow_ImportResults_A_regression_for_declustering_potention_must_be_selected_in_the_Prediction_tab_of_the_Transition_Settings_in_order_to_import_optimization_data_for_decluserting_potential {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_A_regression_for_declustering_potention_must_be_selec" +
"ted_in_the_Prediction_tab_of_the_Transition_Settings_in_order_to_import_optimiza" +
"tion_data_for_decluserting_potential", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add missing iRT standard peptides to your document or change the retention time predictor..
/// </summary>
public static string SkylineWindow_ImportResults_Add_missing_iRT_standard_peptides_to_your_document_or_change_the_retention_time_predictor_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_Add_missing_iRT_standard_peptides_to_your_document_or" +
"_change_the_retention_time_predictor_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure? Peak scoring models trained with non-matching targets and decoys may produce incorrect results..
/// </summary>
public static string SkylineWindow_ImportResults_Are_you_sure__Peak_scoring_models_trained_with_non_matching_targets_and_decoys_may_produce_incorrect_results_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_Are_you_sure__Peak_scoring_models_trained_with_non_ma" +
"tching_targets_and_decoys_may_produce_incorrect_results_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Continue.
/// </summary>
public static string SkylineWindow_ImportResults_Continue {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_Continue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to continue?.
/// </summary>
public static string SkylineWindow_ImportResults_Do_you_want_to_continue_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_Do_you_want_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to generate new decoys or continue with the current decoys?.
/// </summary>
public static string SkylineWindow_ImportResults_Do_you_want_to_generate_new_decoys_or_continue_with_the_current_decoys_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_Do_you_want_to_generate_new_decoys_or_continue_with_t" +
"he_current_decoys_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Generate.
/// </summary>
public static string SkylineWindow_ImportResults_Generate {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_Generate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import {0}.
/// </summary>
public static string SkylineWindow_ImportResults_Import__0__ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_Import__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import results.
/// </summary>
public static string SkylineWindow_ImportResults_Import_results {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_Import_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None may be missing or outliers for a successful import..
/// </summary>
public static string SkylineWindow_ImportResults_None_may_be_missing_or_outliers_for_a_successful_import_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_None_may_be_missing_or_outliers_for_a_successful_impo" +
"rt_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document contains {0} of these iRT standard peptides..
/// </summary>
public static string SkylineWindow_ImportResults_The_document_contains__0__of_these_iRT_standard_peptides_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_The_document_contains__0__of_these_iRT_standard_pepti" +
"des_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document contains a decoy that does not match the targets:.
/// </summary>
public static string SkylineWindow_ImportResults_The_document_contains_a_decoy_that_does_not_match_the_targets_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_The_document_contains_a_decoy_that_does_not_match_the" +
"_targets_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document contains decoys that do not match the targets. Out of {0} decoys:.
/// </summary>
public static string SkylineWindow_ImportResults_The_document_contains_decoys_that_do_not_match_the_targets__Out_of__0__decoys_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_The_document_contains_decoys_that_do_not_match_the_ta" +
"rgets__Out_of__0__decoys_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document does not contain any of these iRT standard peptides..
/// </summary>
public static string SkylineWindow_ImportResults_The_document_does_not_contain_any_of_these_iRT_standard_peptides_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_The_document_does_not_contain_any_of_these_iRT_standa" +
"rd_peptides_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document only contains {0} of these iRT standard peptides..
/// </summary>
public static string SkylineWindow_ImportResults_The_document_only_contains__0__of_these_iRT_standard_peptides_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_The_document_only_contains__0__of_these_iRT_standard_" +
"peptides_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The following iRT standard peptides are missing from the document:.
/// </summary>
public static string SkylineWindow_ImportResults_The_following_iRT_standard_peptides_are_missing_from_the_document_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_The_following_iRT_standard_peptides_are_missing_from_" +
"the_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to With {0} standard peptides, {1} are required with a correlation of {2}..
/// </summary>
public static string SkylineWindow_ImportResults_With__0__standard_peptides___1__are_required_with_a_correlation_of__2__ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_With__0__standard_peptides___1__are_required_with_a_c" +
"orrelation_of__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must add at least one target transition before importing results..
/// </summary>
public static string SkylineWindow_ImportResults_You_must_add_at_least_one_target_transition_before_importing_results_ {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_You_must_add_at_least_one_target_transition_before_im" +
"porting_results_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must save this document before importing results..
/// </summary>
public static string SkylineWindow_ImportResults_You_must_save_this_document_before_importing_results {
get {
return ResourceManager.GetString("SkylineWindow_ImportResults_You_must_save_this_document_before_importing_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Clear integrate all.
/// </summary>
public static string SkylineWindow_IntegrateAll_Clear_integrate_all {
get {
return ResourceManager.GetString("SkylineWindow_IntegrateAll_Clear_integrate_all", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Set integrate all.
/// </summary>
public static string SkylineWindow_IntegrateAll_Set_integrate_all {
get {
return ResourceManager.GetString("SkylineWindow_IntegrateAll_Set_integrate_all", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to In the Peptide Settings - Prediction tab, click the calculator button to edit the current iRT calculator..
/// </summary>
public static string SkylineWindow_irtStandardContextMenuItem_Click_In_the_Peptide_Settings___Prediction_tab__click_the_calculator_button_to_edit_the_current_iRT_calculator_ {
get {
return ResourceManager.GetString("SkylineWindow_irtStandardContextMenuItem_Click_In_the_Peptide_Settings___Predicti" +
"on_tab__click_the_calculator_button_to_edit_the_current_iRT_calculator_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The standard peptides for an iRT calculator can only be set in the iRT calculator editor..
/// </summary>
public static string SkylineWindow_irtStandardContextMenuItem_Click_The_standard_peptides_for_an_iRT_calculator_can_only_be_set_in_the_iRT_calculator_editor_ {
get {
return ResourceManager.GetString("SkylineWindow_irtStandardContextMenuItem_Click_The_standard_peptides_for_an_iRT_c" +
"alculator_can_only_be_set_in_the_iRT_calculator_editor_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Must be called from event thread.
/// </summary>
public static string SkylineWindow_IsGraphUpdatePending_Must_be_called_from_event_thread {
get {
return ResourceManager.GetString("SkylineWindow_IsGraphUpdatePending_Must_be_called_from_event_thread", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A failure occurred attempting to re-import results..
/// </summary>
public static string SkylineWindow_ManageResults_A_failure_occurred_attempting_to_reimport_results {
get {
return ResourceManager.GetString("SkylineWindow_ManageResults_A_failure_occurred_attempting_to_reimport_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to remove library runs from the document library..
/// </summary>
public static string SkylineWindow_ManageResults_Failed_to_remove_library_runs_from_the_document_library_ {
get {
return ResourceManager.GetString("SkylineWindow_ManageResults_Failed_to_remove_library_runs_from_the_document_libra" +
"ry_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to remove library runs from the MIDAS library..
/// </summary>
public static string SkylineWindow_ManageResults_Failed_to_remove_library_runs_from_the_MIDAS_library_ {
get {
return ResourceManager.GetString("SkylineWindow_ManageResults_Failed_to_remove_library_runs_from_the_MIDAS_library_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Manage results.
/// </summary>
public static string SkylineWindow_ManageResults_Manage_results {
get {
return ResourceManager.GetString("SkylineWindow_ManageResults_Manage_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must contain mass spec data to manage results..
/// </summary>
public static string SkylineWindow_ManageResults_The_document_must_contain_mass_spec_data_to_manage_results_ {
get {
return ResourceManager.GetString("SkylineWindow_ManageResults_The_document_must_contain_mass_spec_data_to_manage_re" +
"sults_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mark transitions non-quantitative.
/// </summary>
public static string SkylineWindow_MarkQuantitative_Mark_transitions_non_quantitative {
get {
return ResourceManager.GetString("SkylineWindow_MarkQuantitative_Mark_transitions_non_quantitative", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mark transitions quantitative.
/// </summary>
public static string SkylineWindow_MarkQuantitative_Mark_transitions_quantitative {
get {
return ResourceManager.GetString("SkylineWindow_MarkQuantitative_Mark_transitions_quantitative", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure attempting to modify the document..
/// </summary>
public static string SkylineWindow_ModifyDocument_Failure_attempting_to_modify_the_document {
get {
return ResourceManager.GetString("SkylineWindow_ModifyDocument_Failure_attempting_to_modify_the_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modify {0}.
/// </summary>
public static string SkylineWindow_ModifyPeptide_Modify__0__ {
get {
return ResourceManager.GetString("SkylineWindow_ModifyPeptide_Modify__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modify Molecule.
/// </summary>
public static string SkylineWindow_ModifyPeptide_Modify_Small_Molecule {
get {
return ResourceManager.GetString("SkylineWindow_ModifyPeptide_Modify_Small_Molecule", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modify Custom Ion Precursor.
/// </summary>
public static string SkylineWindow_ModifySmallMoleculeTransitionGroup_Modify_Custom_Ion_Precursor {
get {
return ResourceManager.GetString("SkylineWindow_ModifySmallMoleculeTransitionGroup_Modify_Custom_Ion_Precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modify product ion {0}.
/// </summary>
public static string SkylineWindow_ModifyTransition_Modify_product_ion__0_ {
get {
return ResourceManager.GetString("SkylineWindow_ModifyTransition_Modify_product_ion__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modify Transition.
/// </summary>
public static string SkylineWindow_ModifyTransition_Modify_Transition {
get {
return ResourceManager.GetString("SkylineWindow_ModifyTransition_Modify_Transition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An unexpected error has prevented global settings changes from this session from being saved..
/// </summary>
public static string SkylineWindow_OnClosing_An_unexpected_error_has_prevented_global_settings_changes_from_this_session_from_being_saved {
get {
return ResourceManager.GetString("SkylineWindow_OnClosing_An_unexpected_error_has_prevented_global_settings_changes" +
"_from_this_session_from_being_saved", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure opening {0}..
/// </summary>
public static string SkylineWindow_OpenFile_Failure_opening__0__ {
get {
return ResourceManager.GetString("SkylineWindow_OpenFile_Failure_opening__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading....
/// </summary>
public static string SkylineWindow_OpenFile_Loading___ {
get {
return ResourceManager.GetString("SkylineWindow_OpenFile_Loading___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file you are trying to open ("{0}") does not appear to be a Skyline document. Skyline documents normally have a "{1}" or "{2}" filename extension and are in XML format..
/// </summary>
public static string SkylineWindow_OpenFile_The_file_you_are_trying_to_open____0____does_not_appear_to_be_a_Skyline_document__Skyline_documents_normally_have_a___1___or___2___filename_extension_and_are_in_XML_format_ {
get {
return ResourceManager.GetString("SkylineWindow_OpenFile_The_file_you_are_trying_to_open____0____does_not_appear_to" +
"_be_a_Skyline_document__Skyline_documents_normally_have_a___1___or___2___filenam" +
"e_extension_and_are_in_XML_format_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Extracting Files.
/// </summary>
public static string SkylineWindow_OpenSharedFile_Extracting_Files {
get {
return ResourceManager.GetString("SkylineWindow_OpenSharedFile_Extracting_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure extracting Skyline document from zip file {0}..
/// </summary>
public static string SkylineWindow_OpenSharedFile_Failure_extracting_Skyline_document_from_zip_file__0__ {
get {
return ResourceManager.GetString("SkylineWindow_OpenSharedFile_Failure_extracting_Skyline_document_from_zip_file__0" +
"__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The zip file {0} cannot be read..
/// </summary>
public static string SkylineWindow_OpenSharedFile_The_zip_file__0__cannot_be_read {
get {
return ResourceManager.GetString("SkylineWindow_OpenSharedFile_The_zip_file__0__cannot_be_read", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not perform transition list paste: {0}.
/// </summary>
public static string SkylineWindow_Paste_Could_not_perform_transition_list_paste___0_ {
get {
return ResourceManager.GetString("SkylineWindow_Paste_Could_not_perform_transition_list_paste___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Empty sequence found at line {0}..
/// </summary>
public static string SkylineWindow_Paste_Empty_sequence_found_at_line__0__ {
get {
return ResourceManager.GetString("SkylineWindow_Paste_Empty_sequence_found_at_line__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed reading Skyline document from the clipboard..
/// </summary>
public static string SkylineWindow_Paste_Failed_reading_Skyline_document_from_the_clipboard_ {
get {
return ResourceManager.GetString("SkylineWindow_Paste_Failed_reading_Skyline_document_from_the_clipboard_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Paste.
/// </summary>
public static string SkylineWindow_Paste_Paste {
get {
return ResourceManager.GetString("SkylineWindow_Paste_Paste", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Paste {0}.
/// </summary>
public static string SkylineWindow_Paste_Paste__0__ {
get {
return ResourceManager.GetString("SkylineWindow_Paste_Paste__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Paste FASTA.
/// </summary>
public static string SkylineWindow_Paste_Paste_FASTA {
get {
return ResourceManager.GetString("SkylineWindow_Paste_Paste_FASTA", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Paste peptide list.
/// </summary>
public static string SkylineWindow_Paste_Paste_peptide_list {
get {
return ResourceManager.GetString("SkylineWindow_Paste_Paste_peptide_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Paste proteins.
/// </summary>
public static string SkylineWindow_Paste_Paste_proteins {
get {
return ResourceManager.GetString("SkylineWindow_Paste_Paste_proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Paste transition list.
/// </summary>
public static string SkylineWindow_Paste_Paste_transition_list {
get {
return ResourceManager.GetString("SkylineWindow_Paste_Paste_transition_list", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to peptides.
/// </summary>
public static string SkylineWindow_Paste_peptides {
get {
return ResourceManager.GetString("SkylineWindow_Paste_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Protein sequence not found..
/// </summary>
public static string SkylineWindow_Paste_Protein_sequence_not_found {
get {
return ResourceManager.GetString("SkylineWindow_Paste_Protein_sequence_not_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to proteins.
/// </summary>
public static string SkylineWindow_Paste_proteins {
get {
return ResourceManager.GetString("SkylineWindow_Paste_proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The protein sequence must be the last value in each line..
/// </summary>
public static string SkylineWindow_Paste_The_protein_sequence_must_be_the_last_value_in_each_line {
get {
return ResourceManager.GetString("SkylineWindow_Paste_The_protein_sequence_must_be_the_last_value_in_each_line", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected character '.' found..
/// </summary>
public static string SkylineWindow_Paste_Unexpected_character_period_found {
get {
return ResourceManager.GetString("SkylineWindow_Paste_Unexpected_character_period_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Apply picked peak.
/// </summary>
public static string SkylineWindow_PickPeakInChromatograms_Apply_picked_peak {
get {
return ResourceManager.GetString("SkylineWindow_PickPeakInChromatograms_Apply_picked_peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error retrieving server information: {0}.
/// </summary>
public static string SkylineWindow_Publish_Error_retrieving_server_information__0__ {
get {
return ResourceManager.GetString("SkylineWindow_Publish_Error_retrieving_server_information__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retrieving server information..
/// </summary>
public static string SkylineWindow_Publish_Retrieving_server_information {
get {
return ResourceManager.GetString("SkylineWindow_Publish_Retrieving_server_information", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There are no Panorama servers to publish to. Please add a server under Tools..
/// </summary>
public static string SkylineWindow_Publish_There_are_no_Panorama_servers_to_publish_to_Please_add_a_server_under_Tools {
get {
return ResourceManager.GetString("SkylineWindow_Publish_There_are_no_Panorama_servers_to_publish_to_Please_add_a_se" +
"rver_under_Tools", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline Shared Documents.
/// </summary>
public static string SkylineWindow_publishToolStripMenuItem_Click_Skyline_Shared_Documents {
get {
return ResourceManager.GetString("SkylineWindow_publishToolStripMenuItem_Click_Skyline_Shared_Documents", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This file was last uploaded to: {0}.
/// </summary>
public static string SkylineWindow_PublishToSavedUri_This_file_was_last_uploaded_to___0_ {
get {
return ResourceManager.GetString("SkylineWindow_PublishToSavedUri_This_file_was_last_uploaded_to___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Upload to the same location?.
/// </summary>
public static string SkylineWindow_PublishToSavedUri_Upload_to_the_same_location_ {
get {
return ResourceManager.GetString("SkylineWindow_PublishToSavedUri_Upload_to_the_same_location_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reimporting chromatograms.
/// </summary>
public static string SkylineWindow_ReimportChromatograms_Reimporting_chromatograms {
get {
return ResourceManager.GetString("SkylineWindow_ReimportChromatograms_Reimporting_chromatograms", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove peptides above CV cutoff.
/// </summary>
public static string SkylineWindow_RemoveAboveCVCutoff_Remove_peptides_above_CV_cutoff {
get {
return ResourceManager.GetString("SkylineWindow_RemoveAboveCVCutoff_Remove_peptides_above_CV_cutoff", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove duplicate peptides.
/// </summary>
public static string SkylineWindow_removeDuplicatePeptidesMenuItem_Click_Remove_duplicate_peptides {
get {
return ResourceManager.GetString("SkylineWindow_removeDuplicatePeptidesMenuItem_Click_Remove_duplicate_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove empty peptides.
/// </summary>
public static string SkylineWindow_removeEmptyPeptidesMenuItem_Click_Remove_empty_peptides {
get {
return ResourceManager.GetString("SkylineWindow_removeEmptyPeptidesMenuItem_Click_Remove_empty_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove empty proteins.
/// </summary>
public static string SkylineWindow_removeEmptyProteinsMenuItem_Click_Remove_empty_proteins {
get {
return ResourceManager.GetString("SkylineWindow_removeEmptyProteinsMenuItem_Click_Remove_empty_proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove missing results.
/// </summary>
public static string SkylineWindow_RemoveMissingResults_Remove_missing_results {
get {
return ResourceManager.GetString("SkylineWindow_RemoveMissingResults_Remove_missing_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove all peaks from {0}.
/// </summary>
public static string SkylineWindow_RemovePeak_Remove_all_peaks_from__0__ {
get {
return ResourceManager.GetString("SkylineWindow_RemovePeak_Remove_all_peaks_from__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove peak from {0}.
/// </summary>
public static string SkylineWindow_RemovePeak_Remove_peak_from__0__ {
get {
return ResourceManager.GetString("SkylineWindow_RemovePeak_Remove_peak_from__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove all peaks from {0}.
/// </summary>
public static string SkylineWindow_removePeakContextMenuItem_Click_Remove_all_peaks_from__0_ {
get {
return ResourceManager.GetString("SkylineWindow_removePeakContextMenuItem_Click_Remove_all_peaks_from__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All.
/// </summary>
public static string SkylineWindow_removePeaksGraphMenuItem_DropDownOpening_All {
get {
return ResourceManager.GetString("SkylineWindow_removePeaksGraphMenuItem_DropDownOpening_All", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove repeated peptides.
/// </summary>
public static string SkylineWindow_removeRepeatedPeptidesMenuItem_Click_Remove_repeated_peptides {
get {
return ResourceManager.GetString("SkylineWindow_removeRepeatedPeptidesMenuItem_Click_Remove_repeated_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove retention time outliers.
/// </summary>
public static string SkylineWindow_RemoveRTOutliers_Remove_retention_time_outliers {
get {
return ResourceManager.GetString("SkylineWindow_RemoveRTOutliers_Remove_retention_time_outliers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reset default settings.
/// </summary>
public static string SkylineWindow_ResetDefaultSettings_Reset_default_settings {
get {
return ResourceManager.GetString("SkylineWindow_ResetDefaultSettings_Reset_default_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to restore document.
/// </summary>
public static string SkylineWindow_RestoreDocument_Failed_to_restore_document {
get {
return ResourceManager.GetString("SkylineWindow_RestoreDocument_Failed_to_restore_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed writing to {0}..
/// </summary>
public static string SkylineWindow_SaveDocument_Failed_writing_to__0__ {
get {
return ResourceManager.GetString("SkylineWindow_SaveDocument_Failed_writing_to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Optimizing data file....
/// </summary>
public static string SkylineWindow_SaveDocument_Optimizing_data_file___ {
get {
return ResourceManager.GetString("SkylineWindow_SaveDocument_Optimizing_data_file___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Saving....
/// </summary>
public static string SkylineWindow_SaveDocument_Saving___ {
get {
return ResourceManager.GetString("SkylineWindow_SaveDocument_Saving___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline Documents.
/// </summary>
public static string SkylineWindow_SaveDocumentAs_Skyline_Documents {
get {
return ResourceManager.GetString("SkylineWindow_SaveDocumentAs_Skyline_Documents", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must be fully loaded before it can be saved to a new name..
/// </summary>
public static string SkylineWindow_SaveDocumentAs_The_document_must_be_fully_loaded_before_it_can_be_saved_to_a_new_name {
get {
return ResourceManager.GetString("SkylineWindow_SaveDocumentAs_The_document_must_be_fully_loaded_before_it_can_be_s" +
"aved_to_a_new_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Name settings.
/// </summary>
public static string SkylineWindow_SaveSettings_Name_settings {
get {
return ResourceManager.GetString("SkylineWindow_SaveSettings_Name_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Would you like to use the Unimod definitions for the following modifications?.
/// </summary>
public static string SkylineWindow_sequenceTree_AfterLabelEdit_Would_you_like_to_use_the_Unimod_definitions_for_the_following_modifications {
get {
return ResourceManager.GetString("SkylineWindow_sequenceTree_AfterLabelEdit_Would_you_like_to_use_the_Unimod_defini" +
"tions_for_the_following_modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add {0}.
/// </summary>
public static string SkylineWindow_sequenceTree_AfterNodeEdit_Add__0__ {
get {
return ResourceManager.GetString("SkylineWindow_sequenceTree_AfterNodeEdit_Add__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit name {0}.
/// </summary>
public static string SkylineWindow_sequenceTree_AfterNodeEdit_Edit_name__0__ {
get {
return ResourceManager.GetString("SkylineWindow_sequenceTree_AfterNodeEdit_Edit_name__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Drag and drop.
/// </summary>
public static string SkylineWindow_sequenceTree_DragDrop_Drag_and_drop {
get {
return ResourceManager.GetString("SkylineWindow_sequenceTree_DragDrop_Drag_and_drop", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Pick {0}.
/// </summary>
public static string SkylineWindow_sequenceTree_PickedChildrenEvent_Pick__0__ {
get {
return ResourceManager.GetString("SkylineWindow_sequenceTree_PickedChildrenEvent_Pick__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Clear standard type.
/// </summary>
public static string SkylineWindow_SetStandardType_Clear_standard_type {
get {
return ResourceManager.GetString("SkylineWindow_SetStandardType_Clear_standard_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Set standard type to {0}.
/// </summary>
public static string SkylineWindow_SetStandardType_Set_standard_type_to__0_ {
get {
return ResourceManager.GetString("SkylineWindow_SetStandardType_Set_standard_type_to__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Auto.
/// </summary>
public static string SkylineWindow_SetupCalculatorChooser_Auto {
get {
return ResourceManager.GetString("SkylineWindow_SetupCalculatorChooser_Auto", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Compressing Files.
/// </summary>
public static string SkylineWindow_ShareDocument_Compressing_Files {
get {
return ResourceManager.GetString("SkylineWindow_ShareDocument_Compressing_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed attempting to create sharing file {0}..
/// </summary>
public static string SkylineWindow_ShareDocument_Failed_attempting_to_create_sharing_file__0__ {
get {
return ResourceManager.GetString("SkylineWindow_ShareDocument_Failed_attempting_to_create_sharing_file__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Share Document.
/// </summary>
public static string SkylineWindow_shareDocumentMenuItem_Click_Share_Document {
get {
return ResourceManager.GetString("SkylineWindow_shareDocumentMenuItem_Click_Share_Document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline Shared Documents.
/// </summary>
public static string SkylineWindow_shareDocumentMenuItem_Click_Skyline_Shared_Documents {
get {
return ResourceManager.GetString("SkylineWindow_shareDocumentMenuItem_Click_Skyline_Shared_Documents", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must be fully loaded before it can be shared..
/// </summary>
public static string SkylineWindow_shareDocumentMenuItem_Click_The_document_must_be_fully_loaded_before_it_can_be_shared {
get {
return ResourceManager.GetString("SkylineWindow_shareDocumentMenuItem_Click_The_document_must_be_fully_loaded_befor" +
"e_it_can_be_shared", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must be saved before it can be shared..
/// </summary>
public static string SkylineWindow_shareDocumentMenuItem_Click_The_document_must_be_saved_before_it_can_be_shared {
get {
return ResourceManager.GetString("SkylineWindow_shareDocumentMenuItem_Click_The_document_must_be_saved_before_it_ca" +
"n_be_shared", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Show {0} Score.
/// </summary>
public static string SkylineWindow_ShowCalculatorScoreFormat {
get {
return ResourceManager.GetString("SkylineWindow_ShowCalculatorScoreFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must have imported results..
/// </summary>
public static string SkylineWindow_ShowChromatogramFeaturesDialog_The_document_must_have_imported_results_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowChromatogramFeaturesDialog_The_document_must_have_imported_resu" +
"lts_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must have targets for which to export chromatograms..
/// </summary>
public static string SkylineWindow_ShowChromatogramFeaturesDialog_The_document_must_have_targets_for_which_to_export_chromatograms_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowChromatogramFeaturesDialog_The_document_must_have_targets_for_w" +
"hich_to_export_chromatograms_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must be fully loaded in order to compare model peak picking..
/// </summary>
public static string SkylineWindow_ShowCompareModelsDlg_The_document_must_be_fully_loaded_in_order_to_compare_model_peak_picking_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowCompareModelsDlg_The_document_must_be_fully_loaded_in_order_to_" +
"compare_model_peak_picking_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must have targets in order to compare model peak picking..
/// </summary>
public static string SkylineWindow_ShowCompareModelsDlg_The_document_must_have_targets_in_order_to_compare_model_peak_picking_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowCompareModelsDlg_The_document_must_have_targets_in_order_to_com" +
"pare_model_peak_picking_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change document settings.
/// </summary>
public static string SkylineWindow_ShowDocumentSettingsDialog_Change_document_settings {
get {
return ResourceManager.GetString("SkylineWindow_ShowDocumentSettingsDialog_Change_document_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Update {0} calculator.
/// </summary>
public static string SkylineWindow_ShowEditCalculatorDlg_Update__0__calculator {
get {
return ResourceManager.GetString("SkylineWindow_ShowEditCalculatorDlg_Update__0__calculator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ESP Feature Files.
/// </summary>
public static string SkylineWindow_ShowExportEspFeaturesDialog_ESP_Feature_Files {
get {
return ResourceManager.GetString("SkylineWindow_ShowExportEspFeaturesDialog_ESP_Feature_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Export ESP Features.
/// </summary>
public static string SkylineWindow_ShowExportEspFeaturesDialog_Export_ESP_Features {
get {
return ResourceManager.GetString("SkylineWindow_ShowExportEspFeaturesDialog_Export_ESP_Features", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed attempting to save ESP features to {0}..
/// </summary>
public static string SkylineWindow_ShowExportEspFeaturesDialog_Failed_attempting_to_save_ESP_features_to__0__ {
get {
return ResourceManager.GetString("SkylineWindow_ShowExportEspFeaturesDialog_Failed_attempting_to_save_ESP_features_" +
"to__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must contain targets for which to export features..
/// </summary>
public static string SkylineWindow_ShowExportEspFeaturesDialog_The_document_must_contain_targets_for_which_to_export_features_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowExportEspFeaturesDialog_The_document_must_contain_targets_for_w" +
"hich_to_export_features_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Export Spectral Library.
/// </summary>
public static string SkylineWindow_ShowExportSpectralLibraryDialog_Export_Spectral_Library {
get {
return ResourceManager.GetString("SkylineWindow_ShowExportSpectralLibraryDialog_Export_Spectral_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exporting spectral library {0}....
/// </summary>
public static string SkylineWindow_ShowExportSpectralLibraryDialog_Exporting_spectral_library__0____ {
get {
return ResourceManager.GetString("SkylineWindow_ShowExportSpectralLibraryDialog_Exporting_spectral_library__0____", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed exporting spectral library to {0}..
/// </summary>
public static string SkylineWindow_ShowExportSpectralLibraryDialog_Failed_exporting_spectral_library_to__0__ {
get {
return ResourceManager.GetString("SkylineWindow_ShowExportSpectralLibraryDialog_Failed_exporting_spectral_library_t" +
"o__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must contain at least one peptide precursor to export a spectral library..
/// </summary>
public static string SkylineWindow_ShowExportSpectralLibraryDialog_The_document_must_contain_at_least_one_peptide_precursor_to_export_a_spectral_library_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowExportSpectralLibraryDialog_The_document_must_contain_at_least_" +
"one_peptide_precursor_to_export_a_spectral_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must contain results to export a spectral library..
/// </summary>
public static string SkylineWindow_ShowExportSpectralLibraryDialog_The_document_must_contain_results_to_export_a_spectral_library_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowExportSpectralLibraryDialog_The_document_must_contain_results_t" +
"o_export_a_spectral_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Generate Decoys.
/// </summary>
public static string SkylineWindow_ShowGenerateDecoysDlg_Generate_Decoys {
get {
return ResourceManager.GetString("SkylineWindow_ShowGenerateDecoysDlg_Generate_Decoys", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must be fully loaded before importing a peptide search..
/// </summary>
public static string SkylineWindow_ShowImportPeptideSearchDlg_The_document_must_be_fully_loaded_before_importing_a_peptide_search_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowImportPeptideSearchDlg_The_document_must_be_fully_loaded_before" +
"_importing_a_peptide_search_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must save this document before importing a peptide search..
/// </summary>
public static string SkylineWindow_ShowImportPeptideSearchDlg_You_must_save_this_document_before_importing_a_peptide_search_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowImportPeptideSearchDlg_You_must_save_this_document_before_impor" +
"ting_a_peptide_search_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must contain targets for which to export features..
/// </summary>
public static string SkylineWindow_ShowMProphetFeaturesDialog_The_document_must_contain_targets_for_which_to_export_features_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowMProphetFeaturesDialog_The_document_must_contain_targets_for_wh" +
"ich_to_export_features_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must have imported results..
/// </summary>
public static string SkylineWindow_ShowMProphetFeaturesDialog_The_document_must_have_imported_results_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowMProphetFeaturesDialog_The_document_must_have_imported_results_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Do you want to continue?.
/// </summary>
public static string SkylineWindow_ShowProgressErrorUI_Do_you_want_to_continue_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowProgressErrorUI_Do_you_want_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retry.
/// </summary>
public static string SkylineWindow_ShowProgressErrorUI_Retry {
get {
return ResourceManager.GetString("SkylineWindow_ShowProgressErrorUI_Retry", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skip.
/// </summary>
public static string SkylineWindow_ShowProgressErrorUI_Skip {
get {
return ResourceManager.GetString("SkylineWindow_ShowProgressErrorUI_Skip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Continue.
/// </summary>
public static string SkylineWindow_ShowPublishDlg_Continue {
get {
return ResourceManager.GetString("SkylineWindow_ShowPublishDlg_Continue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Press Continue to use the server of your choice..
/// </summary>
public static string SkylineWindow_ShowPublishDlg_Press_Continue_to_use_the_server_of_your_choice_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowPublishDlg_Press_Continue_to_use_the_server_of_your_choice_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Press Register to register for a project on PanoramaWeb..
/// </summary>
public static string SkylineWindow_ShowPublishDlg_Press_Register_to_register_for_a_project_on_PanoramaWeb_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowPublishDlg_Press_Register_to_register_for_a_project_on_Panorama" +
"Web_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Register.
/// </summary>
public static string SkylineWindow_ShowPublishDlg_Register {
get {
return ResourceManager.GetString("SkylineWindow_ShowPublishDlg_Register", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must be fully loaded before it can be uploaded..
/// </summary>
public static string SkylineWindow_ShowPublishDlg_The_document_must_be_fully_loaded_before_it_can_be_uploaded_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowPublishDlg_The_document_must_be_fully_loaded_before_it_can_be_u" +
"ploaded_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must be saved before it can be uploaded..
/// </summary>
public static string SkylineWindow_ShowPublishDlg_The_document_must_be_saved_before_it_can_be_uploaded_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowPublishDlg_The_document_must_be_saved_before_it_can_be_uploaded" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There are no Panorama servers to upload to.
/// </summary>
public static string SkylineWindow_ShowPublishDlg_There_are_no_Panorama_servers_to_upload_to {
get {
return ResourceManager.GetString("SkylineWindow_ShowPublishDlg_There_are_no_Panorama_servers_to_upload_to", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Refine.
/// </summary>
public static string SkylineWindow_ShowRefineDlg_Refine {
get {
return ResourceManager.GetString("SkylineWindow_ShowRefineDlg_Refine", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Refining document.
/// </summary>
public static string SkylineWindow_ShowRefineDlg_Refining_document {
get {
return ResourceManager.GetString("SkylineWindow_ShowRefineDlg_Refining_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reintegrate peaks.
/// </summary>
public static string SkylineWindow_ShowReintegrateDialog_Reintegrate_peaks {
get {
return ResourceManager.GetString("SkylineWindow_ShowReintegrateDialog_Reintegrate_peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reintegration of results requires a trained peak scoring model..
/// </summary>
public static string SkylineWindow_ShowReintegrateDialog_Reintegration_of_results_requires_a_trained_peak_scoring_model_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowReintegrateDialog_Reintegration_of_results_requires_a_trained_p" +
"eak_scoring_model_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must be fully loaded before it can be re-integrated..
/// </summary>
public static string SkylineWindow_ShowReintegrateDialog_The_document_must_be_fully_loaded_before_it_can_be_re_integrated_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowReintegrateDialog_The_document_must_be_fully_loaded_before_it_c" +
"an_be_re_integrated_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must have imported results..
/// </summary>
public static string SkylineWindow_ShowReintegrateDialog_The_document_must_have_imported_results_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowReintegrateDialog_The_document_must_have_imported_results_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document must have targets in order to reintegrate chromatograms..
/// </summary>
public static string SkylineWindow_ShowReintegrateDialog_The_document_must_have_targets_in_order_to_reintegrate_chromatograms_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowReintegrateDialog_The_document_must_have_targets_in_order_to_re" +
"integrate_chromatograms_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected document change during operation..
/// </summary>
public static string SkylineWindow_ShowReintegrateDialog_Unexpected_document_change_during_operation_ {
get {
return ResourceManager.GetString("SkylineWindow_ShowReintegrateDialog_Unexpected_document_change_during_operation_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Rename proteins.
/// </summary>
public static string SkylineWindow_ShowRenameProteinsDlg_Rename_proteins {
get {
return ResourceManager.GetString("SkylineWindow_ShowRenameProteinsDlg_Rename_proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Choose a background proteome in the Digestions tab of the Peptide Settings..
/// </summary>
public static string SkylineWindow_ShowUniquePeptidesDlg_Choose_a_background_proteome_in_the_Digestions_tab_of_the_Peptide_Settings {
get {
return ResourceManager.GetString("SkylineWindow_ShowUniquePeptidesDlg_Choose_a_background_proteome_in_the_Digestion" +
"s_tab_of_the_Peptide_Settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Inspecting peptide uniqueness requires a background proteome..
/// </summary>
public static string SkylineWindow_ShowUniquePeptidesDlg_Inspecting_peptide_uniqueness_requires_a_background_proteome {
get {
return ResourceManager.GetString("SkylineWindow_ShowUniquePeptidesDlg_Inspecting_peptide_uniqueness_requires_a_back" +
"ground_proteome", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid file specified..
/// </summary>
public static string SkylineWindow_SkylineWindow_Invalid_file_specified {
get {
return ResourceManager.GetString("SkylineWindow_SkylineWindow_Invalid_file_specified", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Must have a window handle to begin processing..
/// </summary>
public static string SkylineWindow_SkylineWindow_Must_have_a_window_handle_to_begin_processing {
get {
return ResourceManager.GetString("SkylineWindow_SkylineWindow_Must_have_a_window_handle_to_begin_processing", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The URI {0} is not a file..
/// </summary>
public static string SkylineWindow_SkylineWindow_The_URI__0__is_not_a_file {
get {
return ResourceManager.GetString("SkylineWindow_SkylineWindow_The_URI__0__is_not_a_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sort proteins by accession.
/// </summary>
public static string SkylineWindow_sortProteinsByAccessionToolStripMenuItem_Click_Sort_proteins_by_accession {
get {
return ResourceManager.GetString("SkylineWindow_sortProteinsByAccessionToolStripMenuItem_Click_Sort_proteins_by_acc" +
"ession", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sort proteins by gene.
/// </summary>
public static string SkylineWindow_sortProteinsByGeneToolStripMenuItem_Click_Sort_proteins_by_gene {
get {
return ResourceManager.GetString("SkylineWindow_sortProteinsByGeneToolStripMenuItem_Click_Sort_proteins_by_gene", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sort proteins by preferred name.
/// </summary>
public static string SkylineWindow_sortProteinsByPreferredNameToolStripMenuItem_Click_Sort_proteins_by_preferred_name {
get {
return ResourceManager.GetString("SkylineWindow_sortProteinsByPreferredNameToolStripMenuItem_Click_Sort_proteins_by" +
"_preferred_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sort proteins by name.
/// </summary>
public static string SkylineWindow_sortProteinsMenuItem_Click_Sort_proteins_by_name {
get {
return ResourceManager.GetString("SkylineWindow_sortProteinsMenuItem_Click_Sort_proteins_by_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Showing targets at 1% FDR will set the replicate display type to single. Do you want to continue?.
/// </summary>
public static string SkylineWindow_targetsAt1FDRToolStripMenuItem_Click_Showing_targets_at_1__FDR_will_set_the_replicate_display_type_to_single__Do_you_want_to_continue_ {
get {
return ResourceManager.GetString("SkylineWindow_targetsAt1FDRToolStripMenuItem_Click_Showing_targets_at_1__FDR_will" +
"_set_the_replicate_display_type_to_single__Do_you_want_to_continue_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected character '{0}' found on line {1}..
/// </summary>
public static string SkylineWindow_Unexpected_character__0__found_on_line__1__ {
get {
return ResourceManager.GetString("SkylineWindow_Unexpected_character__0__found_on_line__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Targets.
/// </summary>
public static string SkylineWindow_UpdateAreaPointsTypeMenuItems_Targets {
get {
return ResourceManager.GetString("SkylineWindow_UpdateAreaPointsTypeMenuItems_Targets", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Targets at {0}% FDR.
/// </summary>
public static string SkylineWindow_UpdateAreaPointsTypeMenuItems_Targets_at__0___FDR {
get {
return ResourceManager.GetString("SkylineWindow_UpdateAreaPointsTypeMenuItems_Targets_at__0___FDR", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure attempting to load the window layout file {0}..
/// </summary>
public static string SkylineWindow_UpdateGraphUI_Failure_attempting_to_load_the_window_layout_file__0__ {
get {
return ResourceManager.GetString("SkylineWindow_UpdateGraphUI_Failure_attempting_to_load_the_window_layout_file__0_" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Rename or delete this file to restore the default layout..
/// </summary>
public static string SkylineWindow_UpdateGraphUI_Rename_or_delete_this_file_to_restore_the_default_layout {
get {
return ResourceManager.GetString("SkylineWindow_UpdateGraphUI_Rename_or_delete_this_file_to_restore_the_default_lay" +
"out", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline may also need to be restarted..
/// </summary>
public static string SkylineWindow_UpdateGraphUI_Skyline_may_also_need_to_be_restarted {
get {
return ResourceManager.GetString("SkylineWindow_UpdateGraphUI_Skyline_may_also_need_to_be_restarted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ready.
/// </summary>
public static string SkylineWindow_UpdateProgressUI_Ready {
get {
return ResourceManager.GetString("SkylineWindow_UpdateProgressUI_Ready", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No libraries to show. Would you like to add a library?.
/// </summary>
public static string SkylineWindow_ViewSpectralLibraries_No_libraries_to_show_Would_you_like_to_add_a_library {
get {
return ResourceManager.GetString("SkylineWindow_ViewSpectralLibraries_No_libraries_to_show_Would_you_like_to_add_a_" +
"library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline Document Pointer.
/// </summary>
public static string SkypFile_FILTER_SKYP_Skyline_Document_Pointer {
get {
return ResourceManager.GetString("SkypFile_FILTER_SKYP_Skyline_Document_Pointer", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Name of shared Skyline archive cannot be null or empty..
/// </summary>
public static string SkypFile_GetNonExistentPath_Name_of_shared_Skyline_archive_cannot_be_null_or_empty_ {
get {
return ResourceManager.GetString("SkypFile_GetNonExistentPath_Name_of_shared_Skyline_archive_cannot_be_null_or_empt" +
"y_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} is not a valid URL on a Panorama server..
/// </summary>
public static string SkypFile_GetSkyFileUrl__0__is_not_a_valid_URL_on_a_Panorama_server_ {
get {
return ResourceManager.GetString("SkypFile_GetSkyFileUrl__0__is_not_a_valid_URL_on_a_Panorama_server_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Expected the URL of a shared Skyline document archive ({0}) in the skyp file. Found {1} instead..
/// </summary>
public static string SkypFile_GetSkyFileUrl_Expected_the_URL_of_a_shared_Skyline_document_archive___0___in_the_skyp_file__Found__1__instead_ {
get {
return ResourceManager.GetString("SkypFile_GetSkyFileUrl_Expected_the_URL_of_a_shared_Skyline_document_archive___0_" +
"__in_the_skyp_file__Found__1__instead_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File does not contain the URL of a shared Skyline archive file ({0}) on a Panorama server..
/// </summary>
public static string SkypFile_GetSkyFileUrl_File_does_not_contain_the_URL_of_a_shared_Skyline_archive_file___0___on_a_Panorama_server_ {
get {
return ResourceManager.GetString("SkypFile_GetSkyFileUrl_File_does_not_contain_the_URL_of_a_shared_Skyline_archive_" +
"file___0___on_a_Panorama_server_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading {0}.
/// </summary>
public static string SkypSupport_Download_Downloading__0_ {
get {
return ResourceManager.GetString("SkypSupport_Download_Downloading__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There was an error downloading the Skyline document specified in the skyp file: {0}..
/// </summary>
public static string SkypSupport_Download_There_was_an_error_downloading_the_Skyline_document_specified_in_the_skyp_file___0__ {
get {
return ResourceManager.GetString("SkypSupport_Download_There_was_an_error_downloading_the_Skyline_document_specifie" +
"d_in_the_skyp_file___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You do not have permissions to download this file from {0}..
/// </summary>
public static string SkypSupport_Download_You_do_not_have_permissions_to_download_this_file_from__0__ {
get {
return ResourceManager.GetString("SkypSupport_Download_You_do_not_have_permissions_to_download_this_file_from__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You may have to add {0} as a Panorama server from the Tools > Options menu in Skyline..
/// </summary>
public static string SkypSupport_Download_You_may_have_to_add__0__as_a_Panorama_server_from_the_Tools___Options_menu_in_Skyline_ {
get {
return ResourceManager.GetString("SkypSupport_Download_You_may_have_to_add__0__as_a_Panorama_server_from_the_Tools_" +
"__Options_menu_in_Skyline_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading Skyline Document Archive.
/// </summary>
public static string SkypSupport_Open_Downloading_Skyline_Document_Archive {
get {
return ResourceManager.GetString("SkypSupport_Open_Downloading_Skyline_Document_Archive", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure opening skyp file..
/// </summary>
public static string SkypSupport_Open_Failure_opening_skyp_file_ {
get {
return ResourceManager.GetString("SkypSupport_Open_Failure_opening_skyp_file_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Average mass.
/// </summary>
public static string SmallMoleculeLibraryAttributes_KeyValuePairs_Average_mass {
get {
return ResourceManager.GetString("SmallMoleculeLibraryAttributes_KeyValuePairs_Average_mass", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Formula.
/// </summary>
public static string SmallMoleculeLibraryAttributes_KeyValuePairs_Formula {
get {
return ResourceManager.GetString("SmallMoleculeLibraryAttributes_KeyValuePairs_Formula", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to InChIKey.
/// </summary>
public static string SmallMoleculeLibraryAttributes_KeyValuePairs_InChIKey {
get {
return ResourceManager.GetString("SmallMoleculeLibraryAttributes_KeyValuePairs_InChIKey", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Monoisotopic mass.
/// </summary>
public static string SmallMoleculeLibraryAttributes_KeyValuePairs_Monoisotopic_mass {
get {
return ResourceManager.GetString("SmallMoleculeLibraryAttributes_KeyValuePairs_Monoisotopic_mass", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Name.
/// </summary>
public static string SmallMoleculeLibraryAttributes_KeyValuePairs_Name {
get {
return ResourceManager.GetString("SmallMoleculeLibraryAttributes_KeyValuePairs_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to OtherIDs.
/// </summary>
public static string SmallMoleculeLibraryAttributes_KeyValuePairs_OtherIDs {
get {
return ResourceManager.GetString("SmallMoleculeLibraryAttributes_KeyValuePairs_OtherIDs", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A molecule is defined by a chemical formula and at least one of Name, InChiKey, or other keys (HMDB etc).
/// </summary>
public static string SmallMoleculeLibraryAttributes_Validate_A_small_molecule_is_defined_by_a_chemical_formula_and_at_least_one_of_Name__InChiKey__or_other_keys__HMDB_etc_ {
get {
return ResourceManager.GetString("SmallMoleculeLibraryAttributes_Validate_A_small_molecule_is_defined_by_a_chemical" +
"_formula_and_at_least_one_of_Name__InChiKey__or_other_keys__HMDB_etc_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Compound.
/// </summary>
public static string SmallMoleculeTransitionListColumnHeaders_SmallMoleculeTransitionListColumnHeaders_Compound {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListColumnHeaders_SmallMoleculeTransitionListColumnHeaders" +
"_Compound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule.
/// </summary>
public static string SmallMoleculeTransitionListColumnHeaders_SmallMoleculeTransitionListColumnHeaders_Molecule {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListColumnHeaders_SmallMoleculeTransitionListColumnHeaders" +
"_Molecule", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to RT (min).
/// </summary>
public static string SmallMoleculeTransitionListColumnHeaders_SmallMoleculeTransitionListColumnHeaders_RT__min_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListColumnHeaders_SmallMoleculeTransitionListColumnHeaders" +
"_RT__min_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Inconsistent molecule description.
/// </summary>
public static string SmallMoleculeTransitionListReader_GetMoleculeTransitionGroup_Inconsistent_molecule_description {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_GetMoleculeTransitionGroup_Inconsistent_molecul" +
"e_description", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot use product neutral loss chemical formula without a precursor chemical formula.
/// </summary>
public static string SmallMoleculeTransitionListReader_ProcessNeutralLoss_Cannot_use_product_neutral_loss_chemical_formula_without_a_precursor_chemical_formula {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ProcessNeutralLoss_Cannot_use_product_neutral_l" +
"oss_chemical_formula_without_a_precursor_chemical_formula", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor molecular formula {0} does not contain sufficient atoms to be used with neutral loss {1}.
/// </summary>
public static string SmallMoleculeTransitionListReader_ProcessNeutralLoss_Precursor_molecular_formula__0__does_not_contain_sufficient_atoms_to_be_used_with_neutral_loss__1_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ProcessNeutralLoss_Precursor_molecular_formula_" +
"_0__does_not_contain_sufficient_atoms_to_be_used_with_neutral_loss__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} is not a valid CAS registry number..
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadMoleculeIdColumns__0__is_not_a_valid_CAS_registry_number_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadMoleculeIdColumns__0__is_not_a_valid_CAS_re" +
"gistry_number_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} is not a valid HMDB identifier..
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadMoleculeIdColumns__0__is_not_a_valid_HMDB_identifier_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadMoleculeIdColumns__0__is_not_a_valid_HMDB_i" +
"dentifier_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} is not a valid InChI identifier..
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadMoleculeIdColumns__0__is_not_a_valid_InChI_identifier_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadMoleculeIdColumns__0__is_not_a_valid_InChI_" +
"identifier_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} is not a valid InChiKey..
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadMoleculeIdColumns__0__is_not_a_valid_InChiKey_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadMoleculeIdColumns__0__is_not_a_valid_InChiK" +
"ey_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adduct {0} charge {1} does not agree with declared charge {2}.
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Adduct__0__charge__1__does_not_agree_with_declared_charge__2_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Adduct__0__charge" +
"__1__does_not_agree_with_declared_charge__2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot derive charge from adduct description "{0}". Use the corresponding Charge column to set this explicitly, or change the adduct description as needed..
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Cannot_derive_charge_from_adduct_description___0____Use_the_corresponding_Charge_column_to_set_this_explicitly__or_change_the_adduct_description_as_needed_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Cannot_derive_cha" +
"rge_from_adduct_description___0____Use_the_corresponding_Charge_column_to_set_th" +
"is_explicitly__or_change_the_adduct_description_as_needed_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Formula already contains an adduct description, and it does not match..
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Formula_already_contains_an_adduct_description__and_it_does_not_match_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Formula_already_c" +
"ontains_an_adduct_description__and_it_does_not_match_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid collisional cross section value {0}.
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Invalid_collisional_cross_section_value__0_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Invalid_collision" +
"al_cross_section_value__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid ion mobility high energy offset value {0}.
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Invalid_ion_mobility_high_energy_offset_value__0_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Invalid_ion_mobil" +
"ity_high_energy_offset_value__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid ion mobility units value {0} (accepted values are {1}).
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Invalid_ion_mobility_units_value__0___accepted_values_are__1__ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Invalid_ion_mobil" +
"ity_units_value__0___accepted_values_are__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid ion mobility value {0}.
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Invalid_ion_mobility_value__0_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Invalid_ion_mobil" +
"ity_value__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing ion mobility units.
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Missing_ion_mobility_units {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_Missing_ion_mobil" +
"ity_units", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to unknown error.
/// </summary>
public static string SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_unknown_error {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_ReadPrecursorOrProductColumns_unknown_error", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error reading molecule column headers, did not recognize:
///{0}
///Supported values include:
///{1}.
/// </summary>
public static string SmallMoleculeTransitionListReader_SmallMoleculeTransitionListReader_ {
get {
return ResourceManager.GetString("SmallMoleculeTransitionListReader_SmallMoleculeTransitionListReader_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to "{0}" is not a valid setting for full scan special handling.
/// </summary>
public static string SpecialHandlingType_Validate___0___is_not_a_valid_setting_for_full_scan_special_handling {
get {
return ResourceManager.GetString("SpecialHandlingType_Validate___0___is_not_a_valid_setting_for_full_scan_special_h" +
"andling", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None.
/// </summary>
public static string SpecialHandlingType_Validate_None {
get {
return ResourceManager.GetString("SpecialHandlingType_Validate_None", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scan {0} found without precursor m/z..
/// </summary>
public static string SpectraChromDataProvider_SpectraChromDataProvider_Scan__0__found_without_precursor_mz {
get {
return ResourceManager.GetString("SpectraChromDataProvider_SpectraChromDataProvider_Scan__0__found_without_precurso" +
"r_mz", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Scan {0} found without scan time..
/// </summary>
public static string SpectraChromDataProvider_SpectraChromDataProvider_Scan__0__found_without_scan_time {
get {
return ResourceManager.GetString("SpectraChromDataProvider_SpectraChromDataProvider_Scan__0__found_without_scan_tim" +
"e", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Libraries:.
/// </summary>
public static string SpectralLibraryList_Label_Libraries {
get {
return ResourceManager.GetString("SpectralLibraryList_Label_Libraries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Libraries.
/// </summary>
public static string SpectralLibraryList_Title_Edit_Libraries {
get {
return ResourceManager.GetString("SpectralLibraryList_Title_Edit_Libraries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SpectraST Library.
/// </summary>
public static string SpectrastLibrary_SpecFilter_SpectraST_Library {
get {
return ResourceManager.GetString("SpectrastLibrary_SpecFilter_SpectraST_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to determine isolation width for the scan targeted at {0}.
/// </summary>
public static string SpectrumFilter_CalcDiaIsolationValues_Unable_to_determine_isolation_width_for_the_scan_targeted_at__0_ {
get {
return ResourceManager.GetString("SpectrumFilter_CalcDiaIsolationValues_Unable_to_determine_isolation_width_for_the" +
"_scan_targeted_at__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Two isolation windows contain targets which match the isolation target {0}..
/// </summary>
public static string SpectrumFilter_FindFilterPairs_Two_isolation_windows_contain_targets_which_match_the_isolation_target__0__ {
get {
return ResourceManager.GetString("SpectrumFilter_FindFilterPairs_Two_isolation_windows_contain_targets_which_match_" +
"the_isolation_target__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}{1}, Charge {2}.
/// </summary>
public static string SpectrumGraphItem_Title__0__1__Charge__2__ {
get {
return ResourceManager.GetString("SpectrumGraphItem_Title__0__1__Charge__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}{1}, Charge {2} ({3}).
/// </summary>
public static string SpectrumGraphItem_Title__0__1__Charge__2__3__ {
get {
return ResourceManager.GetString("SpectrumGraphItem_Title__0__1__Charge__2__3__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} library.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText__0__library {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText__0__library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data files.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_Data_files {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_Data_files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Data files: {0}.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_Data_files___0_ {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_Data_files___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ID.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_ID {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_ID", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ID: {0}.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_ID__0__ {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_ID__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Matched spectra.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_Matched_spectra {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_Matched_spectra", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Matched spectra: {0}.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_Matched_spectra__0__ {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_Matched_spectra__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Revision.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_Revision {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_Revision", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Revision: {0}.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_Revision__0__ {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_Revision__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unique peptides: {0}.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_Unique_peptides {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_Unique_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unique peptides: {0}.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_Unique_peptides__0__ {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_Unique_peptides__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unique precursors: {0}.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_Unique_Precursors___0_ {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_Unique_Precursors___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Version.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_Version {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_Version", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Version: {0}.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetDetailsText_Version__0__ {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetDetailsText_Version__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library source:.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetLibraryLinks_Library_source {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetLibraryLinks_Library_source", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library sources:.
/// </summary>
public static string SpectrumLibraryInfoDlg_SetLibraryLinks_Library_sources {
get {
return ResourceManager.GetString("SpectrumLibraryInfoDlg_SetLibraryLinks_Library_sources", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Two incompatible transition groups for sequence {0}, precursor m/z {1}..
/// </summary>
public static string SpectrumMzInfo_CombineSpectrumInfo_Two_incompatible_transition_groups_for_sequence__0___precursor_m_z__1__ {
get {
return ResourceManager.GetString("SpectrumMzInfo_CombineSpectrumInfo_Two_incompatible_transition_groups_for_sequenc" +
"e__0___precursor_m_z__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library spectrum for sequence {0} is missing..
/// </summary>
public static string SpectrumMzInfo_GetInfoFromLibrary_Library_spectrum_for_sequence__0__is_missing_ {
get {
return ResourceManager.GetString("SpectrumMzInfo_GetInfoFromLibrary_Library_spectrum_for_sequence__0__is_missing_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Must have an active iRT calculator to add iRT peptides..
/// </summary>
public static string SrmDocument_AddIrtPeptides_Must_have_an_active_iRT_calculator_to_add_iRT_peptides {
get {
return ResourceManager.GetString("SrmDocument_AddIrtPeptides_Must_have_an_active_iRT_calculator_to_add_iRT_peptides" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No replicate named {0} was found.
/// </summary>
public static string SrmDocument_ChangePeak_No_replicate_named__0__was_found {
get {
return ResourceManager.GetString("SrmDocument_ChangePeak_No_replicate_named__0__was_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No results found for the precursor {0} in the file {1}.
/// </summary>
public static string SrmDocument_ChangePeak_No_results_found_for_the_precursor__0__in_the_file__1__ {
get {
return ResourceManager.GetString("SrmDocument_ChangePeak_No_results_found_for_the_precursor__0__in_the_file__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No results found for the precursor {0} in the replicate {1}.
/// </summary>
public static string SrmDocument_ChangePeak_No_results_found_for_the_precursor__0__in_the_replicate__1__ {
get {
return ResourceManager.GetString("SrmDocument_ChangePeak_No_results_found_for_the_precursor__0__in_the_replicate__1" +
"__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} was not found in the replicate {1}..
/// </summary>
public static string SrmDocument_ChangePeak_The_file__0__was_not_found_in_the_replicate__1__ {
get {
return ResourceManager.GetString("SrmDocument_ChangePeak_The_file__0__was_not_found_in_the_replicate__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline Files.
/// </summary>
public static string SrmDocument_FILTER_DOC_AND_SKY_ZIP_Skyline_Files {
get {
return ResourceManager.GetString("SrmDocument_FILTER_DOC_AND_SKY_ZIP_Skyline_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline Documents.
/// </summary>
public static string SrmDocument_FILTER_DOC_Skyline_Documents {
get {
return ResourceManager.GetString("SrmDocument_FILTER_DOC_Skyline_Documents", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to molecules.
/// </summary>
public static string SrmDocument_GetPeptideGroupId_molecules {
get {
return ResourceManager.GetString("SrmDocument_GetPeptideGroupId_molecules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to peptides.
/// </summary>
public static string SrmDocument_GetPeptideGroupId_peptides {
get {
return ResourceManager.GetString("SrmDocument_GetPeptideGroupId_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to sequence.
/// </summary>
public static string SrmDocument_GetPeptideGroupId_sequence {
get {
return ResourceManager.GetString("SrmDocument_GetPeptideGroupId_sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to molecules.
/// </summary>
public static string SrmDocument_GetSmallMoleculeGroupId_molecules {
get {
return ResourceManager.GetString("SrmDocument_GetSmallMoleculeGroupId_molecules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide {0} was found multiple times with user modifications..
/// </summary>
public static string SrmDocument_MergeMatchingPeptidesUserInfo_The_peptide__0__was_found_multiple_times_with_user_modifications {
get {
return ResourceManager.GetString("SrmDocument_MergeMatchingPeptidesUserInfo_The_peptide__0__was_found_multiple_time" +
"s_with_user_modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid move source..
/// </summary>
public static string SrmDocument_MoveNode_Invalid_move_source {
get {
return ResourceManager.GetString("SrmDocument_MoveNode_Invalid_move_source", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid move target..
/// </summary>
public static string SrmDocument_MoveNode_Invalid_move_target {
get {
return ResourceManager.GetString("SrmDocument_MoveNode_Invalid_move_target", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Annotation found without name..
/// </summary>
public static string SrmDocument_ReadAnnotations_Annotation_found_without_name {
get {
return ResourceManager.GetString("SrmDocument_ReadAnnotations_Annotation_found_without_name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The isotope modification type {0} does not exist in the document settings..
/// </summary>
public static string SrmDocument_ReadLabelType_The_isotope_modification_type__0__does_not_exist_in_the_document_settings {
get {
return ResourceManager.GetString("SrmDocument_ReadLabelType_The_isotope_modification_type__0__does_not_exist_in_the" +
"_document_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No file with id {0} found in the replicate {1}.
/// </summary>
public static string SrmDocument_ReadResults_No_file_with_id__0__found_in_the_replicate__1__ {
get {
return ResourceManager.GetString("SrmDocument_ReadResults_No_file_with_id__0__found_in_the_replicate__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No replicate named {0} found in measured results.
/// </summary>
public static string SrmDocument_ReadResults_No_replicate_named__0__found_in_measured_results {
get {
return ResourceManager.GetString("SrmDocument_ReadResults_No_replicate_named__0__found_in_measured_results", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No results information found in the document settings.
/// </summary>
public static string SrmDocument_ReadResults_No_results_information_found_in_the_document_settings {
get {
return ResourceManager.GetString("SrmDocument_ReadResults_No_results_information_found_in_the_document_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All transitions of decoy precursors must have a decoy mass shift..
/// </summary>
public static string SrmDocument_ReadTransitionXml_All_transitions_of_decoy_precursors_must_have_a_decoy_mass_shift {
get {
return ResourceManager.GetString("SrmDocument_ReadTransitionXml_All_transitions_of_decoy_precursors_must_have_a_dec" +
"oy_mass_shift", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document format version {0} is newer than the version {1} supported by {2}..
/// </summary>
public static string SrmDocument_ReadXml_The_document_format_version__0__is_newer_than_the_version__1__supported_by__2__ {
get {
return ResourceManager.GetString("SrmDocument_ReadXml_The_document_format_version__0__is_newer_than_the_version__1_" +
"_supported_by__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Compressing files for sharing archive {0}.
/// </summary>
public static string SrmDocumentSharing_DefaultMessage_Compressing_files_for_sharing_archive__0__ {
get {
return ResourceManager.GetString("SrmDocumentSharing_DefaultMessage_Compressing_files_for_sharing_archive__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Extracting files from sharing archive {0}.
/// </summary>
public static string SrmDocumentSharing_DefaultMessage_Extracting_files_from_sharing_archive__0__ {
get {
return ResourceManager.GetString("SrmDocumentSharing_DefaultMessage_Extracting_files_from_sharing_archive__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shared Files.
/// </summary>
public static string SrmDocumentSharing_FILTER_SHARING_Shared_Files {
get {
return ResourceManager.GetString("SrmDocumentSharing_FILTER_SHARING_Shared_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The zip file is not a shared file..
/// </summary>
public static string SrmDocumentSharing_FindSharedSkylineFile_The_zip_file_is_not_a_shared_file {
get {
return ResourceManager.GetString("SrmDocumentSharing_FindSharedSkylineFile_The_zip_file_is_not_a_shared_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The zip file is not a shared file. The file contains multiple Skyline documents..
/// </summary>
public static string SrmDocumentSharing_FindSharedSkylineFile_The_zip_file_is_not_a_shared_file_The_file_contains_multiple_Skyline_documents {
get {
return ResourceManager.GetString("SrmDocumentSharing_FindSharedSkylineFile_The_zip_file_is_not_a_shared_file_The_fi" +
"le_contains_multiple_Skyline_documents", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The zip file is not a shared file. The file does not contain any Skyline documents..
/// </summary>
public static string SrmDocumentSharing_FindSharedSkylineFile_The_zip_file_is_not_a_shared_file_The_file_does_not_contain_any_Skyline_documents {
get {
return ResourceManager.GetString("SrmDocumentSharing_FindSharedSkylineFile_The_zip_file_is_not_a_shared_file_The_fi" +
"le_does_not_contain_any_Skyline_documents", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Writing chromatograms.
/// </summary>
public static string SrmDocumentSharing_MinimizeToFile_Writing_chromatograms {
get {
return ResourceManager.GetString("SrmDocumentSharing_MinimizeToFile_Writing_chromatograms", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure removing temporary directory {0}..
/// </summary>
public static string SrmDocumentSharing_ShareMinimal_Failure_removing_temporary_directory__0__ {
get {
return ResourceManager.GetString("SrmDocumentSharing_ShareMinimal_Failure_removing_temporary_directory__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Extracting {0}.
/// </summary>
public static string SrmDocumentSharing_SrmDocumentSharing_ExtractProgress_Extracting__0__ {
get {
return ResourceManager.GetString("SrmDocumentSharing_SrmDocumentSharing_ExtractProgress_Extracting__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Compressing {0}.
/// </summary>
public static string SrmDocumentSharing_SrmDocumentSharing_SaveProgress_Compressing__0__ {
get {
return ResourceManager.GetString("SrmDocumentSharing_SrmDocumentSharing_SaveProgress_Compressing__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results found in document with no replicates..
/// </summary>
public static string SrmDocumentValidateChromInfoResults_found_in_document_with_no_replicates {
get {
return ResourceManager.GetString("SrmDocumentValidateChromInfoResults_found_in_document_with_no_replicates", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Settings missing library spec..
/// </summary>
public static string SrmSettings_ConnectLibrarySpecs_Settings_missing_library_spec {
get {
return ResourceManager.GetString("SrmSettings_ConnectLibrarySpecs_Settings_missing_library_spec", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The modification '{0}' already exists with a different definition..
/// </summary>
public static string SrmSettings_UpdateDefaultModifications_The_modification__0__already_exists_with_a_different_definition {
get {
return ResourceManager.GetString("SrmSettings_UpdateDefaultModifications_The_modification__0__already_exists_with_a" +
"_different_definition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 3 ions.
/// </summary>
public static string SrmSettingsList_DEFAULT_3_ions {
get {
return ResourceManager.GetString("SrmSettingsList_DEFAULT_3_ions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to m/z > precursor.
/// </summary>
public static string SrmSettingsList_DEFAULT_m_z_precursor {
get {
return ResourceManager.GetString("SrmSettingsList_DEFAULT_m_z_precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default.
/// </summary>
public static string SrmSettingsList_DefaultName_Default {
get {
return ResourceManager.GetString("SrmSettingsList_DefaultName_Default", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Saved Settings:.
/// </summary>
public static string SrmSettingsList_Label_Saved_Settings {
get {
return ResourceManager.GetString("SrmSettingsList_Label_Saved_Settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Settings.
/// </summary>
public static string SrmSettingsList_Title_Edit_Settings {
get {
return ResourceManager.GetString("SrmSettingsList_Title_Edit_Settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to False.
/// </summary>
public static string SrmTreeNode_RenderTip_False {
get {
return ResourceManager.GetString("SrmTreeNode_RenderTip_False", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Note.
/// </summary>
public static string SrmTreeNode_RenderTip_Note {
get {
return ResourceManager.GetString("SrmTreeNode_RenderTip_Note", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to True.
/// </summary>
public static string SrmTreeNode_RenderTip_True {
get {
return ResourceManager.GetString("SrmTreeNode_RenderTip_True", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred creating options..
/// </summary>
public static string SrmTreeNodeParent_ShowPickList_An_error_occurred_creating_options_ {
get {
return ResourceManager.GetString("SrmTreeNodeParent_ShowPickList_An_error_occurred_creating_options_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Surrogate Standard.
/// </summary>
public static string StandardType_SURROGATE_STANDARD_Surrogate_Standard {
get {
return ResourceManager.GetString("StandardType_SURROGATE_STANDARD_Surrogate_Standard", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import DIA Peptide Search.
/// </summary>
public static string StartPage_PopulateWizardPanel_Import_DIA_Peptide_Search {
get {
return ResourceManager.GetString("StartPage_PopulateWizardPanel_Import_DIA_Peptide_Search", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Import PRM Peptide Search.
/// </summary>
public static string StartPage_PopulateWizardPanel_Import_PRM_Peptide_Search {
get {
return ResourceManager.GetString("StartPage_PopulateWizardPanel_Import_PRM_Peptide_Search", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use the Skyline Import Peptide Search wizard to build a spectral library from peptide search results on DIA data, and then import the raw data to quantify peptides using Skyline MS1 Filtering..
/// </summary>
public static string StartPage_PopulateWizardPanel_Use_the_Skyline_Import_Peptide_Search_wizard_to_build_a_spectral_library_from_peptide_search_results_on_DIA_data__and_then_import_the_raw_data_to_quantify_peptides_using_Skyline_MS1_Filtering_ {
get {
return ResourceManager.GetString("StartPage_PopulateWizardPanel_Use_the_Skyline_Import_Peptide_Search_wizard_to_bui" +
"ld_a_spectral_library_from_peptide_search_results_on_DIA_data__and_then_import_t" +
"he_raw_data_to_quantify_peptides_using_Skyline_MS1_Filtering_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use the Skyline Import Peptide Search wizard to build a spectral library from peptide search results on PRM data, and then import the raw data to quantify peptides using Skyline MS1 Filtering..
/// </summary>
public static string StartPage_PopulateWizardPanel_Use_the_Skyline_Import_Peptide_Search_wizard_to_build_a_spectral_library_from_peptide_search_results_on_PRM_data__and_then_import_the_raw_data_to_quantify_peptides_using_Skyline_MS1_Filtering_ {
get {
return ResourceManager.GetString("StartPage_PopulateWizardPanel_Use_the_Skyline_Import_Peptide_Search_wizard_to_bui" +
"ld_a_spectral_library_from_peptide_search_results_on_PRM_data__and_then_import_t" +
"he_raw_data_to_quantify_peptides_using_Skyline_MS1_Filtering_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Folder for tutorial files:.
/// </summary>
public static string StartPage_Tutorial__Folder_for_tutorial_files_ {
get {
return ResourceManager.GetString("StartPage_Tutorial__Folder_for_tutorial_files_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ZIP Files.
/// </summary>
public static string StartPage_Tutorial_Zip_Files {
get {
return ResourceManager.GetString("StartPage_Tutorial_Zip_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The settings have been reset to the default values..
/// </summary>
public static string StartPageSettingsUI_btnResetDefaults_Click_The_settings_have_been_reset_to_the_default_values_ {
get {
return ResourceManager.GetString("StartPageSettingsUI_btnResetDefaults_Click_The_settings_have_been_reset_to_the_de" +
"fault_values_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Integrate all: on.
/// </summary>
public static string StartPageSettingsUI_StartPageSettingsUI_Integrate_all__on {
get {
return ResourceManager.GetString("StartPageSettingsUI_StartPageSettingsUI_Integrate_all__on", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to List view item already has a description.
/// </summary>
public static string StatementCompletionForm_AddDescription_List_view_item_already_has_a_description {
get {
return ResourceManager.GetString("StatementCompletionForm_AddDescription_List_view_item_already_has_a_description", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Alternative Names:.
/// </summary>
public static string StatementCompletionTextBox_CreateListViewItems_Alternative_Names {
get {
return ResourceManager.GetString("StatementCompletionTextBox_CreateListViewItems_Alternative_Names", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Descriptions:.
/// </summary>
public static string StatementCompletionTextBox_CreateListViewItems_Descriptions {
get {
return ResourceManager.GetString("StatementCompletionTextBox_CreateListViewItems_Descriptions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid terminus '{0}'..
/// </summary>
public static string StaticMod_ToModTerminus_Invalid_terminus__0__ {
get {
return ResourceManager.GetString("StaticMod_ToModTerminus_Invalid_terminus__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Formula not allowed with labeled atoms..
/// </summary>
public static string StaticMod_Validate_Formula_not_allowed_with_labeled_atoms {
get {
return ResourceManager.GetString("StaticMod_Validate_Formula_not_allowed_with_labeled_atoms", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid amino acid '{0}'..
/// </summary>
public static string StaticMod_Validate_Invalid_amino_acid___0___ {
get {
return ResourceManager.GetString("StaticMod_Validate_Invalid_amino_acid___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loss-only modifications may not be variable..
/// </summary>
public static string StaticMod_Validate_Loss_only_modifications_may_not_be_variable {
get {
return ResourceManager.GetString("StaticMod_Validate_Loss_only_modifications_may_not_be_variable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modification formula may not be empty..
/// </summary>
public static string StaticMod_Validate_Modification_formula_may_not_be_empty {
get {
return ResourceManager.GetString("StaticMod_Validate_Modification_formula_may_not_be_empty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modification must specify a formula, labeled atoms or valid monoisotopic and average masses..
/// </summary>
public static string StaticMod_Validate_Modification_must_specify_a_formula_labeled_atoms_or_valid_monoisotopic_and_average_masses {
get {
return ResourceManager.GetString("StaticMod_Validate_Modification_must_specify_a_formula_labeled_atoms_or_valid_mon" +
"oisotopic_and_average_masses", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modification with a formula may not specify modification masses..
/// </summary>
public static string StaticMod_Validate_Modification_with_a_formula_may_not_specify_modification_masses {
get {
return ResourceManager.GetString("StaticMod_Validate_Modification_with_a_formula_may_not_specify_modification_masse" +
"s", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Terminal modification with labeled atoms not allowed..
/// </summary>
public static string StaticMod_Validate_Terminal_modification_with_labeled_atoms_not_allowed {
get {
return ResourceManager.GetString("StaticMod_Validate_Terminal_modification_with_labeled_atoms_not_allowed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Variable modifications must specify amino acid or terminus..
/// </summary>
public static string StaticMod_Validate_Variable_modifications_must_specify_amino_acid_or_terminus {
get {
return ResourceManager.GetString("StaticMod_Validate_Variable_modifications_must_specify_amino_acid_or_terminus", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &Modifications:.
/// </summary>
public static string StaticModList_Label_Modifications {
get {
return ResourceManager.GetString("StaticModList_Label_Modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Structural Modifications.
/// </summary>
public static string StaticModList_Title_Edit_Structural_Modifications {
get {
return ResourceManager.GetString("StaticModList_Title_Edit_Structural_Modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to foo.
/// </summary>
public static string String1 {
get {
return ResourceManager.GetString("String1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptide.
/// </summary>
public static string SummaryPeptideGraphPane_SummaryPeptideGraphPane_Peptide {
get {
return ResourceManager.GetString("SummaryPeptideGraphPane_SummaryPeptideGraphPane_Peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Log.
/// </summary>
public static string SummaryPeptideGraphPane_UpdateAxes_Log {
get {
return ResourceManager.GetString("SummaryPeptideGraphPane_UpdateAxes_Log", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Replicate.
/// </summary>
public static string SummaryReplicateGraphPane_SummaryReplicateGraphPane_Replicate {
get {
return ResourceManager.GetString("SummaryReplicateGraphPane_SummaryReplicateGraphPane_Replicate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to resolve molecule from '{0}'..
/// </summary>
public static string TargetResolver_TryResolveTarget_Unable_to_resolve_molecule_from___0___ {
get {
return ResourceManager.GetString("TargetResolver_TryResolveTarget_Unable_to_resolve_molecule_from___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to resolve molecule from "{0}": could be any of {1}.
/// </summary>
public static string TargetResolver_TryResolveTarget_Unable_to_resolve_molecule_from___0____could_be_any_of__1_ {
get {
return ResourceManager.GetString("TargetResolver_TryResolveTarget_Unable_to_resolve_molecule_from___0____could_be_a" +
"ny_of__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error running process.
/// </summary>
public static string TestNamedPipeProcessRunner_RunProcess_Error_running_process {
get {
return ResourceManager.GetString("TestNamedPipeProcessRunner_RunProcess_Error_running_process", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The operation was canceled by the user..
/// </summary>
public static string TestSkylineProcessRunner_RunProcess_The_operation_was_canceled_by_the_user_ {
get {
return ResourceManager.GetString("TestSkylineProcessRunner_RunProcess_The_operation_was_canceled_by_the_user_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot find a file with that identifier..
/// </summary>
public static string TestToolStoreClient_GetToolZipFile_Cannot_find_a_file_with_that_identifier_ {
get {
return ResourceManager.GetString("TestToolStoreClient_GetToolZipFile_Cannot_find_a_file_with_that_identifier_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error downloading tool.
/// </summary>
public static string TestToolStoreClient_GetToolZipFile_Error_downloading_tool {
get {
return ResourceManager.GetString("TestToolStoreClient_GetToolZipFile_Error_downloading_tool", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CSV (Comma delimited).
/// </summary>
public static string TextUtil_DESCRIPTION_CSV_CSV__Comma_delimited_ {
get {
return ResourceManager.GetString("TextUtil_DESCRIPTION_CSV_CSV__Comma_delimited_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to TSV (Tab delimited).
/// </summary>
public static string TextUtil_DESCRIPTION_TSV_TSV__Tab_delimited_ {
get {
return ResourceManager.GetString("TextUtil_DESCRIPTION_TSV_TSV__Tab_delimited_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All Files.
/// </summary>
public static string TextUtil_FileDialogFiltersAll_All_Files {
get {
return ResourceManager.GetString("TextUtil_FileDialogFiltersAll_All_Files", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to find a valid Thermo instrument installation..
/// </summary>
public static string ThermoMassListExporter_EnsureLibraries_Failed_to_find_a_valid_Thermo_instrument_installation_ {
get {
return ResourceManager.GetString("ThermoMassListExporter_EnsureLibraries_Failed_to_find_a_valid_Thermo_instrument_i" +
"nstallation_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Thermo instrument software may not be installed correctly. The library {0} could not be found..
/// </summary>
public static string ThermoMassListExporter_EnsureLibraries_Thermo_instrument_software_may_not_be_installed_correctly__The_library__0__could_not_be_found_ {
get {
return ResourceManager.GetString("ThermoMassListExporter_EnsureLibraries_Thermo_instrument_software_may_not_be_inst" +
"alled_correctly__The_library__0__could_not_be_found_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Thermo method creation software may not be installed correctly..
/// </summary>
public static string ThermoMassListExporter_EnsureLibraries_Thermo_method_creation_software_may_not_be_installed_correctly_ {
get {
return ResourceManager.GetString("ThermoMassListExporter_EnsureLibraries_Thermo_method_creation_software_may_not_be" +
"_installed_correctly_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error loading report from the temporary file {0}.
/// </summary>
public static string ToolDescription_CallArgsCollector_Error_loading_report_from_the_temporary_file__0_ {
get {
return ResourceManager.GetString("ToolDescription_CallArgsCollector_Error_loading_report_from_the_temporary_file__0" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error running the installed tool {0}. The method '{1}' has the wrong signature..
/// </summary>
public static string ToolDescription_CallArgsCollector_Error_running_the_installed_tool__0___The_method___1___has_the_wrong_signature_ {
get {
return ResourceManager.GetString("ToolDescription_CallArgsCollector_Error_running_the_installed_tool__0___The_metho" +
"d___1___has_the_wrong_signature_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find any CollectArgs method to call on class '{0}'..
/// </summary>
public static string ToolDescription_FindArgsCollectorMethod_Unable_to_find_any_CollectArgs_method_to_call_on_class___0___ {
get {
return ResourceManager.GetString("ToolDescription_FindArgsCollectorMethod_Unable_to_find_any_CollectArgs_method_to_" +
"call_on_class___0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error running the installed tool {0}. It seems to have an error in one of its files. Please reinstall the tool and try again.
/// </summary>
public static string ToolDescription_RunExecutableBackground_Error_running_the_installed_tool__0___It_seems_to_have_an_error_in_one_of_its_files__Please_reinstall_the_tool_and_try_again {
get {
return ResourceManager.GetString("ToolDescription_RunExecutableBackground_Error_running_the_installed_tool__0___It_" +
"seems_to_have_an_error_in_one_of_its_files__Please_reinstall_the_tool_and_try_ag" +
"ain", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error running the installed tool {0}. It seems to be missing a file. Please reinstall the tool and try again..
/// </summary>
public static string ToolDescription_RunExecutableBackground_Error_running_the_installed_tool_0_It_seems_to_be_missing_a_file__Please_reinstall_the_tool_and_try_again_ {
get {
return ResourceManager.GetString("ToolDescription_RunExecutableBackground_Error_running_the_installed_tool_0_It_see" +
"ms_to_be_missing_a_file__Please_reinstall_the_tool_and_try_again_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The tool {0} had an error..
/// </summary>
public static string ToolDescription_RunExecutableBackground_The_tool__0__had_an_error_ {
get {
return ResourceManager.GetString("ToolDescription_RunExecutableBackground_The_tool__0__had_an_error_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The tool {0} had an error, it returned the message:.
/// </summary>
public static string ToolDescription_RunExecutableBackground_The_tool__0__had_an_error__it_returned_the_message_ {
get {
return ResourceManager.GetString("ToolDescription_RunExecutableBackground_The_tool__0__had_an_error__it_returned_th" +
"e_message_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File not found..
/// </summary>
public static string ToolDescription_RunTool_File_not_found_ {
get {
return ResourceManager.GetString("ToolDescription_RunTool_File_not_found_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please check the command location is correct for this tool..
/// </summary>
public static string ToolDescription_RunTool_Please_check_the_command_location_is_correct_for_this_tool_ {
get {
return ResourceManager.GetString("ToolDescription_RunTool_Please_check_the_command_location_is_correct_for_this_too" +
"l_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please check the External Tools Store on the Skyline web site for the most recent version of the QuaSAR external tool..
/// </summary>
public static string ToolDescription_RunTool_Please_check_the_External_Tools_Store_on_the_Skyline_web_site_for_the_most_recent_version_of_the_QuaSAR_external_tool_ {
get {
return ResourceManager.GetString("ToolDescription_RunTool_Please_check_the_External_Tools_Store_on_the_Skyline_web_" +
"site_for_the_most_recent_version_of_the_QuaSAR_external_tool_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please reconfigure that tool, it failed to execute. .
/// </summary>
public static string ToolDescription_RunTool_Please_reconfigure_that_tool__it_failed_to_execute__ {
get {
return ResourceManager.GetString("ToolDescription_RunTool_Please_reconfigure_that_tool__it_failed_to_execute__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Support for the GenePattern version of QuaSAR has been discontinued..
/// </summary>
public static string ToolDescription_RunTool_Support_for_the_GenePattern_version_of_QuaSAR_has_been_discontinued_ {
get {
return ResourceManager.GetString("ToolDescription_RunTool_Support_for_the_GenePattern_version_of_QuaSAR_has_been_di" +
"scontinued_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Tools must have a command line.
/// </summary>
public static string ToolDescription_Validate_Tools_must_have_a_command_line {
get {
return ResourceManager.GetString("ToolDescription_Validate_Tools_must_have_a_command_line", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Tools must have a title.
/// </summary>
public static string ToolDescription_Validate_Tools_must_have_a_title {
get {
return ResourceManager.GetString("ToolDescription_Validate_Tools_must_have_a_title", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please enable these annotations and fill in the appropriate data in order to use the tool..
/// </summary>
public static string ToolDescription_VerifyAnnotations_Please_enable_these_annotations_and_fill_in_the_appropriate_data_in_order_to_use_the_tool_ {
get {
return ResourceManager.GetString("ToolDescription_VerifyAnnotations_Please_enable_these_annotations_and_fill_in_the" +
"_appropriate_data_in_order_to_use_the_tool_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please re-install the tool and try again..
/// </summary>
public static string ToolDescription_VerifyAnnotations_Please_re_install_the_tool_and_try_again_ {
get {
return ResourceManager.GetString("ToolDescription_VerifyAnnotations_Please_re_install_the_tool_and_try_again_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires the use of the following annotations which are missing or improperly formatted.
/// </summary>
public static string ToolDescription_VerifyAnnotations_This_tool_requires_the_use_of_the_following_annotations_which_are_missing_or_improperly_formatted {
get {
return ResourceManager.GetString("ToolDescription_VerifyAnnotations_This_tool_requires_the_use_of_the_following_ann" +
"otations_which_are_missing_or_improperly_formatted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires the use of the following annotations which are not enabled for this document.
/// </summary>
public static string ToolDescription_VerifyAnnotations_This_tool_requires_the_use_of_the_following_annotations_which_are_not_enabled_for_this_document {
get {
return ResourceManager.GetString("ToolDescription_VerifyAnnotations_This_tool_requires_the_use_of_the_following_ann" +
"otations_which_are_not_enabled_for_this_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: {0} requires a report titled {1} which no longer exists. Please select a new report or import the report format.
/// </summary>
public static string ToolDescriptionHelpers_GetReport_Error_0_requires_a_report_titled_1_which_no_longer_exists__Please_select_a_new_report_or_import_the_report_format {
get {
return ResourceManager.GetString("ToolDescriptionHelpers_GetReport_Error_0_requires_a_report_titled_1_which_no_long" +
"er_exists__Please_select_a_new_report_or_import_the_report_format", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing the file {0}. Tool {1} import failed.
/// </summary>
public static string ToolInstaller_AddToolFromProperties_Missing_the_file__0___Tool__1__import_failed {
get {
return ResourceManager.GetString("ToolInstaller_AddToolFromProperties_Missing_the_file__0___Tool__1__import_failed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: It does not contain the required {0} in the {1} directory..
/// </summary>
public static string ToolInstaller_GetToolInfo_Error__It_does_not_contain_the_required__0__in_the__1__directory_ {
get {
return ResourceManager.GetString("ToolInstaller_GetToolInfo_Error__It_does_not_contain_the_required__0__in_the__1__" +
"directory_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to process the {0} file.
/// </summary>
public static string ToolInstaller_GetToolInfo_Failed_to_process_the__0__file {
get {
return ResourceManager.GetString("ToolInstaller_GetToolInfo_Failed_to_process_the__0__file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: It does not contain the required {0} directory..
/// </summary>
public static string ToolInstaller_UnpackZipTool_Error__It_does_not_contain_the_required__0__directory_ {
get {
return ResourceManager.GetString("ToolInstaller_UnpackZipTool_Error__It_does_not_contain_the_required__0__directory" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: The {0} does not contain a valid {1} attribute..
/// </summary>
public static string ToolInstaller_UnpackZipTool_Error__The__0__does_not_contain_a_valid__1__attribute_ {
get {
return ResourceManager.GetString("ToolInstaller_UnpackZipTool_Error__The__0__does_not_contain_a_valid__1__attribute" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error: There is a file missing the {0}.zip.
/// </summary>
public static string ToolInstaller_UnpackZipTool_Error__There_is_a_file_missing_the__0__zip {
get {
return ResourceManager.GetString("ToolInstaller_UnpackZipTool_Error__There_is_a_file_missing_the__0__zip", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The selected zip file is not a valid installable tool..
/// </summary>
public static string ToolInstaller_UnpackZipTool_The_selected_zip_file_is_not_a_valid_installable_tool_ {
get {
return ResourceManager.GetString("ToolInstaller_UnpackZipTool_The_selected_zip_file_is_not_a_valid_installable_tool" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The selected zip file is not an installable tool..
/// </summary>
public static string ToolInstaller_UnpackZipTool_The_selected_zip_file_is_not_an_installable_tool_ {
get {
return ResourceManager.GetString("ToolInstaller_UnpackZipTool_The_selected_zip_file_is_not_an_installable_tool_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Tool Uses R and specifies Packages without an {0} file in the tool-inf directory..
/// </summary>
public static string ToolInstaller_UnpackZipTool_Tool_Uses_R_and_specifies_Packages_without_an__0__file_in_the_tool_inf_directory_ {
get {
return ResourceManager.GetString("ToolInstaller_UnpackZipTool_Tool_Uses_R_and_specifies_Packages_without_an__0__fil" +
"e_in_the_tool_inf_directory_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The server returned an invalid response. It might be down for maintenance. Please check the Tool Store on the skyline.ms website..
/// </summary>
public static string ToolInstallUI_InstallZipFromWeb_The_server_returned_an_invalid_response__It_might_be_down_for_maintenance__Please_check_the_Tool_Store_on_the_skyline_ms_website_ {
get {
return ResourceManager.GetString("ToolInstallUI_InstallZipFromWeb_The_server_returned_an_invalid_response__It_might" +
"_be_down_for_maintenance__Please_check_the_Tool_Store_on_the_skyline_ms_website_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Active Replicate Name.
/// </summary>
public static string ToolMacros__listArguments_Active_Replicate_Name {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Active_Replicate_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collected Arguments.
/// </summary>
public static string ToolMacros__listArguments_Collected_Arguments {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Collected_Arguments", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document Directory.
/// </summary>
public static string ToolMacros__listArguments_Document_Directory {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Document_Directory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document File Name.
/// </summary>
public static string ToolMacros__listArguments_Document_File_Name {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Document_File_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document File Name Without Extension.
/// </summary>
public static string ToolMacros__listArguments_Document_File_Name_Without_Extension {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Document_File_Name_Without_Extension", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Document Path.
/// </summary>
public static string ToolMacros__listArguments_Document_Path {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Document_Path", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input Report Temp Path.
/// </summary>
public static string ToolMacros__listArguments_Input_Report_Temp_Path {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Input_Report_Temp_Path", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please select a peptide sequence before running this tool..
/// </summary>
public static string ToolMacros__listArguments_Please_select_a_peptide_sequence_before_running_this_tool_ {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Please_select_a_peptide_sequence_before_running_this_to" +
"ol_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please select a protein before running this tool..
/// </summary>
public static string ToolMacros__listArguments_Please_select_a_protein_before_running_this_tool_ {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Please_select_a_protein_before_running_this_tool_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Selected Peptide Sequence.
/// </summary>
public static string ToolMacros__listArguments_Selected_Peptide_Sequence {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Selected_Peptide_Sequence", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Selected Precursor.
/// </summary>
public static string ToolMacros__listArguments_Selected_Precursor {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Selected_Precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Selected Protein Name.
/// </summary>
public static string ToolMacros__listArguments_Selected_Protein_Name {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Selected_Protein_Name", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skyline Connection.
/// </summary>
public static string ToolMacros__listArguments_Skyline_Connection {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Skyline_Connection", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool does not provide the functionality for the Collected Arguments macro. Please edit the tool..
/// </summary>
public static string ToolMacros__listArguments_This_tool_does_not_provide_the_functionality_for_the_Collected_Arguments_macro__Please_edit_the_tool_ {
get {
return ResourceManager.GetString("ToolMacros__listArguments_This_tool_does_not_provide_the_functionality_for_the_Co" +
"llected_Arguments_macro__Please_edit_the_tool_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool is not an installed tool so $(ToolDir) cannot be used as a macro. Please edit the tool..
/// </summary>
public static string ToolMacros__listArguments_This_tool_is_not_an_installed_tool_so_ToolDir_cannot_be_used_as_a_macro__Please_edit_the_tool_ {
get {
return ResourceManager.GetString("ToolMacros__listArguments_This_tool_is_not_an_installed_tool_so_ToolDir_cannot_be" +
"_used_as_a_macro__Please_edit_the_tool_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires a Document Directory to run.
/// </summary>
public static string ToolMacros__listArguments_This_tool_requires_a_Document_Directory_to_run {
get {
return ResourceManager.GetString("ToolMacros__listArguments_This_tool_requires_a_Document_Directory_to_run", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires a Document File Name to run..
/// </summary>
public static string ToolMacros__listArguments_This_tool_requires_a_Document_File_Name__to_run_ {
get {
return ResourceManager.GetString("ToolMacros__listArguments_This_tool_requires_a_Document_File_Name__to_run_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires a Document File Name to run.
/// </summary>
public static string ToolMacros__listArguments_This_tool_requires_a_Document_File_Name_to_run {
get {
return ResourceManager.GetString("ToolMacros__listArguments_This_tool_requires_a_Document_File_Name_to_run", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires a Document Path to run.
/// </summary>
public static string ToolMacros__listArguments_This_tool_requires_a_Document_Path_to_run {
get {
return ResourceManager.GetString("ToolMacros__listArguments_This_tool_requires_a_Document_Path_to_run", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires a Selected Peptide Sequence to run.
/// </summary>
public static string ToolMacros__listArguments_This_tool_requires_a_Selected_Peptide_Sequence_to_run {
get {
return ResourceManager.GetString("ToolMacros__listArguments_This_tool_requires_a_Selected_Peptide_Sequence_to_run", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires a Selected Protein to run..
/// </summary>
public static string ToolMacros__listArguments_This_tool_requires_a_Selected_Protein_to_run_ {
get {
return ResourceManager.GetString("ToolMacros__listArguments_This_tool_requires_a_Selected_Protein_to_run_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Tool Directory.
/// </summary>
public static string ToolMacros__listArguments_Tool_Directory {
get {
return ResourceManager.GetString("ToolMacros__listArguments_Tool_Directory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No Path Provided. Tool execution cancled..
/// </summary>
public static string ToolMacros__listCommand__No_Path_Provided__Tool_execution_cancled_ {
get {
return ResourceManager.GetString("ToolMacros__listCommand__No_Path_Provided__Tool_execution_cancled_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Program Path.
/// </summary>
public static string ToolMacros__listCommand_Program_Path {
get {
return ResourceManager.GetString("ToolMacros__listCommand_Program_Path", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires a Program Path to run..
/// </summary>
public static string ToolMacros__listCommand_This_tool_requires_a_Program_Path_to_run_ {
get {
return ResourceManager.GetString("ToolMacros__listCommand_This_tool_requires_a_Program_Path_to_run_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error exporting the report, tool execution canceled..
/// </summary>
public static string ToolMacros_GetReportTempPath_Error_exporting_the_report__tool_execution_canceled_ {
get {
return ResourceManager.GetString("ToolMacros_GetReportTempPath_Error_exporting_the_report__tool_execution_canceled_" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The selected tool ( {0} ) requires a selected report. Please select a report for this tool..
/// </summary>
public static string ToolMacros_GetReportTempPath_The_selected_tool_0_requires_a_selected_report_Please_select_a_report_for_this_tool_ {
get {
return ResourceManager.GetString("ToolMacros_GetReportTempPath_The_selected_tool_0_requires_a_selected_report_Pleas" +
"e_select_a_report_for_this_tool_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please select a precursor before running this tool..
/// </summary>
public static string ToolMacros_listArguments_Please_select_a_precursor_before_running_this_tool_ {
get {
return ResourceManager.GetString("ToolMacros_listArguments_Please_select_a_precursor_before_running_this_tool_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires a Selected Precursor to run.
/// </summary>
public static string ToolMacros_listArguments_This_tool_requires_a_Selected_Precursor_to_run {
get {
return ResourceManager.GetString("ToolMacros_listArguments_This_tool_requires_a_Selected_Precursor_to_run", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires a selected report.
/// </summary>
public static string ToolMacros_listArguments_This_tool_requires_a_selected_report {
get {
return ResourceManager.GetString("ToolMacros_listArguments_This_tool_requires_a_selected_report", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This tool requires an Active Replicate Name to run.
/// </summary>
public static string ToolMacros_listArguments_This_tool_requires_an_Active_Replicate_Name_to_run {
get {
return ResourceManager.GetString("ToolMacros_listArguments_This_tool_requires_an_Active_Replicate_Name_to_run", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to clear all saved settings? This will immediately return {0} to its original configuration and cannot be undone..
/// </summary>
public static string ToolOptionsUI_btnResetSettings_Click_Are_you_sure_you_want_to_clear_all_saved_settings__This_will_immediately_return__0__to_its_original_configuration_and_cannot_be_undone_ {
get {
return ResourceManager.GetString("ToolOptionsUI_btnResetSettings_Click_Are_you_sure_you_want_to_clear_all_saved_set" +
"tings__This_will_immediately_return__0__to_its_original_configuration_and_cannot" +
"_be_undone_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default ({0}).
/// </summary>
public static string ToolOptionsUI_ToolOptionsUI_Default___0__ {
get {
return ResourceManager.GetString("ToolOptionsUI_ToolOptionsUI_Default___0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insert proteins.
/// </summary>
public static string ToolService_ImportFasta_Insert_proteins {
get {
return ResourceManager.GetString("ToolService_ImportFasta_Insert_proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Insert Molecule Transition List.
/// </summary>
public static string ToolService_InsertSmallMoleculeTransitionList_Insert_Small_Molecule_Transition_List {
get {
return ResourceManager.GetString("ToolService_InsertSmallMoleculeTransitionList_Insert_Small_Molecule_Transition_Li" +
"st", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading {0}.
/// </summary>
public static string ToolStoreDlg_DownloadSelectedTool_Downloading__0_ {
get {
return ResourceManager.GetString("ToolStoreDlg_DownloadSelectedTool_Downloading__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Currently installed and fully updated (Version: {0})..
/// </summary>
public static string ToolStoreDlg_FormatVersionText_Currently_installed_and_fully_updated__Version___0___ {
get {
return ResourceManager.GetString("ToolStoreDlg_FormatVersionText_Currently_installed_and_fully_updated__Version___0" +
"___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Not currently installed. Version: {0} is available.
/// </summary>
public static string ToolStoreDlg_FormatVersionText_Not_currently_installed__Version___0__is_available {
get {
return ResourceManager.GetString("ToolStoreDlg_FormatVersionText_Not_currently_installed__Version___0__is_available" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Version {0} currently installed. Version {1} is available..
/// </summary>
public static string ToolStoreDlg_FormatVersionText_Version__0__currently_installed__Version__1__is_available_ {
get {
return ResourceManager.GetString("ToolStoreDlg_FormatVersionText_Version__0__currently_installed__Version__1__is_av" +
"ailable_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Install.
/// </summary>
public static string ToolStoreDlg_UpdateDisplayedTool_Install {
get {
return ResourceManager.GetString("ToolStoreDlg_UpdateDisplayedTool_Install", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reinstall.
/// </summary>
public static string ToolStoreDlg_UpdateDisplayedTool_Reinstall {
get {
return ResourceManager.GetString("ToolStoreDlg_UpdateDisplayedTool_Reinstall", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Update.
/// </summary>
public static string ToolStoreDlg_UpdateDisplayedTool_Update {
get {
return ResourceManager.GetString("ToolStoreDlg_UpdateDisplayedTool_Update", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap ToolUpdateAvailable {
get {
object obj = ResourceManager.GetObject("ToolUpdateAvailable", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Please select at least one tool to update..
/// </summary>
public static string ToolUpdatesDlg_btnUpdate_Click_Please_select_at_least_one_tool_to_update_ {
get {
return ResourceManager.GetString("ToolUpdatesDlg_btnUpdate_Click_Please_select_at_least_one_tool_to_update_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to download updates for the following packages.
/// </summary>
public static string ToolUpdatesDlg_DisplayDownloadSummary_Failed_to_download_updates_for_the_following_packages {
get {
return ResourceManager.GetString("ToolUpdatesDlg_DisplayDownloadSummary_Failed_to_download_updates_for_the_followin" +
"g_packages", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to update the following tool.
/// </summary>
public static string ToolUpdatesDlg_DisplayInstallSummary_Failed_to_update_the_following_tool {
get {
return ResourceManager.GetString("ToolUpdatesDlg_DisplayInstallSummary_Failed_to_update_the_following_tool", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to update the following tools.
/// </summary>
public static string ToolUpdatesDlg_DisplayInstallSummary_Failed_to_update_the_following_tools {
get {
return ResourceManager.GetString("ToolUpdatesDlg_DisplayInstallSummary_Failed_to_update_the_following_tools", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Successfully updated the following tool.
/// </summary>
public static string ToolUpdatesDlg_DisplayInstallSummary_Successfully_updated_the_following_tool {
get {
return ResourceManager.GetString("ToolUpdatesDlg_DisplayInstallSummary_Successfully_updated_the_following_tool", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Successfully updated the following tools.
/// </summary>
public static string ToolUpdatesDlg_DisplayInstallSummary_Successfully_updated_the_following_tools {
get {
return ResourceManager.GetString("ToolUpdatesDlg_DisplayInstallSummary_Successfully_updated_the_following_tools", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading updates for {0}.
/// </summary>
public static string ToolUpdatesDlg_DownloadTools_Downloading_updates_for__0_ {
get {
return ResourceManager.GetString("ToolUpdatesDlg_DownloadTools_Downloading_updates_for__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading Updates.
/// </summary>
public static string ToolUpdatesDlg_GetTools_Downloading_Updates {
get {
return ResourceManager.GetString("ToolUpdatesDlg_GetTools_Downloading_Updates", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Downloading Updates.
/// </summary>
public static string ToolUpdatesDlg_GetToolsToUpdate_Downloading_Updates {
get {
return ResourceManager.GetString("ToolUpdatesDlg_GetToolsToUpdate_Downloading_Updates", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Installing updates to {0}.
/// </summary>
public static string ToolUpdatesDlg_InstallUpdates_Installing_updates_to__0_ {
get {
return ResourceManager.GetString("ToolUpdatesDlg_InstallUpdates_Installing_updates_to__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User cancelled installation.
/// </summary>
public static string ToolUpdatesDlg_InstallUpdates_User_cancelled_installation {
get {
return ResourceManager.GetString("ToolUpdatesDlg_InstallUpdates_User_cancelled_installation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete the transition '{0}'?.
/// </summary>
public static string Transition_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_the_transition___0___ {
get {
return ResourceManager.GetString("Transition_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_the_transition__" +
"_0___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete these {0} transitions?.
/// </summary>
public static string Transition_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__transitions_ {
get {
return ResourceManager.GetString("Transition_GetDeleteConfirmation_Are_you_sure_you_want_to_delete_these__0__transi" +
"tions_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to precursor.
/// </summary>
public static string Transition_ToString_precursor {
get {
return ResourceManager.GetString("Transition_ToString_precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A transition of ion type {0} can't have a custom ion.
/// </summary>
public static string Transition_Validate_A_transition_of_ion_type__0__can_t_have_a_custom_ion {
get {
return ResourceManager.GetString("Transition_Validate_A_transition_of_ion_type__0__can_t_have_a_custom_ion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A transition of ion type {0} must have a custom ion..
/// </summary>
public static string Transition_Validate_A_transition_of_ion_type__0__must_have_a_custom_ion_ {
get {
return ResourceManager.GetString("Transition_Validate_A_transition_of_ion_type__0__must_have_a_custom_ion_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fragment decoy mass shift {0} must be between {1} and {2}..
/// </summary>
public static string Transition_Validate_Fragment_decoy_mass_shift__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("Transition_Validate_Fragment_decoy_mass_shift__0__must_be_between__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fragment ordinal {0} exceeds the maximum {1} for the peptide {2}..
/// </summary>
public static string Transition_Validate_Fragment_ordinal__0__exceeds_the_maximum__1__for_the_peptide__2__ {
get {
return ResourceManager.GetString("Transition_Validate_Fragment_ordinal__0__exceeds_the_maximum__1__for_the_peptide_" +
"_2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Fragment ordinal {0} may not be less than 1..
/// </summary>
public static string Transition_Validate_Fragment_ordinal__0__may_not_be_less_than__1__ {
get {
return ResourceManager.GetString("Transition_Validate_Fragment_ordinal__0__may_not_be_less_than__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor and product ion polarity do not agree..
/// </summary>
public static string Transition_Validate_Precursor_and_product_ion_polarity_do_not_agree_ {
get {
return ResourceManager.GetString("Transition_Validate_Precursor_and_product_ion_polarity_do_not_agree_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor charge {0} must be between {1} and {2}..
/// </summary>
public static string Transition_Validate_Precursor_charge__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("Transition_Validate_Precursor_charge__0__must_be_between__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor charge {0} must be non-zero and between {1} and {2}..
/// </summary>
public static string Transition_Validate_Precursor_charge__0__must_be_non_zero_and_between__1__and__2__ {
get {
return ResourceManager.GetString("Transition_Validate_Precursor_charge__0__must_be_non_zero_and_between__1__and__2_" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor ordinal must be the length of the peptide..
/// </summary>
public static string Transition_Validate_Precursor_ordinal_must_be_the_lenght_of_the_peptide {
get {
return ResourceManager.GetString("Transition_Validate_Precursor_ordinal_must_be_the_lenght_of_the_peptide", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product ion charge {0} must be between {1} and {2}..
/// </summary>
public static string Transition_Validate_Product_ion_charge__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("Transition_Validate_Product_ion_charge__0__must_be_between__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product ion charge {0} must be non-zero and between {1} and {2}..
/// </summary>
public static string Transition_Validate_Product_ion_charge__0__must_be_non_zero_and_between__1__and__2__ {
get {
return ResourceManager.GetString("Transition_Validate_Product_ion_charge__0__must_be_non_zero_and_between__1__and__" +
"2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Imported spectrum appears to be missing m/z or intensity values ({0} != {1}).
/// </summary>
public static string TransitionBinner_BinData_ {
get {
return ResourceManager.GetString("TransitionBinner_BinData_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Duplicate or out of order peak in transition {0}.
/// </summary>
public static string TransitionDocNode_ChangePeak_Duplicate_or_out_of_order_peak_in_transition__0_ {
get {
return ResourceManager.GetString("TransitionDocNode_ChangePeak_Duplicate_or_out_of_order_peak_in_transition__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 ion.
/// </summary>
public static string TransitionFilter_FragmentEndFinders_1_ion {
get {
return ResourceManager.GetString("TransitionFilter_FragmentEndFinders_1_ion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 2 ions.
/// </summary>
public static string TransitionFilter_FragmentEndFinders_2_ions {
get {
return ResourceManager.GetString("TransitionFilter_FragmentEndFinders_2_ions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 3 ions.
/// </summary>
public static string TransitionFilter_FragmentEndFinders_3_ions {
get {
return ResourceManager.GetString("TransitionFilter_FragmentEndFinders_3_ions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 4 ions.
/// </summary>
public static string TransitionFilter_FragmentEndFinders_4_ions {
get {
return ResourceManager.GetString("TransitionFilter_FragmentEndFinders_4_ions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 5 ions.
/// </summary>
public static string TransitionFilter_FragmentEndFinders_5_ions {
get {
return ResourceManager.GetString("TransitionFilter_FragmentEndFinders_5_ions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 6 ions.
/// </summary>
public static string TransitionFilter_FragmentEndFinders_6_ions {
get {
return ResourceManager.GetString("TransitionFilter_FragmentEndFinders_6_ions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to last ion.
/// </summary>
public static string TransitionFilter_FragmentEndFinders_last_ion {
get {
return ResourceManager.GetString("TransitionFilter_FragmentEndFinders_last_ion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to last ion - 1.
/// </summary>
public static string TransitionFilter_FragmentEndFinders_last_ion_minus_1 {
get {
return ResourceManager.GetString("TransitionFilter_FragmentEndFinders_last_ion_minus_1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to last ion - 2.
/// </summary>
public static string TransitionFilter_FragmentEndFinders_last_ion_minus_2 {
get {
return ResourceManager.GetString("TransitionFilter_FragmentEndFinders_last_ion_minus_2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to last ion - 3.
/// </summary>
public static string TransitionFilter_FragmentEndFinders_last_ion_minus_3 {
get {
return ResourceManager.GetString("TransitionFilter_FragmentEndFinders_last_ion_minus_3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unsupported first fragment name {0}..
/// </summary>
public static string TransitionFilter_FragmentRangeFirstName_Unsupported_first_fragment_name__0__ {
get {
return ResourceManager.GetString("TransitionFilter_FragmentRangeFirstName_Unsupported_first_fragment_name__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unsupported last fragment name {0}..
/// </summary>
public static string TransitionFilter_FragmentRangeLastName_Unsupported_last_fragment_name__0__ {
get {
return ResourceManager.GetString("TransitionFilter_FragmentRangeLastName_Unsupported_last_fragment_name__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ion 1.
/// </summary>
public static string TransitionFilter_FragmentStartFinders_ion_1 {
get {
return ResourceManager.GetString("TransitionFilter_FragmentStartFinders_ion_1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ion 2.
/// </summary>
public static string TransitionFilter_FragmentStartFinders_ion_2 {
get {
return ResourceManager.GetString("TransitionFilter_FragmentStartFinders_ion_2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ion 3.
/// </summary>
public static string TransitionFilter_FragmentStartFinders_ion_3 {
get {
return ResourceManager.GetString("TransitionFilter_FragmentStartFinders_ion_3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ion 4.
/// </summary>
public static string TransitionFilter_FragmentStartFinders_ion_4 {
get {
return ResourceManager.GetString("TransitionFilter_FragmentStartFinders_ion_4", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to m/z > precursor.
/// </summary>
public static string TransitionFilter_FragmentStartFinders_m_z_precursor {
get {
return ResourceManager.GetString("TransitionFilter_FragmentStartFinders_m_z_precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to (m/z > precursor) - 1.
/// </summary>
public static string TransitionFilter_FragmentStartFinders_m_z_precursor_minus_1 {
get {
return ResourceManager.GetString("TransitionFilter_FragmentStartFinders_m_z_precursor_minus_1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to (m/z > precursor) - 2.
/// </summary>
public static string TransitionFilter_FragmentStartFinders_m_z_precursor_minus_2 {
get {
return ResourceManager.GetString("TransitionFilter_FragmentStartFinders_m_z_precursor_minus_2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to (m/z > precursor) + 1.
/// </summary>
public static string TransitionFilter_FragmentStartFinders_m_z_precursor_plus_1 {
get {
return ResourceManager.GetString("TransitionFilter_FragmentStartFinders_m_z_precursor_plus_1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to (m/z > precursor) + 2.
/// </summary>
public static string TransitionFilter_FragmentStartFinders_m_z_precursor_plus_2 {
get {
return ResourceManager.GetString("TransitionFilter_FragmentStartFinders_m_z_precursor_plus_2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown fragment name in Transition Settings '{0}'.
/// </summary>
public static string TransitionFilter_GetEndFragmentFinder_Unknown_fragment_name_in_Transition_Settings__0__ {
get {
return ResourceManager.GetString("TransitionFilter_GetEndFragmentFinder_Unknown_fragment_name_in_Transition_Setting" +
"s__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The label {0} is not a valid end fragment filter..
/// </summary>
public static string TransitionFilter_GetEndFragmentNameFromLabel_The_label__0__is_not_a_valid_end_fragment_filter_ {
get {
return ResourceManager.GetString("TransitionFilter_GetEndFragmentNameFromLabel_The_label__0__is_not_a_valid_end_fra" +
"gment_filter_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The label {0} is not a valid start fragment filter..
/// </summary>
public static string TransitionFilter_GetStartFragmentNameFromLabel_The_label__0__is_not_a_valid_start_fragment_filter_ {
get {
return ResourceManager.GetString("TransitionFilter_GetStartFragmentNameFromLabel_The_label__0__is_not_a_valid_start" +
"_fragment_filter_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to At least one ion type is required..
/// </summary>
public static string TransitionFilter_IonTypes_At_least_one_ion_type_is_required {
get {
return ResourceManager.GetString("TransitionFilter_IonTypes_At_least_one_ion_type_is_required", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor charges.
/// </summary>
public static string TransitionFilter_PrecursorCharges_Precursor_charges {
get {
return ResourceManager.GetString("TransitionFilter_PrecursorCharges_Precursor_charges", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product ion charges.
/// </summary>
public static string TransitionFilter_ProductCharges_Product_ion_charges {
get {
return ResourceManager.GetString("TransitionFilter_ProductCharges_Product_ion_charges", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule precursor adducts.
/// </summary>
public static string TransitionFilter_SmallMoleculePrecursorAdducts_Small_molecule_precursor_adducts {
get {
return ResourceManager.GetString("TransitionFilter_SmallMoleculePrecursorAdducts_Small_molecule_precursor_adducts", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A precursor exclusion window must be between {0} and {1}..
/// </summary>
public static string TransitionFilter_Validate_A_precursor_exclusion_window_must_be_between__0__and__1__ {
get {
return ResourceManager.GetString("TransitionFilter_Validate_A_precursor_exclusion_window_must_be_between__0__and__1" +
"__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} cannot be empty..
/// </summary>
public static string TransitionFilter_ValidateCharges__0__cannot_be_empty {
get {
return ResourceManager.GetString("TransitionFilter_ValidateCharges__0__cannot_be_empty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid charge {1} found. {0} must be between {2} and {3}..
/// </summary>
public static string TransitionFilter_ValidateCharges_Invalid_charge__1__found__0__must_be_between__2__and__3__ {
get {
return ResourceManager.GetString("TransitionFilter_ValidateCharges_Invalid_charge__1__found__0__must_be_between__2_" +
"_and__3__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor charges specified charge {0} more than once..
/// </summary>
public static string TransitionFilter_ValidateCharges_Precursor_charges_specified_charge__0__more_than_once {
get {
return ResourceManager.GetString("TransitionFilter_ValidateCharges_Precursor_charges_specified_charge__0__more_than" +
"_once", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Tried to create an isolation scheme for non-DIA mode.
/// </summary>
public static string TransitionFullScan_CreateIsolationSchemeForFilter_Tried_to_create_an_isolation_scheme_for_non_DIA_mode {
get {
return ResourceManager.GetString("TransitionFullScan_CreateIsolationSchemeForFilter_Tried_to_create_an_isolation_sc" +
"heme_for_non_DIA_mode", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Tried to create an isolation scheme without precursor filter.
/// </summary>
public static string TransitionFullScan_CreateIsolationSchemeForFilter_Tried_to_create_an_isolation_scheme_without_precursor_filter {
get {
return ResourceManager.GetString("TransitionFullScan_CreateIsolationSchemeForFilter_Tried_to_create_an_isolation_sc" +
"heme_without_precursor_filter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An isolation window width value is not allowed in Targeted mode..
/// </summary>
public static string TransitionFullScan_DoValidate_An_isolation_window_width_value_is_not_allowed_in_Targeted_mode {
get {
return ResourceManager.GetString("TransitionFullScan_DoValidate_An_isolation_window_width_value_is_not_allowed_in_T" +
"argeted_mode", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An isolation window width value is required in DIA mode..
/// </summary>
public static string TransitionFullScan_DoValidate_An_isolation_window_width_value_is_required_in_DIA_mode {
get {
return ResourceManager.GetString("TransitionFullScan_DoValidate_An_isolation_window_width_value_is_required_in_DIA_" +
"mode", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to For MS1 filtering with a QIT mass analyzer only 1 isotope peak is supported..
/// </summary>
public static string TransitionFullScan_DoValidate_For_MS1_filtering_with_a_QIT_mass_analyzer_only_1_isotope_peak_is_supported {
get {
return ResourceManager.GetString("TransitionFullScan_DoValidate_For_MS1_filtering_with_a_QIT_mass_analyzer_only_1_i" +
"sotope_peak_is_supported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No other full-scan MS1 filter settings are allowed when no precursor isotopes are included..
/// </summary>
public static string TransitionFullScan_DoValidate_No_other_full_scan_MS1_filter_settings_are_allowed_when_no_precursor_isotopes_are_included {
get {
return ResourceManager.GetString("TransitionFullScan_DoValidate_No_other_full_scan_MS1_filter_settings_are_allowed_" +
"when_no_precursor_isotopes_are_included", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor isotope count for MS1 filtering must be between {0} and {1} peaks..
/// </summary>
public static string TransitionFullScan_DoValidate_The_precursor_isotope_count_for_MS1_filtering_must_be_between__0__and__1__peaks {
get {
return ResourceManager.GetString("TransitionFullScan_DoValidate_The_precursor_isotope_count_for_MS1_filtering_must_" +
"be_between__0__and__1__peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor isotope percent for MS1 filtering must be between {0}% and {1}% of the base peak..
/// </summary>
public static string TransitionFullScan_DoValidate_The_precursor_isotope_percent_for_MS1_filtering_must_be_between__0___and__1___of_the_base_peak {
get {
return ResourceManager.GetString("TransitionFullScan_DoValidate_The_precursor_isotope_percent_for_MS1_filtering_mus" +
"t_be_between__0___and__1___of_the_base_peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mass accuracy must be between {0} and {1} for centroided data..
/// </summary>
public static string TransitionFullScan_ValidateRes_Mass_accuracy_must_be_between__0__and__1__for_centroided_data_ {
get {
return ResourceManager.GetString("TransitionFullScan_ValidateRes_Mass_accuracy_must_be_between__0__and__1__for_cent" +
"roided_data_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Resolution must be between {0} and {1} for QIT..
/// </summary>
public static string TransitionFullScan_ValidateRes_Resolution_must_be_between__0__and__1__for_QIT_ {
get {
return ResourceManager.GetString("TransitionFullScan_ValidateRes_Resolution_must_be_between__0__and__1__for_QIT_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Resolving power must be between {0} and {1} for {2}..
/// </summary>
public static string TransitionFullScan_ValidateRes_Resolving_power_must_be_between__0__and__1__for__2__ {
get {
return ResourceManager.GetString("TransitionFullScan_ValidateRes_Resolving_power_must_be_between__0__and__1__for__2" +
"__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The m/z value at which the resolving power is calibrated is required for {0}..
/// </summary>
public static string TransitionFullScan_ValidateRes_The_mz_value_at_which_the_resolving_power_is_calibrated_is_required_for__0__ {
get {
return ResourceManager.GetString("TransitionFullScan_ValidateRes_The_mz_value_at_which_the_resolving_power_is_calib" +
"rated_is_required_for__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected resolving power m/z value for {0}.
/// </summary>
public static string TransitionFullScan_ValidateRes_Unexpected_resolving_power_mz_value_for__0__ {
get {
return ResourceManager.GetString("TransitionFullScan_ValidateRes_Unexpected_resolving_power_mz_value_for__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results {0:0.##},{1:0.##} m/z.
/// </summary>
public static string TransitionFullScanCreateIsolationSchemeForFilterResults__0__0__1_0__Th {
get {
return ResourceManager.GetString("TransitionFullScanCreateIsolationSchemeForFilterResults__0__0__1_0__Th", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Results {0:0.##} m/z.
/// </summary>
public static string TransitionFullScanCreateIsolationSchemeForFilterResults__0__0__Th {
get {
return ResourceManager.GetString("TransitionFullScanCreateIsolationSchemeForFilterResults__0__0__Th", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap TransitionGroup {
get {
object obj = ResourceManager.GetObject("TransitionGroup", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Precursor charge {0} must be between {1} and {2}..
/// </summary>
public static string TransitionGroup_Validate_Precursor_charge__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("TransitionGroup_Validate_Precursor_charge__0__must_be_between__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor decoy mass shift {0} must be between {1} and {2}..
/// </summary>
public static string TransitionGroup_Validate_Precursor_decoy_mass_shift__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("TransitionGroup_Validate_Precursor_decoy_mass_shift__0__must_be_between__1__and__" +
"2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Grouping transitions from file {0} with file {1}.
/// </summary>
public static string TransitionGroupChromInfoCalculator_AddChromInfo_Grouping_transitions_from_file__0__with_file__1__ {
get {
return ResourceManager.GetString("TransitionGroupChromInfoCalculator_AddChromInfo_Grouping_transitions_from_file__0" +
"__with_file__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempt to add integration information for missing file..
/// </summary>
public static string TransitionGroupChromInfoListCalculator_AddChromInfoList_Attempt_to_add_integration_information_for_missing_file {
get {
return ResourceManager.GetString("TransitionGroupChromInfoListCalculator_AddChromInfoList_Attempt_to_add_integratio" +
"n_information_for_missing_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap TransitionGroupDecoy {
get {
object obj = ResourceManager.GetObject("TransitionGroupDecoy", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Missing End Time In Change Peak.
/// </summary>
public static string TransitionGroupDocNode_ChangePeak_Missing_End_Time_In_Change_Peak {
get {
return ResourceManager.GetString("TransitionGroupDocNode_ChangePeak_Missing_End_Time_In_Change_Peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Missing Start Time in Change Peak.
/// </summary>
public static string TransitionGroupDocNode_ChangePeak_Missing_Start_Time_in_Change_Peak {
get {
return ResourceManager.GetString("TransitionGroupDocNode_ChangePeak_Missing_Start_Time_in_Change_Peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No peak found at {0:F01}.
/// </summary>
public static string TransitionGroupDocNode_ChangePeak_No_peak_found_at__0__ {
get {
return ResourceManager.GetString("TransitionGroupDocNode_ChangePeak_No_peak_found_at__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File Id {0} does not match any file in document..
/// </summary>
public static string TransitionGroupDocNode_ChangePrecursorAnnotations_File_Id__0__does_not_match_any_file_in_document_ {
get {
return ResourceManager.GetString("TransitionGroupDocNode_ChangePrecursorAnnotations_File_Id__0__does_not_match_any_" +
"file_in_document_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap TransitionGroupLib {
get {
object obj = ResourceManager.GetObject("TransitionGroupLib", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap TransitionGroupLibDecoy {
get {
object obj = ResourceManager.GetObject("TransitionGroupLibDecoy", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Invalid attempt to get choices for a node that has not been added to the tree yet..
/// </summary>
public static string TransitionGroupTreeNode_GetChoices_Invalid_attempt_to_get_choices_for_a_node_that_has_not_been_added_to_the_tree_yet {
get {
return ResourceManager.GetString("TransitionGroupTreeNode_GetChoices_Invalid_attempt_to_get_choices_for_a_node_that" +
"_has_not_been_added_to_the_tree_yet", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to total ratio {0}.
/// </summary>
public static string TransitionGroupTreeNode_GetResultsText_total_ratio__0__ {
get {
return ResourceManager.GetString("TransitionGroupTreeNode_GetResultsText_total_ratio__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Decoy Mass Shift.
/// </summary>
public static string TransitionGroupTreeNode_RenderTip_Decoy_Mass_Shift {
get {
return ResourceManager.GetString("TransitionGroupTreeNode_RenderTip_Decoy_Mass_Shift", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modified.
/// </summary>
public static string TransitionGroupTreeNode_RenderTip_Modified {
get {
return ResourceManager.GetString("TransitionGroupTreeNode_RenderTip_Modified", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule.
/// </summary>
public static string TransitionGroupTreeNode_RenderTip_Molecule {
get {
return ResourceManager.GetString("TransitionGroupTreeNode_RenderTip_Molecule", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor charge.
/// </summary>
public static string TransitionGroupTreeNode_RenderTip_Precursor_charge {
get {
return ResourceManager.GetString("TransitionGroupTreeNode_RenderTip_Precursor_charge", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor m+h.
/// </summary>
public static string TransitionGroupTreeNode_RenderTip_Precursor_mh {
get {
return ResourceManager.GetString("TransitionGroupTreeNode_RenderTip_Precursor_mh", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor m/z.
/// </summary>
public static string TransitionGroupTreeNode_RenderTip_Precursor_mz {
get {
return ResourceManager.GetString("TransitionGroupTreeNode_RenderTip_Precursor_mz", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Synchronize isotope label types.
/// </summary>
public static string TransitionGroupTreeNode_SynchSiblingsLabel_Synchronize_isotope_label_types {
get {
return ResourceManager.GetString("TransitionGroupTreeNode_SynchSiblingsLabel_Synchronize_isotope_label_types", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Precursor.
/// </summary>
public static string TransitionGroupTreeNode_Title {
get {
return ResourceManager.GetString("TransitionGroupTreeNode_Title", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid loss index {0} for modification {1}.
/// </summary>
public static string TransitionInfo_ReadTransitionLosses_Invalid_loss_index__0__for_modification__1__ {
get {
return ResourceManager.GetString("TransitionInfo_ReadTransitionLosses_Invalid_loss_index__0__for_modification__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No modification named {0} was found in this document..
/// </summary>
public static string TransitionInfo_ReadTransitionLosses_No_modification_named__0__was_found_in_this_document {
get {
return ResourceManager.GetString("TransitionInfo_ReadTransitionLosses_No_modification_named__0__was_found_in_this_d" +
"ocument", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The reporter ion {0} was not found in the transition filter settings..
/// </summary>
public static string TransitionInfo_ReadXmlAttributes_The_reporter_ion__0__was_not_found_in_the_transition_filter_settings_ {
get {
return ResourceManager.GetString("TransitionInfo_ReadXmlAttributes_The_reporter_ion__0__was_not_found_in_the_transi" +
"tion_filter_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Instrument maximum m/z value {0} is less than {1} from minimum {2}..
/// </summary>
public static string TransitionInstrument_DoValidate_Instrument_maximum_m_z_value__0__is_less_than__1__from_minimum__2__ {
get {
return ResourceManager.GetString("TransitionInstrument_DoValidate_Instrument_maximum_m_z_value__0__is_less_than__1_" +
"_from_minimum__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Instrument maximum m/z exceeds allowable maximum {0}..
/// </summary>
public static string TransitionInstrument_DoValidate_Instrument_maximum_mz_exceeds_allowable_maximum__0__ {
get {
return ResourceManager.GetString("TransitionInstrument_DoValidate_Instrument_maximum_mz_exceeds_allowable_maximum__" +
"0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Instrument minimum m/z value {0} must be between {1} and {2}..
/// </summary>
public static string TransitionInstrument_DoValidate_Instrument_minimum_mz_value__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("TransitionInstrument_DoValidate_Instrument_minimum_mz_value__0__must_be_between__" +
"1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No other full-scan MS/MS filter settings are allowed when precursor filter is none..
/// </summary>
public static string TransitionInstrument_DoValidate_No_other_full_scan_MS_MS_filter_settings_are_allowed_when_precursor_filter_is_none {
get {
return ResourceManager.GetString("TransitionInstrument_DoValidate_No_other_full_scan_MS_MS_filter_settings_are_allo" +
"wed_when_precursor_filter_is_none", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The allowable retention time range {0} to {1} must be at least {2} minutes apart..
/// </summary>
public static string TransitionInstrument_DoValidate_The_allowable_retention_time_range__0__to__1__must_be_at_least__2__minutes_apart_ {
get {
return ResourceManager.GetString("TransitionInstrument_DoValidate_The_allowable_retention_time_range__0__to__1__mus" +
"t_be_at_least__2__minutes_apart_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The maximum number of inclusions {0} must be between {1} and {2}..
/// </summary>
public static string TransitionInstrument_DoValidate_The_maximum_number_of_inclusions__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("TransitionInstrument_DoValidate_The_maximum_number_of_inclusions__0__must_be_betw" +
"een__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The maximum number of transitions {0} must be between {1} and {2}..
/// </summary>
public static string TransitionInstrument_DoValidate_The_maximum_number_of_transitions__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("TransitionInstrument_DoValidate_The_maximum_number_of_transitions__0__must_be_bet" +
"ween__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The maximum retention time {0} must be between {1} and {2}..
/// </summary>
public static string TransitionInstrument_DoValidate_The_maximum_retention_time__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("TransitionInstrument_DoValidate_The_maximum_retention_time__0__must_be_between__1" +
"__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The minimum retention time {0} must be between {1} and {2}..
/// </summary>
public static string TransitionInstrument_DoValidate_The_minimum_retention_time__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("TransitionInstrument_DoValidate_The_minimum_retention_time__0__must_be_between__1" +
"__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The m/z match tolerance {0} must be between {1} and {2}..
/// </summary>
public static string TransitionInstrument_DoValidate_The_mz_match_tolerance__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("TransitionInstrument_DoValidate_The_mz_match_tolerance__0__must_be_between__1__an" +
"d__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor m/z filter must be between {0} and {1}.
/// </summary>
public static string TransitionInstrument_DoValidate_The_precursor_mz_filter_must_be_between__0__and__1__ {
get {
return ResourceManager.GetString("TransitionInstrument_DoValidate_The_precursor_mz_filter_must_be_between__0__and__" +
"1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library ion count value {0} must be between {1} and {2}..
/// </summary>
public static string TransitionLibraries_DoValidate_Library_ion_count_value__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("TransitionLibraries_DoValidate_Library_ion_count_value__0__must_be_between__1__an" +
"d__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library ion count value {0} must not be less than min ion count value {1}..
/// </summary>
public static string TransitionLibraries_DoValidate_Library_ion_count_value__0__must_not_be_less_than_min_ion_count_value__1__ {
get {
return ResourceManager.GetString("TransitionLibraries_DoValidate_Library_ion_count_value__0__must_not_be_less_than_" +
"min_ion_count_value__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library ion match tolerance value {0} must be between {1} and {2}..
/// </summary>
public static string TransitionLibraries_DoValidate_Library_ion_match_tolerance_value__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("TransitionLibraries_DoValidate_Library_ion_match_tolerance_value__0__must_be_betw" +
"een__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library min ion count value {0} must be between {1} and {2}..
/// </summary>
public static string TransitionLibraries_DoValidate_Library_min_ion_count_value__0__must_be_between__1__and__2__ {
get {
return ResourceManager.GetString("TransitionLibraries_DoValidate_Library_min_ion_count_value__0__must_be_between__1" +
"__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Expected loss {0} not found in the modification {1}.
/// </summary>
public static string TransitionLoss_LossIndex_Expected_loss__0__not_found_in_the_modification__1_ {
get {
return ResourceManager.GetString("TransitionLoss_LossIndex_Expected_loss__0__not_found_in_the_modification__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition prediction requires a collision energy regression function..
/// </summary>
public static string TransitionPrediction_DoValidate_Transition_prediction_requires_a_collision_energy_regression_function {
get {
return ResourceManager.GetString("TransitionPrediction_DoValidate_Transition_prediction_requires_a_collision_energy" +
"_regression_function", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Compensation voltage parameters must be selected in the Prediction tab of the Transition Settings in order to import optimization data for compensation voltage.
/// </summary>
public static string TransitionPrediction_GetOptimizeFunction_Compensation_voltage_parameters_must_be_selected_in_the_Prediction_tab_of_the_Transition_Settings_in_order_to_import_optimization_data_for_compensation_voltage {
get {
return ResourceManager.GetString("TransitionPrediction_GetOptimizeFunction_Compensation_voltage_parameters_must_be_" +
"selected_in_the_Prediction_tab_of_the_Transition_Settings_in_order_to_import_opt" +
"imization_data_for_compensation_voltage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to High resolution MS1 filtering requires use of monoisotopic precursor masses..
/// </summary>
public static string TransitionSettings_DoValidate_High_resolution_MS1_filtering_requires_use_of_monoisotopic_precursor_masses {
get {
return ResourceManager.GetString("TransitionSettings_DoValidate_High_resolution_MS1_filtering_requires_use_of_monoi" +
"sotopic_precursor_masses", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The instrument's firmware inclusion limit must be specified before doing a multiplexed DIA scan..
/// </summary>
public static string TransitionSettings_DoValidate_The_instrument_s_firmware_inclusion_limit_must_be_specified_before_doing_a_multiplexed_DIA_scan {
get {
return ResourceManager.GetString("TransitionSettings_DoValidate_The_instrument_s_firmware_inclusion_limit_must_be_s" +
"pecified_before_doing_a_multiplexed_DIA_scan", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Max m/z {0} must not be less than min m/z {1}..
/// </summary>
public static string TransitionSettingsControl_GetTransitionSettings_Max_m_z__0__must_not_be_less_than_min_m_z__1__ {
get {
return ResourceManager.GetString("TransitionSettingsControl_GetTransitionSettings_Max_m_z__0__must_not_be_less_than" +
"_min_m_z__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} must contain a comma separated list of integers describing charge states between {1} and {2}..
/// </summary>
public static string TransitionSettingsControl_ValidateAdductListTextBox__0__must_contain_a_comma_separated_list_of_integers_describing_charge_states_between__1__and__2__ {
get {
return ResourceManager.GetString("TransitionSettingsControl_ValidateAdductListTextBox__0__must_contain_a_comma_sepa" +
"rated_list_of_integers_describing_charge_states_between__1__and__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Min % of base pea&k:.
/// </summary>
public static string TransitionSettingsUI_comboPrecursorIsotopes_SelectedIndexChanged_Min_percent_of_base_peak {
get {
return ResourceManager.GetString("TransitionSettingsUI_comboPrecursorIsotopes_SelectedIndexChanged_Min_percent_of_b" +
"ase_peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Pea&ks:.
/// </summary>
public static string TransitionSettingsUI_comboPrecursorIsotopes_SelectedIndexChanged_Peaks {
get {
return ResourceManager.GetString("TransitionSettingsUI_comboPrecursorIsotopes_SelectedIndexChanged_Peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An isolation scheme is required to match multiple precursors..
/// </summary>
public static string TransitionSettingsUI_OkDialog_An_isolation_scheme_is_required_to_match_multiple_precursors {
get {
return ResourceManager.GetString("TransitionSettingsUI_OkDialog_An_isolation_scheme_is_required_to_match_multiple_p" +
"recursors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Before performing a multiplexed DIA scan, the instrument's firmware inclusion limit must be specified..
/// </summary>
public static string TransitionSettingsUI_OkDialog_Before_performing_a_multiplexed_DIA_scan_the_instrument_s_firmware_inclusion_limit_must_be_specified {
get {
return ResourceManager.GetString("TransitionSettingsUI_OkDialog_Before_performing_a_multiplexed_DIA_scan_the_instru" +
"ment_s_firmware_inclusion_limit_must_be_specified", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot use DIA window for precursor exclusion when isolation scheme does not contain prespecified windows. Please select an isolation scheme with prespecified windows..
/// </summary>
public static string TransitionSettingsUI_OkDialog_Cannot_use_DIA_window_for_precursor_exclusion_when_isolation_scheme_does_not_contain_prespecified_windows___Please_select_an_isolation_scheme_with_prespecified_windows_ {
get {
return ResourceManager.GetString("TransitionSettingsUI_OkDialog_Cannot_use_DIA_window_for_precursor_exclusion_when_" +
"isolation_scheme_does_not_contain_prespecified_windows___Please_select_an_isolat" +
"ion_scheme_with_prespecified_windows_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot use DIA window for precusor exclusion when 'All Ions' is selected as the isolation scheme. To use the DIA window for precusor exclusion, change the isolation scheme in the Full Scan settings..
/// </summary>
public static string TransitionSettingsUI_OkDialog_Cannot_use_DIA_window_for_precusor_exclusion_when__All_Ions__is_selected_as_the_isolation_scheme___To_use_the_DIA_window_for_precusor_exclusion__change_the_isolation_scheme_in_the_Full_Scan_settings_ {
get {
return ResourceManager.GetString("TransitionSettingsUI_OkDialog_Cannot_use_DIA_window_for_precusor_exclusion_when__" +
"All_Ions__is_selected_as_the_isolation_scheme___To_use_the_DIA_window_for_precus" +
"or_exclusion__change_the_isolation_scheme_in_the_Full_Scan_settings_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Changing transition settings.
/// </summary>
public static string TransitionSettingsUI_OkDialog_Changing_transition_settings {
get {
return ResourceManager.GetString("TransitionSettingsUI_OkDialog_Changing_transition_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to For MS1 filtering with a QIT mass analyzer only 1 isotope peak is supported..
/// </summary>
public static string TransitionSettingsUI_OkDialog_For_MS1_filtering_with_a_QIT_mass_analyzer_only_1_isotope_peak_is_supported {
get {
return ResourceManager.GetString("TransitionSettingsUI_OkDialog_For_MS1_filtering_with_a_QIT_mass_analyzer_only_1_i" +
"sotope_peak_is_supported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to High resolution MS1 filtering requires use of monoisotopic precursor masses..
/// </summary>
public static string TransitionSettingsUI_OkDialog_High_resolution_MS1_filtering_requires_use_of_monoisotopic_precursor_masses {
get {
return ResourceManager.GetString("TransitionSettingsUI_OkDialog_High_resolution_MS1_filtering_requires_use_of_monoi" +
"sotopic_precursor_masses", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ion types must contain a comma separated list of ion types a, b, c, x, y, z and p (for precursor)..
/// </summary>
public static string TransitionSettingsUI_OkDialog_Ion_types_must_contain_a_comma_separated_list_of_ion_types_a_b_c_x_y_z_and_p_for_precursor {
get {
return ResourceManager.GetString("TransitionSettingsUI_OkDialog_Ion_types_must_contain_a_comma_separated_list_of_io" +
"n_types_a_b_c_x_y_z_and_p_for_precursor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Isotope enrichment settings are required for MS1 filtering on high resolution mass spectrometers..
/// </summary>
public static string TransitionSettingsUI_OkDialog_Isotope_enrichment_settings_are_required_for_MS1_filtering_on_high_resolution_mass_spectrometers {
get {
return ResourceManager.GetString("TransitionSettingsUI_OkDialog_Isotope_enrichment_settings_are_required_for_MS1_fi" +
"ltering_on_high_resolution_mass_spectrometers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecule ion types must contain a comma separated list of ion types. Valid types are "f" (for fragment) and/or "p" (for precursor).
/// </summary>
public static string TransitionSettingsUI_OkDialog_Small_molecule_ion_types_must_contain_a_comma_separated_list_of_ion_types__Valid_types_are__f___for_fragment__and_or__p___for_precursor_ {
get {
return ResourceManager.GetString("TransitionSettingsUI_OkDialog_Small_molecule_ion_types_must_contain_a_comma_separ" +
"ated_list_of_ion_types__Valid_types_are__f___for_fragment__and_or__p___for_precu" +
"rsor_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The allowable retention time range {0} to {1} must be at least {2} minutes apart..
/// </summary>
public static string TransitionSettingsUI_OkDialog_The_allowable_retention_time_range__0__to__1__must_be_at_least__2__minutes_apart {
get {
return ResourceManager.GetString("TransitionSettingsUI_OkDialog_The_allowable_retention_time_range__0__to__1__must_" +
"be_at_least__2__minutes_apart", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This is not a valid number of minutes..
/// </summary>
public static string TransitionSettingsUI_OkDialog_This_is_not_a_valid_number_of_minutes {
get {
return ResourceManager.GetString("TransitionSettingsUI_OkDialog_This_is_not_a_valid_number_of_minutes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adducts---.
/// </summary>
public static string TransitionSettingsUI_PopulateAdductMenu_Adducts_minusminusminus {
get {
return ResourceManager.GetString("TransitionSettingsUI_PopulateAdductMenu_Adducts_minusminusminus", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adducts+++.
/// </summary>
public static string TransitionSettingsUI_PopulateAdductMenu_Adducts_plusplusplus {
get {
return ResourceManager.GetString("TransitionSettingsUI_PopulateAdductMenu_Adducts_plusplusplus", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to More.
/// </summary>
public static string TransitionSettingsUI_PopulateAdductMenu_More {
get {
return ResourceManager.GetString("TransitionSettingsUI_PopulateAdductMenu_More", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Res&olution:.
/// </summary>
public static string TransitionSettingsUI_SetAnalyzerType_Resolution {
get {
return ResourceManager.GetString("TransitionSettingsUI_SetAnalyzerType_Resolution", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Res&olving power:.
/// </summary>
public static string TransitionSettingsUI_SetAnalyzerType_Resolving_power {
get {
return ResourceManager.GetString("TransitionSettingsUI_SetAnalyzerType_Resolving_power", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} [{1}].
/// </summary>
public static string TransitionTreeNode_GetLabel__0__1__ {
get {
return ResourceManager.GetString("TransitionTreeNode_GetLabel__0__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to irank {0}.
/// </summary>
public static string TransitionTreeNode_GetLabel_irank__0__ {
get {
return ResourceManager.GetString("TransitionTreeNode_GetLabel_irank__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to rank {0}.
/// </summary>
public static string TransitionTreeNode_GetLabel_rank__0__ {
get {
return ResourceManager.GetString("TransitionTreeNode_GetLabel_rank__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to [{0}].
/// </summary>
public static string TransitionTreeNode_GetResultsText__0__ {
get {
return ResourceManager.GetString("TransitionTreeNode_GetResultsText__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} (ratio {1}).
/// </summary>
public static string TransitionTreeNode_GetResultsText__0__ratio__1__ {
get {
return ResourceManager.GetString("TransitionTreeNode_GetResultsText__0__ratio__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Charge.
/// </summary>
public static string TransitionTreeNode_RenderTip_Charge {
get {
return ResourceManager.GetString("TransitionTreeNode_RenderTip_Charge", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Decoy Mass Shift.
/// </summary>
public static string TransitionTreeNode_RenderTip_Decoy_Mass_Shift {
get {
return ResourceManager.GetString("TransitionTreeNode_RenderTip_Decoy_Mass_Shift", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Formula.
/// </summary>
public static string TransitionTreeNode_RenderTip_Formula {
get {
return ResourceManager.GetString("TransitionTreeNode_RenderTip_Formula", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ion.
/// </summary>
public static string TransitionTreeNode_RenderTip_Ion {
get {
return ResourceManager.GetString("TransitionTreeNode_RenderTip_Ion", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library intensity.
/// </summary>
public static string TransitionTreeNode_RenderTip_Library_intensity {
get {
return ResourceManager.GetString("TransitionTreeNode_RenderTip_Library_intensity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library rank.
/// </summary>
public static string TransitionTreeNode_RenderTip_Library_rank {
get {
return ResourceManager.GetString("TransitionTreeNode_RenderTip_Library_rank", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loss.
/// </summary>
public static string TransitionTreeNode_RenderTip_Loss {
get {
return ResourceManager.GetString("TransitionTreeNode_RenderTip_Loss", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Losses.
/// </summary>
public static string TransitionTreeNode_RenderTip_Losses {
get {
return ResourceManager.GetString("TransitionTreeNode_RenderTip_Losses", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Product m/z.
/// </summary>
public static string TransitionTreeNode_RenderTip_Product_m_z {
get {
return ResourceManager.GetString("TransitionTreeNode_RenderTip_Product_m_z", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transition.
/// </summary>
public static string TransitionTreeNode_Title {
get {
return ResourceManager.GetString("TransitionTreeNode_Title", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Transitions.
/// </summary>
public static string TransitionTreeNode_Titles {
get {
return ResourceManager.GetString("TransitionTreeNode_Titles", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Truncated peaks.
/// </summary>
public static string TruncatedPeakFinder_DisplayName_Truncated_peaks {
get {
return ResourceManager.GetString("TruncatedPeakFinder_DisplayName_Truncated_peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Truncated peak.
/// </summary>
public static string TruncatedPeakFinder_MatchTransition_Truncated_peak {
get {
return ResourceManager.GetString("TruncatedPeakFinder_MatchTransition_Truncated_peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} truncated peaks.
/// </summary>
public static string TruncatedPeakFinder_MatchTransitionGroup__0__truncated_peaks {
get {
return ResourceManager.GetString("TruncatedPeakFinder_MatchTransitionGroup__0__truncated_peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 1 truncated peak.
/// </summary>
public static string TruncatedPeakFinder_MatchTransitionGroup__1_truncated_peak {
get {
return ResourceManager.GetString("TruncatedPeakFinder_MatchTransitionGroup__1_truncated_peak", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Static mod masses have already been added for this heavy type..
/// </summary>
public static string TypedExplicitModifications_AddModMasses_Static_mod_masses_have_already_been_added_for_this_heavy_type {
get {
return ResourceManager.GetString("TypedExplicitModifications_AddModMasses_Static_mod_masses_have_already_been_added" +
"_for_this_heavy_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Static mod masses may not be added to light type..
/// </summary>
public static string TypedExplicitModifications_AddModMasses_Static_mod_masses_may_not_be_added_to_light_type {
get {
return ResourceManager.GetString("TypedExplicitModifications_AddModMasses_Static_mod_masses_may_not_be_added_to_lig" +
"ht_type", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap UIModeMixed {
get {
object obj = ResourceManager.GetObject("UIModeMixed", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap UIModeProteomic {
get {
object obj = ResourceManager.GetObject("UIModeProteomic", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap UIModeSmallMolecules {
get {
object obj = ResourceManager.GetObject("UIModeSmallMolecules", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Chromatogram information unavailable.
/// </summary>
public static string UnavailableChromGraphItem_UnavailableChromGraphItem_Chromatogram_information_unavailable {
get {
return ResourceManager.GetString("UnavailableChromGraphItem_UnavailableChromGraphItem_Chromatogram_information_unav" +
"ailable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Spectrum information unavailable.
/// </summary>
public static string UnavailableMSGraphItem_UnavailableMSGraphItem_Spectrum_information_unavailable {
get {
return ResourceManager.GetString("UnavailableMSGraphItem_UnavailableMSGraphItem_Spectrum_information_unavailable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Undo transaction may not be started in undo/redo..
/// </summary>
public static string UndoManager_BeginTransaction_Undo_transaction_may_not_be_started_in_undo_redo {
get {
return ResourceManager.GetString("UndoManager_BeginTransaction_Undo_transaction_may_not_be_started_in_undo_redo", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Commit called with no pending undo record..
/// </summary>
public static string UndoManager_Commit_Commit_called_with_no_pending_undo_record {
get {
return ResourceManager.GetString("UndoManager_Commit_Commit_called_with_no_pending_undo_record", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempt to index {0} beyond length {1}..
/// </summary>
public static string UndoManager_Restore_Attempt_to_index__0__beyond_length__1__ {
get {
return ResourceManager.GetString("UndoManager_Restore_Attempt_to_index__0__beyond_length__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempting undo/redo inside undo transaction..
/// </summary>
public static string UndoManager_Restore_Attempting_undo_redo_inside_undo_transaction {
get {
return ResourceManager.GetString("UndoManager_Restore_Attempting_undo_redo_inside_undo_transaction", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Redo {0} Actions.
/// </summary>
public static string UndoRedoList_GetLabelText_Redo__0__Actions {
get {
return ResourceManager.GetString("UndoRedoList_GetLabelText_Redo__0__Actions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Redo 1 Action.
/// </summary>
public static string UndoRedoList_GetLabelText_Redo_1_Action {
get {
return ResourceManager.GetString("UndoRedoList_GetLabelText_Redo_1_Action", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Undo {0} Actions.
/// </summary>
public static string UndoRedoList_GetLabelText_Undo__0__Actions {
get {
return ResourceManager.GetString("UndoRedoList_GetLabelText_Undo__0__Actions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Undo 1 Action.
/// </summary>
public static string UndoRedoList_GetLabelText_Undo_1_Action {
get {
return ResourceManager.GetString("UndoRedoList_GetLabelText_Undo_1_Action", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unifi.
/// </summary>
public static string Unifi_Label_Unifi {
get {
return ResourceManager.GetString("Unifi_Label_Unifi", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot find account for username {0} and server {1}..
/// </summary>
public static string UnifiUrl_OpenMsDataFile_Cannot_find_account_for_username__0__and_server__1__ {
get {
return ResourceManager.GetString("UnifiUrl_OpenMsDataFile_Cannot_find_account_for_username__0__and_server__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unintegrated transitions.
/// </summary>
public static string UnintegratedTransitionFinder_DisplayName_Unintegrated_transitions {
get {
return ResourceManager.GetString("UnintegratedTransitionFinder_DisplayName_Unintegrated_transitions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unintegrated transition.
/// </summary>
public static string UnintegratedTransitionFinder_Match_Unintegrated_transition {
get {
return ResourceManager.GetString("UnintegratedTransitionFinder_Match_Unintegrated_transition", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Adding rows to grid..
/// </summary>
public static string UniquePeptidesDlg_AddProteinRowsToGrid_Adding_rows_to_grid_ {
get {
return ResourceManager.GetString("UniquePeptidesDlg_AddProteinRowsToGrid_Adding_rows_to_grid_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}
///(gene: {1}).
/// </summary>
public static string UniquePeptidesDlg_LaunchPeptideProteinsQuery_ {
get {
return ResourceManager.GetString("UniquePeptidesDlg_LaunchPeptideProteinsQuery_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed querying background proteome {0}..
/// </summary>
public static string UniquePeptidesDlg_LaunchPeptideProteinsQuery_Failed_querying_background_proteome__0__ {
get {
return ResourceManager.GetString("UniquePeptidesDlg_LaunchPeptideProteinsQuery_Failed_querying_background_proteome_" +
"_0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Looking for proteins with matching peptide sequences.
/// </summary>
public static string UniquePeptidesDlg_LaunchPeptideProteinsQuery_Looking_for_proteins_with_matching_peptide_sequences {
get {
return ResourceManager.GetString("UniquePeptidesDlg_LaunchPeptideProteinsQuery_Looking_for_proteins_with_matching_p" +
"eptide_sequences", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Querying Background Proteome Database.
/// </summary>
public static string UniquePeptidesDlg_LaunchPeptideProteinsQuery_Querying_Background_Proteome_Database {
get {
return ResourceManager.GetString("UniquePeptidesDlg_LaunchPeptideProteinsQuery_Querying_Background_Proteome_Databas" +
"e", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Exclude peptides.
/// </summary>
public static string UniquePeptidesDlg_OkDialog_Exclude_peptides {
get {
return ResourceManager.GetString("UniquePeptidesDlg_OkDialog_Exclude_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The background proteome {0} has not yet finished being digested with {1}..
/// </summary>
public static string UniquePeptidesDlg_OnShown_The_background_proteome__0__has_not_yet_finished_being_digested_with__1__ {
get {
return ResourceManager.GetString("UniquePeptidesDlg_OnShown_The_background_proteome__0__has_not_yet_finished_being_" +
"digested_with__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Some background proteome proteins did not have gene information, this selection may be suspect..
/// </summary>
public static string UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_Some_background_proteome_proteins_did_not_have_gene_information__this_selection_may_be_suspect_ {
get {
return ResourceManager.GetString("UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_Some_backgr" +
"ound_proteome_proteins_did_not_have_gene_information__this_selection_may_be_susp" +
"ect_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Some background proteome proteins did not have species information, this selection may be suspect..
/// </summary>
public static string UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_Some_background_proteome_proteins_did_not_have_species_information__this_selection_may_be_suspect_ {
get {
return ResourceManager.GetString("UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_Some_backgr" +
"ound_proteome_proteins_did_not_have_species_information__this_selection_may_be_s" +
"uspect_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to These proteins include:.
/// </summary>
public static string UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_These_proteins_include_ {
get {
return ResourceManager.GetString("UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_These_prote" +
"ins_include_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The tool "{0}" requires report type titled "{1}" and it is not provided. Import canceled..
/// </summary>
public static string UnpackZipToolHelper_UnpackZipTool_The_tool___0___requires_report_type_titled___1___and_it_is_not_provided__Import_canceled_ {
get {
return ResourceManager.GetString("UnpackZipToolHelper_UnpackZipTool_The_tool___0___requires_report_type_titled___1_" +
"__and_it_is_not_provided__Import_canceled_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap up_pro32 {
get {
object obj = ResourceManager.GetObject("up_pro32", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Maybe &Later.
/// </summary>
public static string UpgradeDlg_cbAtStartup_CheckedChanged_Maybe__Later {
get {
return ResourceManager.GetString("UpgradeDlg_cbAtStartup_CheckedChanged_Maybe__Later", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No update was found..
/// </summary>
public static string UpgradeDlg_UpgradeDlg_No_update_was_found_ {
get {
return ResourceManager.GetString("UpgradeDlg_UpgradeDlg_No_update_was_found_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Upgrading to {0} (downloading {1} of {2}).
/// </summary>
public static string UpgradeManager_GetProgressMessage_Upgrading_to__0___downloading__1__of__2__ {
get {
return ResourceManager.GetString("UpgradeManager_GetProgressMessage_Upgrading_to__0___downloading__1__of__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed attempting to check for an upgrade..
/// </summary>
public static string UpgradeManager_updateCheck_Complete_Failed_attempting_to_check_for_an_upgrade_ {
get {
return ResourceManager.GetString("UpgradeManager_updateCheck_Complete_Failed_attempting_to_check_for_an_upgrade_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed attempting to upgrade..
/// </summary>
public static string UpgradeManager_updateCheck_Complete_Failed_attempting_to_upgrade_ {
get {
return ResourceManager.GetString("UpgradeManager_updateCheck_Complete_Failed_attempting_to_upgrade_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Upgrading {0}.
/// </summary>
public static string UpgradeManager_updateCheck_Complete_Upgrading__0_ {
get {
return ResourceManager.GetString("UpgradeManager_updateCheck_Complete_Upgrading__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure uncompressing data..
/// </summary>
public static string UtilDB_Uncompress_Failure_uncompressing_data {
get {
return ResourceManager.GetString("UtilDB_Uncompress_Failure_uncompressing_data", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No ion mobility information found.
/// </summary>
public static string ValidatingIonMobilityPeptide_Validate_No_ion_mobility_information_found {
get {
return ResourceManager.GetString("ValidatingIonMobilityPeptide_Validate_No_ion_mobility_information_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No ion mobility units found.
/// </summary>
public static string ValidatingIonMobilityPeptide_Validate_No_ion_mobility_units_found {
get {
return ResourceManager.GetString("ValidatingIonMobilityPeptide_Validate_No_ion_mobility_units_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A valid adduct description (e.g. "[M+H]") must be provided..
/// </summary>
public static string ValidatingIonMobilityPeptide_ValidateAdduct_A_valid_adduct_description__e_g____M_H____must_be_provided_ {
get {
return ResourceManager.GetString("ValidatingIonMobilityPeptide_ValidateAdduct_A_valid_adduct_description__e_g____M_" +
"H____must_be_provided_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measured collisional cross section values must be valid decimal numbers greater than zero..
/// </summary>
public static string ValidatingIonMobilityPeptide_ValidateCollisionalCrossSection_Measured_collisional_cross_section_values_must_be_valid_decimal_numbers_greater_than_zero_ {
get {
return ResourceManager.GetString("ValidatingIonMobilityPeptide_ValidateCollisionalCrossSection_Measured_collisional" +
"_cross_section_values_must_be_valid_decimal_numbers_greater_than_zero_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to High energy ion mobility offsets should be empty, or express an offset value for ion mobility in high collision energy scans which may add velocity to ions..
/// </summary>
public static string ValidatingIonMobilityPeptide_ValidateHighEnergyIonMobilityOffset_High_energy_ion_mobility_offsets_should_be_empty__or_express_an_offset_value_for_ion_mobility_in_high_collision_energy_scans_which_may_add_velocity_to_ions_ {
get {
return ResourceManager.GetString("ValidatingIonMobilityPeptide_ValidateHighEnergyIonMobilityOffset_High_energy_ion_" +
"mobility_offsets_should_be_empty__or_express_an_offset_value_for_ion_mobility_in" +
"_high_collision_energy_scans_which_may_add_velocity_to_ions_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A modified peptide sequence is required for each entry..
/// </summary>
public static string ValidatingIonMobilityPeptide_ValidateSequence_A_modified_peptide_sequence_is_required_for_each_entry_ {
get {
return ResourceManager.GetString("ValidatingIonMobilityPeptide_ValidateSequence_A_modified_peptide_sequence_is_requ" +
"ired_for_each_entry_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The sequence {0} is not a valid modified peptide sequence..
/// </summary>
public static string ValidatingIonMobilityPeptide_ValidateSequence_The_sequence__0__is_not_a_valid_modified_peptide_sequence_ {
get {
return ResourceManager.GetString("ValidatingIonMobilityPeptide_ValidateSequence_The_sequence__0__is_not_a_valid_mod" +
"ified_peptide_sequence_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' is not valid for the argument {1} which requires an comma-separated list of integers..
/// </summary>
public static string ValueInvalidChargeListException_ValueInvalidChargeListException_The_value___0___is_not_valid_for_the_argument__1__which_requires_an_comma_separated_list_of_integers_ {
get {
return ResourceManager.GetString("ValueInvalidChargeListException_ValueInvalidChargeListException_The_value___0___i" +
"s_not_valid_for_the_argument__1__which_requires_an_comma_separated_list_of_integ" +
"ers_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' is not valid for the argument {1} which requires a date-time value..
/// </summary>
public static string ValueInvalidDateException_ValueInvalidDateException_The_value___0___is_not_valid_for_the_argument__1__which_requires_a_date_time_value_ {
get {
return ResourceManager.GetString("ValueInvalidDateException_ValueInvalidDateException_The_value___0___is_not_valid_" +
"for_the_argument__1__which_requires_a_date_time_value_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' is not valid for the argument {1} which requires a decimal number..
/// </summary>
public static string ValueInvalidDoubleException_ValueInvalidDoubleException_The_value___0___is_not_valid_for_the_argument__1__which_requires_a_decimal_number_ {
get {
return ResourceManager.GetString("ValueInvalidDoubleException_ValueInvalidDoubleException_The_value___0___is_not_va" +
"lid_for_the_argument__1__which_requires_a_decimal_number_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' is not valid for the argument {1}. Use one of {2}.
/// </summary>
public static string ValueInvalidException_ValueInvalidException_The_value___0___is_not_valid_for_the_argument__1___Use_one_of__2_ {
get {
return ResourceManager.GetString("ValueInvalidException_ValueInvalidException_The_value___0___is_not_valid_for_the_" +
"argument__1___Use_one_of__2_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' is not valid for the argument {1} which requires an integer..
/// </summary>
public static string ValueInvalidIntException_ValueInvalidIntException_The_value___0___is_not_valid_for_the_argument__1__which_requires_an_integer_ {
get {
return ResourceManager.GetString("ValueInvalidIntException_ValueInvalidIntException_The_value___0___is_not_valid_fo" +
"r_the_argument__1__which_requires_an_integer_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' is not valid for the argument {1} which requires an comma-separated list of fragment ion types (a, b, c, x, y, z, p)..
/// </summary>
public static string ValueInvalidIonTypeListException_ValueInvalidIonTypeListException_The_value___0___is_not_valid_for_the_argument__1__which_requires_an_comma_separated_list_of_fragment_ion_types__a__b__c__x__y__z__p__ {
get {
return ResourceManager.GetString("ValueInvalidIonTypeListException_ValueInvalidIonTypeListException_The_value___0__" +
"_is_not_valid_for_the_argument__1__which_requires_an_comma_separated_list_of_fra" +
"gment_ion_types__a__b__c__x__y__z__p__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value {0} is not valid for the argument {1} which requires a list of decimal numbers..
/// </summary>
public static string ValueInvalidNumberListException_ValueInvalidNumberListException_The_value__0__is_not_valid_for_the_argument__1__which_requires_a_list_of_decimal_numbers_ {
get {
return ResourceManager.GetString("ValueInvalidNumberListException_ValueInvalidNumberListException_The_value__0__is_" +
"not_valid_for_the_argument__1__which_requires_a_list_of_decimal_numbers_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' is not valid for the argument {1} failed attempting to convert it to a full file path..
/// </summary>
public static string ValueInvalidPathException_ValueInvalidPathException_The_value___0___is_not_valid_for_the_argument__1__failed_attempting_to_convert_it_to_a_full_file_path_ {
get {
return ResourceManager.GetString("ValueInvalidPathException_ValueInvalidPathException_The_value___0___is_not_valid_" +
"for_the_argument__1__failed_attempting_to_convert_it_to_a_full_file_path_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The argument {0} requires a value and must be specified in the format --name=value.
/// </summary>
public static string ValueMissingException_ValueMissingException_ {
get {
return ResourceManager.GetString("ValueMissingException_ValueMissingException_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' for the argument {1} must be between {2} and {3}..
/// </summary>
public static string ValueOutOfRangeDoubleException_ValueOutOfRangeException_The_value___0___for_the_argument__1__must_be_between__2__and__3__ {
get {
return ResourceManager.GetString("ValueOutOfRangeDoubleException_ValueOutOfRangeException_The_value___0___for_the_a" +
"rgument__1__must_be_between__2__and__3__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The argument {0} should not have a value specified.
/// </summary>
public static string ValueUnexpectedException_ValueUnexpectedException_The_argument__0__should_not_have_a_value_specified {
get {
return ResourceManager.GetString("ValueUnexpectedException_ValueUnexpectedException_The_argument__0__should_not_hav" +
"e_a_value_specified", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Calculating hash of input file.
/// </summary>
public static string VendorIssueHelper_ConvertBrukerToMzml_Calculating_hash_of_input_file {
get {
return ResourceManager.GetString("VendorIssueHelper_ConvertBrukerToMzml_Calculating_hash_of_input_file", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CompassXport software must be installed to import Bruker raw data files..
/// </summary>
public static string VendorIssueHelper_ConvertBrukerToMzml_CompassXport_software_must_be_installed_to_import_Bruker_raw_data_files_ {
get {
return ResourceManager.GetString("VendorIssueHelper_ConvertBrukerToMzml_CompassXport_software_must_be_installed_to_" +
"import_Bruker_raw_data_files_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure attempting to convert {0} to mzML using CompassXport..
/// </summary>
public static string VendorIssueHelper_ConvertBrukerToMzml_Failure_attempting_to_convert__0__to_mzML_using_CompassXport_ {
get {
return ResourceManager.GetString("VendorIssueHelper_ConvertBrukerToMzml_Failure_attempting_to_convert__0__to_mzML_u" +
"sing_CompassXport_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure attempting to convert sample {0} in {1} to mzXML to work around a performance issue in the AB Sciex WiffFileDataReader library..
/// </summary>
public static string VendorIssueHelper_ConvertLocalWiffToMzxml_Failure_attempting_to_convert_sample__0__in__1__to_mzXML_to_work_around_a_performance_issue_in_the_AB_Sciex_WiffFileDataReader_library {
get {
return ResourceManager.GetString("VendorIssueHelper_ConvertLocalWiffToMzxml_Failure_attempting_to_convert_sample__0" +
"__in__1__to_mzXML_to_work_around_a_performance_issue_in_the_AB_Sciex_WiffFileDat" +
"aReader_library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Converting {0} to xml.
/// </summary>
public static string VendorIssueHelper_ConvertPilotFiles_Converting__0__to_xml {
get {
return ResourceManager.GetString("VendorIssueHelper_ConvertPilotFiles_Converting__0__to_xml", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure attempting to convert file {0} to .group.xml..
/// </summary>
public static string VendorIssueHelper_ConvertPilotFiles_Failure_attempting_to_convert_file__0__to__group_xml_ {
get {
return ResourceManager.GetString("VendorIssueHelper_ConvertPilotFiles_Failure_attempting_to_convert_file__0__to__gr" +
"oup_xml_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ProteinPilot software (trial or full version) must be installed to convert '.group' files to compatible '.group.xml' files..
/// </summary>
public static string VendorIssueHelper_ConvertPilotFiles_ProteinPilot_software__trial_or_full_version__must_be_installed_to_convert___group__files_to_compatible___group_xml__files_ {
get {
return ResourceManager.GetString("VendorIssueHelper_ConvertPilotFiles_ProteinPilot_software__trial_or_full_version_" +
"_must_be_installed_to_convert___group__files_to_compatible___group_xml__files_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find {0} or {1} in directory {2}. Please reinstall ProteinPilot software to be able to handle .group files..
/// </summary>
public static string VendorIssueHelper_ConvertPilotFiles_Unable_to_find__0__or__1__in_directory__2____Please_reinstall_ProteinPilot_software_to_be_able_to_handle__group_files_ {
get {
return ResourceManager.GetString("VendorIssueHelper_ConvertPilotFiles_Unable_to_find__0__or__1__in_directory__2____" +
"Please_reinstall_ProteinPilot_software_to_be_able_to_handle__group_files_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please install Analyst, or run this import on a computure with Analyst installed.
/// </summary>
public static string VendorIssueHelper_ConvertWiffToMzxml_Please_install_Analyst__or_run_this_import_on_a_computure_with_Analyst_installed {
get {
return ResourceManager.GetString("VendorIssueHelper_ConvertWiffToMzxml_Please_install_Analyst__or_run_this_import_o" +
"n_a_computure_with_Analyst_installed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file {0} cannot be imported by the AB SCIEX WiffFileDataReader library in a reasonable time frame ({1:F02} min)..
/// </summary>
public static string VendorIssueHelper_ConvertWiffToMzxml_The_file__0__cannot_be_imported_by_the_AB_SCIEX_WiffFileDataReader_library_in_a_reasonable_time_frame_1_F02_min {
get {
return ResourceManager.GetString("VendorIssueHelper_ConvertWiffToMzxml_The_file__0__cannot_be_imported_by_the_AB_SC" +
"IEX_WiffFileDataReader_library_in_a_reasonable_time_frame_1_F02_min", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to To work around this issue requires Analyst to be installed on the computer running {0}..
/// </summary>
public static string VendorIssueHelper_ConvertWiffToMzxml_To_work_around_this_issue_requires_Analyst_to_be_installed_on_the_computer_running__0__ {
get {
return ResourceManager.GetString("VendorIssueHelper_ConvertWiffToMzxml_To_work_around_this_issue_requires_Analyst_t" +
"o_be_installed_on_the_computer_running__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Convert to mzXML work-around for {0}.
/// </summary>
public static string VendorIssueHelper_CreateTempFileSubstitute_Convert_to_mzXML_work_around_for__0__ {
get {
return ResourceManager.GetString("VendorIssueHelper_CreateTempFileSubstitute_Convert_to_mzXML_work_around_for__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Local copy work-around for {0}.
/// </summary>
public static string VendorIssueHelper_CreateTempFileSubstitute_Local_copy_work_around_for__0__ {
get {
return ResourceManager.GetString("VendorIssueHelper_CreateTempFileSubstitute_Local_copy_work_around_for__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Click 'Embedded' to use embedded spectra.
///Click 'Retry' to try building again after placing the original spectrum files in one of the directories listed above..
/// </summary>
public static string VendorIssueHelper_ShowLibraryMissingExternalSpectraError_ButtonDescriptions {
get {
return ResourceManager.GetString("VendorIssueHelper_ShowLibraryMissingExternalSpectraError_ButtonDescriptions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to While searching for the spectrum file for the MaxQuant input file '{0}', the following basename could not be found with any of the supported file extensions ({3}):
///
///{1}
///
///In any of the following directories:
///
///{2}
///
///If you do not have the original file, you may build the library with embedded spectra from the input file. However, fragment ions in MaxQuant embedded spectra are charge state deconvoluted, and will contain only singly charged fragment ions which may not be representative of intensities measured by [rest of string was truncated]";.
/// </summary>
public static string VendorIssueHelper_ShowLibraryMissingExternalSpectrumFileError {
get {
return ResourceManager.GetString("VendorIssueHelper_ShowLibraryMissingExternalSpectrumFileError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to While searching for spectrum files for the MaxQuant input file '{0}', the following basenames could not be found with any of the supported file extensions ({3}):
///
///{1}
///
///In any of the following directories:
///
///{2}
///
///If you do not have the original files, you may build the library with embedded spectra from the input file. However, fragment ions in MaxQuant embedded spectra are charge state deconvoluted, and will contain only singly charged fragment ions which may not be representative of intensities measured by [rest of string was truncated]";.
/// </summary>
public static string VendorIssueHelper_ShowLibraryMissingExternalSpectrumFilesError {
get {
return ResourceManager.GetString("VendorIssueHelper_ShowLibraryMissingExternalSpectrumFilesError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}{1} library {2} will be ignored..
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides__0__1__library__2__will_be_ignored {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides__0__1__library__2__will_be_ignored", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} and {1} library {2} will be ignored..
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides__0__and__1__library__2__will_be_ignored {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides__0__and__1__library__2__will_be_ignored", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} existing.
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides__0__existing {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides__0__existing", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} proteins,.
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides__0__proteins {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides__0__proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0} unmatched.
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides__0__unmatched {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides__0__unmatched", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add All.
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_Add_All {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_Add_All", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add all peptides from {0} library.
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_Add_all_peptides_from__0__library {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_Add_all_peptides_from__0__library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All library peptides already exist in the current document..
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_All_library_peptides_already_exist_in_the_current_document {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_All_library_peptides_already_exist_in_the_current_d" +
"ocument", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to entries.
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_entries {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_entries", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to entry.
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_entry {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_entry", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Matching Molecules.
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_Matching_Molecules {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_Matching_Molecules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Matching molecules to the current document settings.
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_Matching_molecules_to_the_current_document_settings {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_Matching_molecules_to_the_current_document_settings" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Matching Peptides.
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_Matching_Peptides {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_Matching_Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Matching peptides to the current document settings.
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_Matching_peptides_to_the_current_document_settings {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_Matching_peptides_to_the_current_document_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No peptides match the current document settings..
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_No_peptides_match_the_current_document_settings {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_No_peptides_match_the_current_document_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please retry this operation..
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_Please_retry_this_operation {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_Please_retry_this_operation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The document changed during processing..
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_The_document_changed_during_processing {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_The_document_changed_during_processing", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This operation will add {0} {1} molecules, {2} precursors and {3} transitions to the document..
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_This_operation_will_add__0__1__molecules__2__precursors_and__3__transitions_to_the_document {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_This_operation_will_add__0__1__molecules__2__precur" +
"sors_and__3__transitions_to_the_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This operation will add {0} {1} peptides, {2} precursors and {3} transitions to the document..
/// </summary>
public static string ViewLibraryDlg_AddAllPeptides_This_operation_will_add__0__1__peptides__2__precursors_and__3__transitions_to_the_document {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddAllPeptides_This_operation_will_add__0__1__peptides__2__precurs" +
"ors_and__3__transitions_to_the_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add library peptide {0}.
/// </summary>
public static string ViewLibraryDlg_AddPeptide_Add_library_peptide__0__ {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddPeptide_Add_library_peptide__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modifications for this peptide do not match current document settings..
/// </summary>
public static string ViewLibraryDlg_AddPeptide_Modifications_for_this_peptide_do_not_match_current_document_settings {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddPeptide_Modifications_for_this_peptide_do_not_match_current_doc" +
"ument_settings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The peptide {0} already exists with charge {1} in the current document..
/// </summary>
public static string ViewLibraryDlg_AddPeptide_The_peptide__0__already_exists_with_charge__1__in_the_current_document {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddPeptide_The_peptide__0__already_exists_with_charge__1__in_the_c" +
"urrent_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor m/z {0:F04} is not measured by the current DIA isolation scheme..
/// </summary>
public static string ViewLibraryDlg_AddPeptide_The_precursor_m_z__0_F04__is_not_measured_by_the_current_DIA_isolation_scheme_ {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddPeptide_The_precursor_m_z__0_F04__is_not_measured_by_the_curren" +
"t_DIA_isolation_scheme_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The precursor m/z {0:F04} is outside the instrument range {1} to {2}..
/// </summary>
public static string ViewLibraryDlg_AddPeptide_The_precursor_m_z__0_F04__is_outside_the_instrument_range__1__to__2__ {
get {
return ResourceManager.GetString("ViewLibraryDlg_AddPeptide_The_precursor_m_z__0_F04__is_outside_the_instrument_ran" +
"ge__1__to__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add Library.
/// </summary>
public static string ViewLibraryDlg_CheckLibraryInSettings_Add_Library {
get {
return ResourceManager.GetString("ViewLibraryDlg_CheckLibraryInSettings_Add_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The library {0} is not currently added to your document..
/// </summary>
public static string ViewLibraryDlg_CheckLibraryInSettings_The_library__0__is_not_currently_added_to_your_document {
get {
return ResourceManager.GetString("ViewLibraryDlg_CheckLibraryInSettings_The_library__0__is_not_currently_added_to_y" +
"our_document", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Would you like to add it?.
/// </summary>
public static string ViewLibraryDlg_CheckLibraryInSettings_Would_you_like_to_add_it {
get {
return ResourceManager.GetString("ViewLibraryDlg_CheckLibraryInSettings_Would_you_like_to_add_it", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A background proteome is required to associate proteins..
/// </summary>
public static string ViewLibraryDlg_EnsureBackgroundProteome_A_background_proteome_is_required_to_associate_proteins {
get {
return ResourceManager.GetString("ViewLibraryDlg_EnsureBackgroundProteome_A_background_proteome_is_required_to_asso" +
"ciate_proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The background proteome must be digested in order to associate proteins..
/// </summary>
public static string ViewLibraryDlg_EnsureBackgroundProteome_The_background_proteome_must_be_digested_in_order_to_associate_proteins {
get {
return ResourceManager.GetString("ViewLibraryDlg_EnsureBackgroundProteome_The_background_proteome_must_be_digested_" +
"in_order_to_associate_proteins", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while trying to process the file {0}..
/// </summary>
public static string ViewLibraryDlg_EnsureDigested_An_error_occurred_while_trying_to_process_the_file__0__ {
get {
return ResourceManager.GetString("ViewLibraryDlg_EnsureDigested_An_error_occurred_while_trying_to_process_the_file_" +
"_0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copying database.
/// </summary>
public static string ViewLibraryDlg_EnsureDigested_Copying_database {
get {
return ResourceManager.GetString("ViewLibraryDlg_EnsureDigested_Copying_database", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The background proteome '{0}' is in an older format. In order to be able to efficiently find peptide sequences, the background proteome should be upgraded to the latest version. Do you want to upgrade the background proteome now?.
/// </summary>
public static string ViewLibraryDlg_EnsureDigested_The_background_proteome___0___is_in_an_older_format___In_order_to_be_able_to_efficiently_find_peptide_sequences__the_background_proteome_should_be_upgraded_to_the_latest_version___Do_you_want_to_upgrade_the_background_proteome_now_ {
get {
return ResourceManager.GetString(@"ViewLibraryDlg_EnsureDigested_The_background_proteome___0___is_in_an_older_format___In_order_to_be_able_to_efficiently_find_peptide_sequences__the_background_proteome_should_be_upgraded_to_the_latest_version___Do_you_want_to_upgrade_the_background_proteome_now_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred attempting to import the {0} library..
/// </summary>
public static string ViewLibraryDlg_LoadLibrary_An_error_occurred_attempting_to_import_the__0__library {
get {
return ResourceManager.GetString("ViewLibraryDlg_LoadLibrary_An_error_occurred_attempting_to_import_the__0__library" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading Library.
/// </summary>
public static string ViewLibraryDlg_LoadLibrary_Loading_Library {
get {
return ResourceManager.GetString("ViewLibraryDlg_LoadLibrary_Loading_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}Would you like to use the Unimod definitions for {1} modifications? The document will not change until peptides with these modifications are added..
/// </summary>
public static string ViewLibraryDlg_MatchModifications__0__Would_you_like_to_use_the_Unimod_definitions_for__1__modifications_The_document_will_not_change_until_peptides_with_these_modifications_are_added {
get {
return ResourceManager.GetString("ViewLibraryDlg_MatchModifications__0__Would_you_like_to_use_the_Unimod_definition" +
"s_for__1__modifications_The_document_will_not_change_until_peptides_with_these_m" +
"odifications_are_added", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add modifications.
/// </summary>
public static string ViewLibraryDlg_MatchModifications_Add_modifications {
get {
return ResourceManager.GetString("ViewLibraryDlg_MatchModifications_Add_modifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No.
/// </summary>
public static string ViewLibraryDlg_MatchModifications_No {
get {
return ResourceManager.GetString("ViewLibraryDlg_MatchModifications_No", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to the matching.
/// </summary>
public static string ViewLibraryDlg_MatchModifications_the_matching {
get {
return ResourceManager.GetString("ViewLibraryDlg_MatchModifications_the_matching", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to these.
/// </summary>
public static string ViewLibraryDlg_MatchModifications_these {
get {
return ResourceManager.GetString("ViewLibraryDlg_MatchModifications_these", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This library appears to contain the following modifications..
/// </summary>
public static string ViewLibraryDlg_MatchModifications_This_library_appears_to_contain_the_following_modifications {
get {
return ResourceManager.GetString("ViewLibraryDlg_MatchModifications_This_library_appears_to_contain_the_following_m" +
"odifications", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Yes.
/// </summary>
public static string ViewLibraryDlg_MatchModifications_Yes {
get {
return ResourceManager.GetString("ViewLibraryDlg_MatchModifications_Yes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Updating list of peptides.
/// </summary>
public static string ViewLibraryDlg_UpdateListPeptide_Updating_list_of_peptides {
get {
return ResourceManager.GetString("ViewLibraryDlg_UpdateListPeptide_Updating_list_of_peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Molecules {0} through {1} of {2} total..
/// </summary>
public static string ViewLibraryDlg_UpdateStatusArea_Molecules__0__through__1__of__2__total_ {
get {
return ResourceManager.GetString("ViewLibraryDlg_UpdateStatusArea_Molecules__0__through__1__of__2__total_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Page {0} of {1}.
/// </summary>
public static string ViewLibraryDlg_UpdateStatusArea_Page__0__of__1__ {
get {
return ResourceManager.GetString("ViewLibraryDlg_UpdateStatusArea_Page__0__of__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Peptides {0} through {1} of {2} total..
/// </summary>
public static string ViewLibraryDlg_UpdateStatusArea_Peptides__0__through__1__of__2__total {
get {
return ResourceManager.GetString("ViewLibraryDlg_UpdateStatusArea_Peptides__0__through__1__of__2__total", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CCS: .
/// </summary>
public static string ViewLibraryDlg_UpdateUI_CCS__ {
get {
return ResourceManager.GetString("ViewLibraryDlg_UpdateUI_CCS__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure loading spectrum. Library may be corrupted..
/// </summary>
public static string ViewLibraryDlg_UpdateUI_Failure_loading_spectrum_Library_may_be_corrupted {
get {
return ResourceManager.GetString("ViewLibraryDlg_UpdateUI_Failure_loading_spectrum_Library_may_be_corrupted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File.
/// </summary>
public static string ViewLibraryDlg_UpdateUI_File {
get {
return ResourceManager.GetString("ViewLibraryDlg_UpdateUI_File", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to IM: .
/// </summary>
public static string ViewLibraryDlg_UpdateUI_IM__ {
get {
return ResourceManager.GetString("ViewLibraryDlg_UpdateUI_IM__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to RT.
/// </summary>
public static string ViewLibraryDlg_UpdateUI_RT {
get {
return ResourceManager.GetString("ViewLibraryDlg_UpdateUI_RT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unauthorized access attempting to read from library..
/// </summary>
public static string ViewLibraryDlg_UpdateUI_Unauthorized_access_attempting_to_read_from_library_ {
get {
return ResourceManager.GetString("ViewLibraryDlg_UpdateUI_Unauthorized_access_attempting_to_read_from_library_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The library {0} is no longer available in the Skyline settings. Reload the library explorer?.
/// </summary>
public static string ViewLibraryDlg_ViewLibraryDlg_Activated_The_library__0__is_no_longer_available_in_the_Skyline_settings__Reload_the_library_explorer_ {
get {
return ResourceManager.GetString("ViewLibraryDlg_ViewLibraryDlg_Activated_The_library__0__is_no_longer_available_in" +
"_the_Skyline_settings__Reload_the_library_explorer_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There are no libraries in the current settings..
/// </summary>
public static string ViewLibraryDlg_ViewLibraryDlg_Activated_There_are_no_libraries_in_the_current_settings {
get {
return ResourceManager.GetString("ViewLibraryDlg_ViewLibraryDlg_Activated_There_are_no_libraries_in_the_current_set" +
"tings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library Molecules.
/// </summary>
public static string ViewLibraryPepMatching_AddPeptidesToLibraryGroup_Library_Molecules {
get {
return ResourceManager.GetString("ViewLibraryPepMatching_AddPeptidesToLibraryGroup_Library_Molecules", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Library Peptides.
/// </summary>
public static string ViewLibraryPepMatching_AddPeptidesToLibraryGroup_Library_Peptides {
get {
return ResourceManager.GetString("ViewLibraryPepMatching_AddPeptidesToLibraryGroup_Library_Peptides", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Skipping {0} already present.
/// </summary>
public static string ViewLibraryPepMatching_AddProteomePeptides_Skipping__0__already_present {
get {
return ResourceManager.GetString("ViewLibraryPepMatching_AddProteomePeptides_Skipping__0__already_present", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}{1} m/z.
/// </summary>
public static string ViewLibSpectrumGraphItem_Title__0__1_ {
get {
return ResourceManager.GetString("ViewLibSpectrumGraphItem_Title__0__1_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}{1}, Charge {2}.
/// </summary>
public static string ViewLibSpectrumGraphItem_Title__0__1__Charge__2__ {
get {
return ResourceManager.GetString("ViewLibSpectrumGraphItem_Title__0__1__Charge__2__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap Wand {
get {
object obj = ResourceManager.GetObject("Wand", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WandProhibit {
get {
object obj = ResourceManager.GetObject("WandProhibit", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap warning {
get {
object obj = ResourceManager.GetObject("warning", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Failed to find a valid MassLynx installation..
/// </summary>
public static string WatersMethodExporter_EnsureLibraries_Failed_to_find_a_valid_MassLynx_installation {
get {
return ResourceManager.GetString("WatersMethodExporter_EnsureLibraries_Failed_to_find_a_valid_MassLynx_installation" +
"", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to MassLynx may not be installed correctly. The library {0} could not be found..
/// </summary>
public static string WatersMethodExporter_EnsureLibraries_MassLynx_may_not_be_installed_correctly_The_library__0__could_not_be_found {
get {
return ResourceManager.GetString("WatersMethodExporter_EnsureLibraries_MassLynx_may_not_be_installed_correctly_The_" +
"library__0__could_not_be_found", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Waters method creation software may not be installed correctly..
/// </summary>
public static string WatersMethodExporter_EnsureLibraries_Waters_method_creation_software_may_not_be_installed_correctly {
get {
return ResourceManager.GetString("WatersMethodExporter_EnsureLibraries_Waters_method_creation_software_may_not_be_i" +
"nstalled_correctly", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure saving temporary post data to disk..
/// </summary>
public static string WebHelpers_PostToLink_Failure_saving_temporary_post_data_to_disk_ {
get {
return ResourceManager.GetString("WebHelpers_PostToLink_Failure_saving_temporary_post_data_to_disk_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File was not uploaded to the server. Please try again, or if the problem persists, please contact your Panorama server administrator..
/// </summary>
public static string WebPanoramaPublishClient_ConfirmFileOnServer_File_was_not_uploaded_to_the_server__Please_try_again__or_if_the_problem_persists__please_contact_your_Panorama_server_administrator_ {
get {
return ResourceManager.GetString("WebPanoramaPublishClient_ConfirmFileOnServer_File_was_not_uploaded_to_the_server_" +
"_Please_try_again__or_if_the_problem_persists__please_contact_your_Panorama_serv" +
"er_administrator_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error deleting temporary zip file: .
/// </summary>
public static string WebPanoramaPublishClient_DeleteTempZipFile_Error_deleting_temporary_zip_file__ {
get {
return ResourceManager.GetString("WebPanoramaPublishClient_DeleteTempZipFile_Error_deleting_temporary_zip_file__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure retrieving folder information from {0}.
/// </summary>
public static string WebPanoramaPublishClient_GetInfoForFolders_Failure_retrieving_folder_information_from__0_ {
get {
return ResourceManager.GetString("WebPanoramaPublishClient_GetInfoForFolders_Failure_retrieving_folder_information_" +
"from__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error importing Skyline file on Panorama server {0}.
/// </summary>
public static string WebPanoramaPublishClient_ImportDataOnServer_Error_importing_Skyline_file_on_Panorama_server__0_ {
get {
return ResourceManager.GetString("WebPanoramaPublishClient_ImportDataOnServer_Error_importing_Skyline_file_on_Panor" +
"ama_server__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Error renaming temporary zip file: .
/// </summary>
public static string WebPanoramaPublishClient_RenameTempZipFile_Error_renaming_temporary_zip_file__ {
get {
return ResourceManager.GetString("WebPanoramaPublishClient_RenameTempZipFile_Error_renaming_temporary_zip_file__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Deleting temporary file on server.
/// </summary>
public static string WebPanoramaPublishClient_SendZipFile_Deleting_temporary_file_on_server {
get {
return ResourceManager.GetString("WebPanoramaPublishClient_SendZipFile_Deleting_temporary_file_on_server", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Renaming temporary file on server.
/// </summary>
public static string WebPanoramaPublishClient_SendZipFile_Renaming_temporary_file_on_server {
get {
return ResourceManager.GetString("WebPanoramaPublishClient_SendZipFile_Renaming_temporary_file_on_server", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Status on server is: {0}.
/// </summary>
public static string WebPanoramaPublishClient_SendZipFile_Status_on_server_is___0_ {
get {
return ResourceManager.GetString("WebPanoramaPublishClient_SendZipFile_Status_on_server_is___0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Waiting for data import completion....
/// </summary>
public static string WebPanoramaPublishClient_SendZipFile_Waiting_for_data_import_completion___ {
get {
return ResourceManager.GetString("WebPanoramaPublishClient_SendZipFile_Waiting_for_data_import_completion___", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Importing data. {0}% complete..
/// </summary>
public static string WebPanoramaPublishClient_updateProgressAndWait_Importing_data___0___complete_ {
get {
return ResourceManager.GetString("WebPanoramaPublishClient_updateProgressAndWait_Importing_data___0___complete_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Uploaded {0:fs} of {1:fs}.
/// </summary>
public static string WebPanoramaPublishClient_webClient_UploadProgressChanged_Uploaded__0_fs__of__1_fs_ {
get {
return ResourceManager.GetString("WebPanoramaPublishClient_webClient_UploadProgressChanged_Uploaded__0_fs__of__1_fs" +
"_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Asymmetric.
/// </summary>
public static string WindowMargin_ASYMMETRIC_Asymmetric {
get {
return ResourceManager.GetString("WindowMargin_ASYMMETRIC_Asymmetric", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to None.
/// </summary>
public static string WindowMargin_NONE_None {
get {
return ResourceManager.GetString("WindowMargin_NONE_None", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Symmetric.
/// </summary>
public static string WindowMargin_SYMMETRIC_Symmetric {
get {
return ResourceManager.GetString("WindowMargin_SYMMETRIC_Symmetric", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Extraction.
/// </summary>
public static string WindowType_EXTRACTION_Extraction {
get {
return ResourceManager.GetString("WindowType_EXTRACTION_Extraction", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Measurement.
/// </summary>
public static string WindowType_MEASUREMENT_Measurement {
get {
return ResourceManager.GetString("WindowType_MEASUREMENT_Measurement", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WizardBlankDocument {
get {
object obj = ResourceManager.GetObject("WizardBlankDocument", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WizardFasta {
get {
object obj = ResourceManager.GetObject("WizardFasta", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WizardImportPeptide {
get {
object obj = ResourceManager.GetObject("WizardImportPeptide", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WizardImportProteins {
get {
object obj = ResourceManager.GetObject("WizardImportProteins", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WizardImportTransition {
get {
object obj = ResourceManager.GetObject("WizardImportTransition", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WizardMoleculeIcon {
get {
object obj = ResourceManager.GetObject("WizardMoleculeIcon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WizardPeptideIcon {
get {
object obj = ResourceManager.GetObject("WizardPeptideIcon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WizardPeptideSearchDDA {
get {
object obj = ResourceManager.GetObject("WizardPeptideSearchDDA", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WizardPeptideSearchDIA {
get {
object obj = ResourceManager.GetObject("WizardPeptideSearchDIA", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WizardPeptideSearchPRM {
get {
object obj = ResourceManager.GetObject("WizardPeptideSearchPRM", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap WizardTransitionIcon {
get {
object obj = ResourceManager.GetObject("WizardTransitionIcon", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Data truncation in library header. File may be corrupted..
/// </summary>
public static string XHunterLibrary_CreateCache_Data_truncation_in_library_header_File_may_be_corrupted {
get {
return ResourceManager.GetString("XHunterLibrary_CreateCache_Data_truncation_in_library_header_File_may_be_corrupte" +
"d", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Building binary cache for {0} library.
/// </summary>
public static string XHunterLibrary_Load_Building_binary_cache_for__0__library {
get {
return ResourceManager.GetString("XHunterLibrary_Load_Building_binary_cache_for__0__library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed loading library '{0}'..
/// </summary>
public static string XHunterLibrary_Load_Failed_loading_library__0__ {
get {
return ResourceManager.GetString("XHunterLibrary_Load_Failed_loading_library__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid precursor charge found. File may be corrupted..
/// </summary>
public static string XHunterLibrary_Load_Invalid_precursor_charge_found_File_may_be_corrupted {
get {
return ResourceManager.GetString("XHunterLibrary_Load_Invalid_precursor_charge_found_File_may_be_corrupted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loading {0} library.
/// </summary>
public static string XHunterLibrary_Load_Loading__0__library {
get {
return ResourceManager.GetString("XHunterLibrary_Load_Loading__0__library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure trying to read peaks.
/// </summary>
public static string XHunterLibrary_ReadSpectrum_Failure_trying_to_read_peaks {
get {
return ResourceManager.GetString("XHunterLibrary_ReadSpectrum_Failure_trying_to_read_peaks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to GPM Spectral Library.
/// </summary>
public static string XHunterLibrary_SpecFilter_GPM_Spectral_Library {
get {
return ResourceManager.GetString("XHunterLibrary_SpecFilter_GPM_Spectral_Library", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Expect.
/// </summary>
public static string XHunterLibSpec_PEP_RANK_EXPECT_Expect {
get {
return ResourceManager.GetString("XHunterLibSpec_PEP_RANK_EXPECT_Expect", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Processed intensity.
/// </summary>
public static string XHunterLibSpec_PEP_RANK_PROCESSED_INTENSITY_Processed_intensity {
get {
return ResourceManager.GetString("XHunterLibSpec_PEP_RANK_PROCESSED_INTENSITY_Processed_intensity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Deserialize.
/// </summary>
public static string XmlElementHelper_Deserialize_Deserialize {
get {
return ResourceManager.GetString("XmlElementHelper_Deserialize_Deserialize", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The class {0} has no {1}..
/// </summary>
public static string XmlElementHelper_XmlElementHelper_The_class__0__has_no__1__ {
get {
return ResourceManager.GetString("XmlElementHelper_XmlElementHelper_The_class__0__has_no__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected failure writing transitions..
/// </summary>
public static string XmlMassListExporter_Export_Unexpected_failure_writing_transitions {
get {
return ResourceManager.GetString("XmlMassListExporter_Export_Unexpected_failure_writing_transitions", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Name property may not be missing or empty..
/// </summary>
public static string XmlNamedElement_Validate_Name_property_may_not_be_missing_or_empty {
get {
return ResourceManager.GetString("XmlNamedElement_Validate_Name_property_may_not_be_missing_or_empty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempt to write scheduling parameters failed..
/// </summary>
public static string XmlThermoMassListExporter_WriteTransition_Attempt_to_write_scheduling_parameters_failed {
get {
return ResourceManager.GetString("XmlThermoMassListExporter_WriteTransition_Attempt_to_write_scheduling_parameters_" +
"failed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The value '{0}' is not valid for the attribute {1}..
/// </summary>
public static string XmlUtil_GetAttribute_The_value__0__is_not_valid_for_the_attribute__1__ {
get {
return ResourceManager.GetString("XmlUtil_GetAttribute_The_value__0__is_not_valid_for_the_attribute__1__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to It may have been truncated during file transfer..
/// </summary>
public static string XmlUtil_GetInvalidDataMessage_It_may_have_been_truncated_during_file_transfer {
get {
return ResourceManager.GetString("XmlUtil_GetInvalidDataMessage_It_may_have_been_truncated_during_file_transfer", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file contains an error on line {0} at column {1}..
/// </summary>
public static string XmlUtil_GetInvalidDataMessage_The_file_contains_an_error_on_line__0__at_column__1__ {
get {
return ResourceManager.GetString("XmlUtil_GetInvalidDataMessage_The_file_contains_an_error_on_line__0__at_column__1" +
"__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file does not appear to be valid XML..
/// </summary>
public static string XmlUtil_GetInvalidDataMessage_The_file_does_not_appear_to_be_valid_XML {
get {
return ResourceManager.GetString("XmlUtil_GetInvalidDataMessage_The_file_does_not_appear_to_be_valid_XML", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The file is empty..
/// </summary>
public static string XmlUtil_GetInvalidDataMessage_The_file_is_empty {
get {
return ResourceManager.GetString("XmlUtil_GetInvalidDataMessage_The_file_is_empty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempt to serialize list containing invalid type {0}..
/// </summary>
public static string XmlUtil_WriteElements_Attempt_to_serialize_list_containing_invalid_type__0__ {
get {
return ResourceManager.GetString("XmlUtil_WriteElements_Attempt_to_serialize_list_containing_invalid_type__0__", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempt to serialize list missing an element..
/// </summary>
public static string XmlUtil_WriteElements_Attempt_to_serialize_list_missing_an_element {
get {
return ResourceManager.GetString("XmlUtil_WriteElements_Attempt_to_serialize_list_missing_an_element", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed attempting to add the file {0}.
/// </summary>
public static string ZipFileShare_AddFile_Failed_attempting_to_add_the_file__0_ {
get {
return ResourceManager.GetString("ZipFileShare_AddFile_Failed_attempting_to_add_the_file__0_", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The name '{0}' is already in use from the path {1}.
/// </summary>
public static string ZipFileShare_AddFile_The_name___0___is_already_in_use_from_the_path__1_ {
get {
return ResourceManager.GetString("ZipFileShare_AddFile_The_name___0___is_already_in_use_from_the_path__1_", resourceCulture);
}
}
}
}
| 1 | 14,468 | Redo this by adding a string literal and then pressing F6 to have Resharper move it to Properties\Resources.resx which will also create this property. | ProteoWizard-pwiz | .cs |
@@ -0,0 +1,11 @@
+// +build !windows
+// Copyright 2012-2017 Apcera Inc. All rights reserved.
+
+package server
+
+// Run starts the NATS server. This wrapper function allows Windows to add a
+// hook for running NATS as a service.
+func Run(server *Server) error {
+ server.Start()
+ return nil
+} | 1 | 1 | 7,146 | Unless a log file has been specified, IMO you should set the server option to enable syslog (windows event log) here, or someplace along the service start code path. We shouldn't really rely on users to specify that when creating the service. | nats-io-nats-server | go |
|
@@ -86,8 +86,8 @@ public class TestFlinkCatalogTable extends FlinkCatalogTestBase {
Types.NestedField.optional(1, "strV", Types.StringType.get())));
Assert.assertEquals(
Arrays.asList(
- TableColumn.of("id", DataTypes.BIGINT()),
- TableColumn.of("strV", DataTypes.STRING())),
+ TableColumn.physical("id", DataTypes.BIGINT()),
+ TableColumn.physical("strV", DataTypes.STRING())),
getTableEnv().from("tl").getSchema().getTableColumns());
Assert.assertTrue(getTableEnv().getCatalog(catalogName).get().tableExists(ObjectPath.fromString("db.tl")));
} | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iceberg.flink;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.TableColumn;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.catalog.CatalogTable;
import org.apache.flink.table.catalog.ObjectPath;
import org.apache.flink.table.catalog.exceptions.TableNotExistException;
import org.apache.iceberg.AssertHelpers;
import org.apache.iceberg.ContentFile;
import org.apache.iceberg.DataFile;
import org.apache.iceberg.DataFiles;
import org.apache.iceberg.DataOperations;
import org.apache.iceberg.FileScanTask;
import org.apache.iceberg.PartitionSpec;
import org.apache.iceberg.Schema;
import org.apache.iceberg.Snapshot;
import org.apache.iceberg.Table;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.exceptions.NoSuchTableException;
import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
import org.apache.iceberg.relocated.com.google.common.collect.Maps;
import org.apache.iceberg.types.Types;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
public class TestFlinkCatalogTable extends FlinkCatalogTestBase {
public TestFlinkCatalogTable(String catalogName, Namespace baseNamepace) {
super(catalogName, baseNamepace);
}
@Before
public void before() {
super.before();
sql("CREATE DATABASE %s", flinkDatabase);
sql("USE CATALOG %s", catalogName);
sql("USE %s", DATABASE);
}
@After
public void cleanNamespaces() {
sql("DROP TABLE IF EXISTS %s.tl", flinkDatabase);
sql("DROP TABLE IF EXISTS %s.tl2", flinkDatabase);
sql("DROP DATABASE IF EXISTS %s", flinkDatabase);
super.clean();
}
@Test
public void testGetTable() {
validationCatalog.createTable(
TableIdentifier.of(icebergNamespace, "tl"),
new Schema(
Types.NestedField.optional(0, "id", Types.LongType.get()),
Types.NestedField.optional(1, "strV", Types.StringType.get())));
Assert.assertEquals(
Arrays.asList(
TableColumn.of("id", DataTypes.BIGINT()),
TableColumn.of("strV", DataTypes.STRING())),
getTableEnv().from("tl").getSchema().getTableColumns());
Assert.assertTrue(getTableEnv().getCatalog(catalogName).get().tableExists(ObjectPath.fromString("db.tl")));
}
@Test
public void testRenameTable() {
Assume.assumeFalse("HadoopCatalog does not support rename table", isHadoopCatalog);
validationCatalog.createTable(
TableIdentifier.of(icebergNamespace, "tl"),
new Schema(Types.NestedField.optional(0, "id", Types.LongType.get())));
sql("ALTER TABLE tl RENAME TO tl2");
AssertHelpers.assertThrows(
"Should fail if trying to get a nonexistent table",
ValidationException.class,
"Table `tl` was not found.",
() -> getTableEnv().from("tl")
);
Assert.assertEquals(
Collections.singletonList(TableColumn.of("id", DataTypes.BIGINT())),
getTableEnv().from("tl2").getSchema().getTableColumns());
}
@Test
public void testCreateTable() throws TableNotExistException {
sql("CREATE TABLE tl(id BIGINT)");
Table table = table("tl");
Assert.assertEquals(
new Schema(Types.NestedField.optional(1, "id", Types.LongType.get())).asStruct(),
table.schema().asStruct());
Assert.assertEquals(Maps.newHashMap(), table.properties());
CatalogTable catalogTable = catalogTable("tl");
Assert.assertEquals(TableSchema.builder().field("id", DataTypes.BIGINT()).build(), catalogTable.getSchema());
Assert.assertEquals(Maps.newHashMap(), catalogTable.getOptions());
}
@Ignore("Enable this after upgrade flink to 1.12.0, because it starts to support 'CREATE TABLE IF NOT EXISTS")
@Test
public void testCreateTableIfNotExists() {
sql("CREATE TABLE tl(id BIGINT)");
// Assert that table does exist.
Assert.assertEquals(Maps.newHashMap(), table("tl").properties());
sql("DROP TABLE tl");
AssertHelpers.assertThrows("Table 'tl' should be dropped",
NoSuchTableException.class, "Table does not exist: db.tl", () -> table("tl"));
sql("CREATE TABLE IF NO EXISTS tl(id BIGINT)");
Assert.assertEquals(Maps.newHashMap(), table("tl").properties());
sql("CREATE TABLE IF NOT EXISTS tl(id BIGINT) WITH ('location'='/tmp/location')");
Assert.assertEquals("Should still be the old table.", Maps.newHashMap(), table("tl").properties());
}
@Test
public void testCreateTableLike() throws TableNotExistException {
sql("CREATE TABLE tl(id BIGINT)");
sql("CREATE TABLE tl2 LIKE tl");
Table table = table("tl2");
Assert.assertEquals(
new Schema(Types.NestedField.optional(1, "id", Types.LongType.get())).asStruct(),
table.schema().asStruct());
Assert.assertEquals(Maps.newHashMap(), table.properties());
CatalogTable catalogTable = catalogTable("tl2");
Assert.assertEquals(TableSchema.builder().field("id", DataTypes.BIGINT()).build(), catalogTable.getSchema());
Assert.assertEquals(Maps.newHashMap(), catalogTable.getOptions());
}
@Test
public void testCreateTableLocation() {
Assume.assumeFalse("HadoopCatalog does not support creating table with location", isHadoopCatalog);
sql("CREATE TABLE tl(id BIGINT) WITH ('location'='/tmp/location')");
Table table = table("tl");
Assert.assertEquals(
new Schema(Types.NestedField.optional(1, "id", Types.LongType.get())).asStruct(),
table.schema().asStruct());
Assert.assertEquals("/tmp/location", table.location());
Assert.assertEquals(Maps.newHashMap(), table.properties());
}
@Test
public void testCreatePartitionTable() throws TableNotExistException {
sql("CREATE TABLE tl(id BIGINT, dt STRING) PARTITIONED BY(dt)");
Table table = table("tl");
Assert.assertEquals(
new Schema(
Types.NestedField.optional(1, "id", Types.LongType.get()),
Types.NestedField.optional(2, "dt", Types.StringType.get())).asStruct(),
table.schema().asStruct());
Assert.assertEquals(PartitionSpec.builderFor(table.schema()).identity("dt").build(), table.spec());
Assert.assertEquals(Maps.newHashMap(), table.properties());
CatalogTable catalogTable = catalogTable("tl");
Assert.assertEquals(
TableSchema.builder().field("id", DataTypes.BIGINT()).field("dt", DataTypes.STRING()).build(),
catalogTable.getSchema());
Assert.assertEquals(Maps.newHashMap(), catalogTable.getOptions());
Assert.assertEquals(Collections.singletonList("dt"), catalogTable.getPartitionKeys());
}
@Test
public void testLoadTransformPartitionTable() throws TableNotExistException {
Schema schema = new Schema(Types.NestedField.optional(0, "id", Types.LongType.get()));
validationCatalog.createTable(
TableIdentifier.of(icebergNamespace, "tl"), schema,
PartitionSpec.builderFor(schema).bucket("id", 100).build());
CatalogTable catalogTable = catalogTable("tl");
Assert.assertEquals(
TableSchema.builder().field("id", DataTypes.BIGINT()).build(),
catalogTable.getSchema());
Assert.assertEquals(Maps.newHashMap(), catalogTable.getOptions());
Assert.assertEquals(Collections.emptyList(), catalogTable.getPartitionKeys());
}
@Test
public void testAlterTable() throws TableNotExistException {
sql("CREATE TABLE tl(id BIGINT) WITH ('oldK'='oldV')");
Map<String, String> properties = Maps.newHashMap();
properties.put("oldK", "oldV");
// new
sql("ALTER TABLE tl SET('newK'='newV')");
properties.put("newK", "newV");
Assert.assertEquals(properties, table("tl").properties());
// update old
sql("ALTER TABLE tl SET('oldK'='oldV2')");
properties.put("oldK", "oldV2");
Assert.assertEquals(properties, table("tl").properties());
// remove property
CatalogTable catalogTable = catalogTable("tl");
properties.remove("oldK");
getTableEnv().getCatalog(getTableEnv().getCurrentCatalog()).get().alterTable(
new ObjectPath(DATABASE, "tl"), catalogTable.copy(properties), false);
Assert.assertEquals(properties, table("tl").properties());
}
@Test
public void testRelocateTable() {
Assume.assumeFalse("HadoopCatalog does not support relocate table", isHadoopCatalog);
sql("CREATE TABLE tl(id BIGINT)");
sql("ALTER TABLE tl SET('location'='/tmp/location')");
Assert.assertEquals("/tmp/location", table("tl").location());
}
@Test
public void testSetCurrentAndCherryPickSnapshotId() {
sql("CREATE TABLE tl(c1 INT, c2 STRING, c3 STRING) PARTITIONED BY (c1)");
Table table = table("tl");
DataFile fileA = DataFiles.builder(table.spec())
.withPath("/path/to/data-a.parquet")
.withFileSizeInBytes(10)
.withPartitionPath("c1=0") // easy way to set partition data for now
.withRecordCount(1)
.build();
DataFile fileB = DataFiles.builder(table.spec())
.withPath("/path/to/data-b.parquet")
.withFileSizeInBytes(10)
.withPartitionPath("c1=1") // easy way to set partition data for now
.withRecordCount(1)
.build();
DataFile replacementFile = DataFiles.builder(table.spec())
.withPath("/path/to/data-a-replacement.parquet")
.withFileSizeInBytes(10)
.withPartitionPath("c1=0") // easy way to set partition data for now
.withRecordCount(1)
.build();
table.newAppend()
.appendFile(fileA)
.commit();
long snapshotId = table.currentSnapshot().snapshotId();
// stage an overwrite that replaces FILE_A
table.newReplacePartitions()
.addFile(replacementFile)
.stageOnly()
.commit();
Snapshot staged = Iterables.getLast(table.snapshots());
Assert.assertEquals("Should find the staged overwrite snapshot", DataOperations.OVERWRITE, staged.operation());
// add another append so that the original commit can't be fast-forwarded
table.newAppend()
.appendFile(fileB)
.commit();
// test cherry pick
sql("ALTER TABLE tl SET('cherry-pick-snapshot-id'='%s')", staged.snapshotId());
validateTableFiles(table, fileB, replacementFile);
// test set current snapshot
sql("ALTER TABLE tl SET('current-snapshot-id'='%s')", snapshotId);
validateTableFiles(table, fileA);
}
private void validateTableFiles(Table tbl, DataFile... expectedFiles) {
tbl.refresh();
Set<CharSequence> expectedFilePaths = Arrays.stream(expectedFiles).map(DataFile::path).collect(Collectors.toSet());
Set<CharSequence> actualFilePaths = StreamSupport.stream(tbl.newScan().planFiles().spliterator(), false)
.map(FileScanTask::file).map(ContentFile::path)
.collect(Collectors.toSet());
Assert.assertEquals("Files should match", expectedFilePaths, actualFilePaths);
}
private Table table(String name) {
return validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, name));
}
private CatalogTable catalogTable(String name) throws TableNotExistException {
return (CatalogTable) getTableEnv().getCatalog(getTableEnv().getCurrentCatalog()).get()
.getTable(new ObjectPath(DATABASE, name));
}
}
| 1 | 30,627 | It's strange here, because I saw the `TableColumn` is marked as `PublicEvolving`, but after released flink 1.12.0 it did not have any Interface compatibility guarantee. At least, it should marked as `deprecated`, and keep it a major release. | apache-iceberg | java |
@@ -104,7 +104,7 @@ public abstract class ConnectionPageAbstract extends DialogPage implements IData
if (!site.isNew() && !site.getDriver().isEmbedded()) {
Link netConfigLink = new Link(panel, SWT.NONE);
- netConfigLink.setText("<a>Network settings (SSH, SSL, Proxy, ...)</a>");
+ netConfigLink.setText("<a>" + CoreMessages.dialog_connection_edit_wizard_conn_conf_network_link + "</a>");
netConfigLink.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) { | 1 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.dialogs.connection;
import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration;
import org.jkiss.dbeaver.model.connection.DBPDriver;
import org.jkiss.dbeaver.ui.IDataSourceConnectionEditor;
import org.jkiss.dbeaver.ui.IDataSourceConnectionEditorSite;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.utils.CommonUtils;
/**
* ConnectionPageAbstract
*/
public abstract class ConnectionPageAbstract extends DialogPage implements IDataSourceConnectionEditor
{
protected IDataSourceConnectionEditorSite site;
// Driver name
protected Text driverText;
public IDataSourceConnectionEditorSite getSite() {
return site;
}
@Override
public void dispose() {
super.dispose();
}
@Override
public void setSite(IDataSourceConnectionEditorSite site)
{
this.site = site;
}
protected boolean isCustomURL()
{
return false;
}
@Override
public void loadSettings() {
DBPDriver driver = site.getDriver();
if (driver != null && driverText != null) {
driverText.setText(CommonUtils.toString(driver.getFullName()));
}
}
@Override
public void saveSettings(DBPDataSourceContainer dataSource)
{
saveConnectionURL(dataSource.getConnectionConfiguration());
}
protected void saveConnectionURL(DBPConnectionConfiguration connectionInfo)
{
if (!isCustomURL()) {
connectionInfo.setUrl(
site.getDriver().getDataSourceProvider().getConnectionURL(
site.getDriver(),
connectionInfo));
}
}
protected void createDriverPanel(Composite parent) {
int numColumns = ((GridLayout) parent.getLayout()).numColumns;
Composite panel = UIUtils.createPlaceholder(parent, 4, 5);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.horizontalSpan = numColumns;
panel.setLayoutData(gd);
Composite placeholder = UIUtils.createPlaceholder(panel, 1);
gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_END);
gd.horizontalSpan = 4;
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
placeholder.setLayoutData(gd);
if (!site.isNew() && !site.getDriver().isEmbedded()) {
Link netConfigLink = new Link(panel, SWT.NONE);
netConfigLink.setText("<a>Network settings (SSH, SSL, Proxy, ...)</a>");
netConfigLink.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
site.openSettingsPage(ConnectionPageNetwork.PAGE_NAME);
}
});
gd = new GridData(GridData.HORIZONTAL_ALIGN_END);
gd.horizontalSpan = 4;
netConfigLink.setLayoutData(gd);
}
Label divLabel = new Label(panel, SWT.SEPARATOR | SWT.HORIZONTAL);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 4;
divLabel.setLayoutData(gd);
Label driverLabel = new Label(panel, SWT.NONE);
driverLabel.setText(CoreMessages.dialog_connection_driver);
gd = new GridData(GridData.HORIZONTAL_ALIGN_END);
driverLabel.setLayoutData(gd);
driverText = new Text(panel, SWT.READ_ONLY);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.grabExcessHorizontalSpace = true;
gd.horizontalSpan = 2;
//gd.widthHint = 200;
driverText.setLayoutData(gd);
Button driverButton = new Button(panel, SWT.PUSH);
driverButton.setText(CoreMessages.dialog_connection_edit_driver_button);
gd = new GridData(GridData.HORIZONTAL_ALIGN_END);
driverButton.setLayoutData(gd);
driverButton.addSelectionListener(new SelectionListener()
{
@Override
public void widgetSelected(SelectionEvent e)
{
if (site.openDriverEditor()) {
updateDriverInfo(site.getDriver());
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e)
{
}
});
}
protected void updateDriverInfo(DBPDriver driver) {
}
}
| 1 | 10,278 | I'm not sure regarding this approach, for me the whole text including anchors should go to resources like ` netConfigLink.setText(CoreMessages.dialog_connection_edit_wizard_conn_conf_network_link); ` You shouldn't concatenate translated values inside the code. If you need some params, please use NLS.bind() | dbeaver-dbeaver | java |
@@ -78,6 +78,7 @@ func (c *connectionFlowController) GetWindowUpdate() protocol.ByteCount {
func (c *connectionFlowController) EnsureMinimumWindowSize(inc protocol.ByteCount) {
c.mutex.Lock()
if inc > c.receiveWindowSize {
+ c.logger.Debugf("Increasing receive flow control window for the connection to %d kB, in response to stream flow control window increase", c.receiveWindowSize/(1<<10))
c.receiveWindowSize = utils.MinByteCount(inc, c.maxReceiveWindowSize)
c.startNewAutoTuningEpoch()
} | 1 | package flowcontrol
import (
"fmt"
"github.com/lucas-clemente/quic-go/internal/congestion"
"github.com/lucas-clemente/quic-go/internal/protocol"
"github.com/lucas-clemente/quic-go/internal/utils"
"github.com/lucas-clemente/quic-go/qerr"
)
type connectionFlowController struct {
lastBlockedAt protocol.ByteCount
baseFlowController
}
var _ ConnectionFlowController = &connectionFlowController{}
// NewConnectionFlowController gets a new flow controller for the connection
// It is created before we receive the peer's transport paramenters, thus it starts with a sendWindow of 0.
func NewConnectionFlowController(
receiveWindow protocol.ByteCount,
maxReceiveWindow protocol.ByteCount,
rttStats *congestion.RTTStats,
logger utils.Logger,
) ConnectionFlowController {
return &connectionFlowController{
baseFlowController: baseFlowController{
rttStats: rttStats,
receiveWindow: receiveWindow,
receiveWindowSize: receiveWindow,
maxReceiveWindowSize: maxReceiveWindow,
logger: logger,
},
}
}
func (c *connectionFlowController) SendWindowSize() protocol.ByteCount {
return c.baseFlowController.sendWindowSize()
}
// IsNewlyBlocked says if it is newly blocked by flow control.
// For every offset, it only returns true once.
// If it is blocked, the offset is returned.
func (c *connectionFlowController) IsNewlyBlocked() (bool, protocol.ByteCount) {
if c.sendWindowSize() != 0 || c.sendWindow == c.lastBlockedAt {
return false, 0
}
c.lastBlockedAt = c.sendWindow
return true, c.sendWindow
}
// IncrementHighestReceived adds an increment to the highestReceived value
func (c *connectionFlowController) IncrementHighestReceived(increment protocol.ByteCount) error {
c.mutex.Lock()
defer c.mutex.Unlock()
c.highestReceived += increment
if c.checkFlowControlViolation() {
return qerr.Error(qerr.FlowControlReceivedTooMuchData, fmt.Sprintf("Received %d bytes for the connection, allowed %d bytes", c.highestReceived, c.receiveWindow))
}
return nil
}
func (c *connectionFlowController) GetWindowUpdate() protocol.ByteCount {
c.mutex.Lock()
oldWindowSize := c.receiveWindowSize
offset := c.baseFlowController.getWindowUpdate()
if oldWindowSize < c.receiveWindowSize {
c.logger.Debugf("Increasing receive flow control window for the connection to %d kB", c.receiveWindowSize/(1<<10))
}
c.mutex.Unlock()
return offset
}
// EnsureMinimumWindowSize sets a minimum window size
// it should make sure that the connection-level window is increased when a stream-level window grows
func (c *connectionFlowController) EnsureMinimumWindowSize(inc protocol.ByteCount) {
c.mutex.Lock()
if inc > c.receiveWindowSize {
c.receiveWindowSize = utils.MinByteCount(inc, c.maxReceiveWindowSize)
c.startNewAutoTuningEpoch()
}
c.mutex.Unlock()
}
| 1 | 7,571 | How often do we expect this to trigger? Should we maybe put it behind an if logger.Debug()? | lucas-clemente-quic-go | go |
@@ -126,12 +126,12 @@ func Snapshot(volname string, snapname string, labels map[string]string) (string
return "", err
}
- volume, err := GetVolume(controller.address)
+ volume, err := GetVolume(controller.Address)
if err != nil {
return "", err
}
- url := controller.address + "/volumes/" + volume.Id + "?action=snapshot"
+ url := controller.Address + "/volumes/" + volume.Id + "?action=snapshot"
fmt.Println("Url is:", url)
| 1 | package command
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"regexp"
"strings"
)
var (
MaximumVolumeNameSize = 64
parsePattern = regexp.MustCompile(`(.*):(\d+)`)
)
type SnapshotCreateCommand struct {
Meta
Name string
Sname string
Labels map[string]string
}
// StringSlice is an opaque type for []string to satisfy flag.Value
type StringSlice []string
// Set appends the string value to the list of values
func (f *StringSlice) Set(value string) error {
*f = append(*f, value)
return nil
}
// String returns a readable representation of this value (for usage defaults)
func (f *StringSlice) String() string {
return fmt.Sprintf("%s", *f)
}
// Value returns the slice of strings set by this flag
func (f *StringSlice) Value() []string {
return *f
}
// Help shows helpText for a particular CLI command
func (c *SnapshotCreateCommand) Help() string {
helpText := `
Usage: maya snapshot create -volname <name> -snapname <snapshot-name>
This command will create the snapshot of a given Volume.
`
return strings.TrimSpace(helpText)
}
// Synopsis shows short information related to CLI command
func (c *SnapshotCreateCommand) Synopsis() string {
return "Create snapshot of a Volume"
}
// Run holds the flag values for CLI subcommands
func (c *SnapshotCreateCommand) Run(args []string) int {
var (
labelMap map[string]string
err error
)
flags := c.Meta.FlagSet("snapshot", FlagSetClient)
flags.Usage = func() { c.Ui.Output(c.Help()) }
flags.StringVar(&c.Name, "volname", "", "")
flags.StringVar(&c.Sname, "snapname", "", "")
//flags.String(&c.Labels, "label", "")
if err := flags.Parse(args); err != nil {
return 1
}
/* var name string
if len(c.Args()) > 0 {
name = c.Args()[0]
} */
/* var flagset *flag.FlagSet
labels := lookupStringSlice("label", flagset)
fmt.Sprint(labels)
if labels != nil {
labelMap, err = ParseLabels(labels)
if err != nil {
fmt.Printf("cannot parse backup labels")
return 1
}
}
*/
// str := os.Args[1:]
// labelMap = map[str]string
//var client ControllerClient
fmt.Println("Creating Snapshot of Volume :", c.Name)
id, err := Snapshot(c.Name, c.Sname, labelMap)
if err != nil {
log.Fatalf("Error running create snapshot command: %v", err)
return 1
}
fmt.Println("Created Snapshot is:", id)
return 0
}
func Snapshot(volname string, snapname string, labels map[string]string) (string, error) {
annotations, err := GetVolAnnotations(volname)
if err != nil || annotations == nil {
return "", err
}
if annotations.ControllerStatus != "Running" {
fmt.Println("Volume not reachable")
return "", err
}
controller, err := NewControllerClient(annotations.ControllerIP + ":9501")
if err != nil {
return "", err
}
volume, err := GetVolume(controller.address)
if err != nil {
return "", err
}
url := controller.address + "/volumes/" + volume.Id + "?action=snapshot"
fmt.Println("Url is:", url)
input := SnapshotInput{
Name: snapname,
Labels: labels,
}
output := SnapshotOutput{}
err = controller.post(url, input, &output)
if err != nil {
return "", err
}
return output.Id, err
}
func (c *ControllerClient) post(path string, req, resp interface{}) error {
return c.do("POST", path, req, resp)
}
func (c *ControllerClient) do(method, path string, req, resp interface{}) error {
b, err := json.Marshal(req)
if err != nil {
return err
}
bodyType := "application/json"
url := path
if !strings.HasPrefix(url, "http") {
url = c.address + path
}
fmt.Println("Do url:", url)
httpReq, err := http.NewRequest(method, url, bytes.NewBuffer(b))
if err != nil {
return err
}
httpReq.Header.Set("Content-Type", bodyType)
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return err
}
defer httpResp.Body.Close()
if httpResp.StatusCode >= 300 {
content, _ := ioutil.ReadAll(httpResp.Body)
return fmt.Errorf("Bad response: %d %s: %s", httpResp.StatusCode, httpResp.Status, content)
}
if resp == nil {
return nil
}
return json.NewDecoder(httpResp.Body).Decode(resp)
}
func GetVolume(path string) (*Volumes, error) {
var volume VolumeCollection
var c ControllerClient
err := c.get(path+"/volumes", &volume)
if err != nil {
return nil, err
}
if len(volume.Data) == 0 {
return nil, errors.New("No volume found")
}
return &volume.Data[0], nil
}
func (c *ControllerClient) get(path string, obj interface{}) error {
// resp, err := http.Get(c.address + path)
resp, err := http.Get(path)
if err != nil {
return err
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(obj)
}
/*func Snapshot(name string, userCreated bool, created string, labels map[string]string) error {
fmt.Println("Snapshot: %s %s UserCreated %v Created at %v, Labels %v",
r.name, name, userCreated, created, labels)
return r.doAction("snapshot",
&map[string]interface{}{
"name": name,
"usercreated": userCreated,
"created": created,
"labels": labels,
})
}*/
func ParseLabels(labels []string) (map[string]string, error) {
result := map[string]string{}
for _, label := range labels {
kv := strings.Split(label, "=")
if len(kv) != 2 {
return nil, fmt.Errorf("Invalid label not in <key>=<value> format %v", label)
}
key := kv[0]
value := kv[1]
//Well, we should rename that ValidVolumeName
if !ValidVolumeName(key) {
return nil, fmt.Errorf("Invalid key %v for label %v", key, label)
}
if !ValidVolumeName(value) {
return nil, fmt.Errorf("Invalid value %v for label %v", value, label)
}
result[key] = value
}
return result, nil
}
func ValidVolumeName(name string) bool {
if len(name) > MaximumVolumeNameSize {
return false
}
validName := regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]+$`)
return validName.MatchString(name)
}
func lookupStringSlice(name string, set *flag.FlagSet) []string {
f := set.Lookup(name)
if f != nil {
return (f.Value.(*StringSlice)).Value()
}
return nil
}
| 1 | 6,731 | How was the name `controller` arrived? Can you get a consensus for the name controller ? This may be OK for jiva. However, c-stor does not have a concept called `controller`. | openebs-maya | go |
@@ -151,6 +151,16 @@ func (v *ConfigValidator) sysctl(config *configs.Config) error {
return fmt.Errorf("sysctl %q is not allowed in the hosts network namespace", s)
}
}
+ if config.Namespaces.Contains(configs.NEWUTS) {
+ switch s {
+ case "kernel.domainname":
+ // This is namespaced and there's no explicit OCI field for it.
+ continue
+ case "kernel.hostname":
+ // This is namespaced but there's a conflicting (dedicated) OCI field for it.
+ return fmt.Errorf("sysctl %q is not allowed as it conflicts with the OCI %q field", s, "hostname")
+ }
+ }
return fmt.Errorf("sysctl %q is not in a separate kernel namespace", s)
}
| 1 | package validate
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/opencontainers/runc/libcontainer/configs"
"github.com/opencontainers/runc/libcontainer/intelrdt"
selinux "github.com/opencontainers/selinux/go-selinux"
)
type Validator interface {
Validate(*configs.Config) error
}
func New() Validator {
return &ConfigValidator{}
}
type ConfigValidator struct {
}
func (v *ConfigValidator) Validate(config *configs.Config) error {
if err := v.rootfs(config); err != nil {
return err
}
if err := v.network(config); err != nil {
return err
}
if err := v.hostname(config); err != nil {
return err
}
if err := v.security(config); err != nil {
return err
}
if err := v.usernamespace(config); err != nil {
return err
}
if err := v.sysctl(config); err != nil {
return err
}
if err := v.intelrdt(config); err != nil {
return err
}
if config.Rootless {
if err := v.rootless(config); err != nil {
return err
}
}
return nil
}
// rootfs validates if the rootfs is an absolute path and is not a symlink
// to the container's root filesystem.
func (v *ConfigValidator) rootfs(config *configs.Config) error {
if _, err := os.Stat(config.Rootfs); err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("rootfs (%s) does not exist", config.Rootfs)
}
return err
}
cleaned, err := filepath.Abs(config.Rootfs)
if err != nil {
return err
}
if cleaned, err = filepath.EvalSymlinks(cleaned); err != nil {
return err
}
if filepath.Clean(config.Rootfs) != cleaned {
return fmt.Errorf("%s is not an absolute path or is a symlink", config.Rootfs)
}
return nil
}
func (v *ConfigValidator) network(config *configs.Config) error {
if !config.Namespaces.Contains(configs.NEWNET) {
if len(config.Networks) > 0 || len(config.Routes) > 0 {
return fmt.Errorf("unable to apply network settings without a private NET namespace")
}
}
return nil
}
func (v *ConfigValidator) hostname(config *configs.Config) error {
if config.Hostname != "" && !config.Namespaces.Contains(configs.NEWUTS) {
return fmt.Errorf("unable to set hostname without a private UTS namespace")
}
return nil
}
func (v *ConfigValidator) security(config *configs.Config) error {
// restrict sys without mount namespace
if (len(config.MaskPaths) > 0 || len(config.ReadonlyPaths) > 0) &&
!config.Namespaces.Contains(configs.NEWNS) {
return fmt.Errorf("unable to restrict sys entries without a private MNT namespace")
}
if config.ProcessLabel != "" && !selinux.GetEnabled() {
return fmt.Errorf("selinux label is specified in config, but selinux is disabled or not supported")
}
return nil
}
func (v *ConfigValidator) usernamespace(config *configs.Config) error {
if config.Namespaces.Contains(configs.NEWUSER) {
if _, err := os.Stat("/proc/self/ns/user"); os.IsNotExist(err) {
return fmt.Errorf("USER namespaces aren't enabled in the kernel")
}
} else {
if config.UidMappings != nil || config.GidMappings != nil {
return fmt.Errorf("User namespace mappings specified, but USER namespace isn't enabled in the config")
}
}
return nil
}
// sysctl validates that the specified sysctl keys are valid or not.
// /proc/sys isn't completely namespaced and depending on which namespaces
// are specified, a subset of sysctls are permitted.
func (v *ConfigValidator) sysctl(config *configs.Config) error {
validSysctlMap := map[string]bool{
"kernel.msgmax": true,
"kernel.msgmnb": true,
"kernel.msgmni": true,
"kernel.sem": true,
"kernel.shmall": true,
"kernel.shmmax": true,
"kernel.shmmni": true,
"kernel.shm_rmid_forced": true,
}
for s := range config.Sysctl {
if validSysctlMap[s] || strings.HasPrefix(s, "fs.mqueue.") {
if config.Namespaces.Contains(configs.NEWIPC) {
continue
} else {
return fmt.Errorf("sysctl %q is not allowed in the hosts ipc namespace", s)
}
}
if strings.HasPrefix(s, "net.") {
if config.Namespaces.Contains(configs.NEWNET) {
if path := config.Namespaces.PathOf(configs.NEWNET); path != "" {
if err := checkHostNs(s, path); err != nil {
return err
}
}
continue
} else {
return fmt.Errorf("sysctl %q is not allowed in the hosts network namespace", s)
}
}
return fmt.Errorf("sysctl %q is not in a separate kernel namespace", s)
}
return nil
}
func (v *ConfigValidator) intelrdt(config *configs.Config) error {
if config.IntelRdt != nil {
if !intelrdt.IsEnabled() {
return fmt.Errorf("intelRdt is specified in config, but Intel RDT feature is not supported or enabled")
}
if config.IntelRdt.L3CacheSchema == "" {
return fmt.Errorf("intelRdt is specified in config, but intelRdt.l3CacheSchema is empty")
}
}
return nil
}
func isSymbolicLink(path string) (bool, error) {
fi, err := os.Lstat(path)
if err != nil {
return false, err
}
return fi.Mode()&os.ModeSymlink == os.ModeSymlink, nil
}
// checkHostNs checks whether network sysctl is used in host namespace.
func checkHostNs(sysctlConfig string, path string) error {
var currentProcessNetns = "/proc/self/ns/net"
// readlink on the current processes network namespace
destOfCurrentProcess, err := os.Readlink(currentProcessNetns)
if err != nil {
return fmt.Errorf("read soft link %q error", currentProcessNetns)
}
// First check if the provided path is a symbolic link
symLink, err := isSymbolicLink(path)
if err != nil {
return fmt.Errorf("could not check that %q is a symlink: %v", path, err)
}
if symLink == false {
// The provided namespace is not a symbolic link,
// it is not the host namespace.
return nil
}
// readlink on the path provided in the struct
destOfContainer, err := os.Readlink(path)
if err != nil {
return fmt.Errorf("read soft link %q error", path)
}
if destOfContainer == destOfCurrentProcess {
return fmt.Errorf("sysctl %q is not allowed in the hosts network namespace", sysctlConfig)
}
return nil
}
| 1 | 16,552 | i dont think we need to explicitly single out `kernel.domainname` here since its not a TODO for OCI either right ? | opencontainers-runc | go |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.