prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>trusts.go<|end_file_name|><|fim▁begin|>package trust import ( "crypto/x509" "errors" "io/ioutil" "net/http" "net/url" "os" "path" "path/filepath" "sync" "time" "github.com/Sirupsen/logrus" "github.com/docker/libtrust/trustgraph" ) type TrustStore struct { path string caPool *x509.CertPool graph trustgraph.TrustGraph expiration time.Time fetcher *time.Timer fetchTime time.Duration<|fim▁hole|> baseEndpoints map[string]*url.URL sync.RWMutex } // defaultFetchtime represents the starting duration to wait between // fetching sections of the graph. Unsuccessful fetches should // increase time between fetching. const defaultFetchtime = 45 * time.Second var baseEndpoints = map[string]string{"official": "https://dvjy3tqbc323p.cloudfront.net/trust/official.json"} func NewTrustStore(path string) (*TrustStore, error) { abspath, err := filepath.Abs(path) if err != nil { return nil, err } // Create base graph url map endpoints := map[string]*url.URL{} for name, endpoint := range baseEndpoints { u, err := url.Parse(endpoint) if err != nil { return nil, err } endpoints[name] = u } // Load grant files t := &TrustStore{ path: abspath, caPool: nil, httpClient: &http.Client{}, fetchTime: time.Millisecond, baseEndpoints: endpoints, } if err := t.reload(); err != nil { return nil, err } return t, nil } func (t *TrustStore) reload() error { t.Lock() defer t.Unlock() matches, err := filepath.Glob(filepath.Join(t.path, "*.json")) if err != nil { return err } statements := make([]*trustgraph.Statement, len(matches)) for i, match := range matches { f, err := os.Open(match) if err != nil { return err } statements[i], err = trustgraph.LoadStatement(f, nil) if err != nil { f.Close() return err } f.Close() } if len(statements) == 0 { if t.autofetch { logrus.Debugf("No grants, fetching") t.fetcher = time.AfterFunc(t.fetchTime, t.fetch) } return nil } grants, expiration, err := trustgraph.CollapseStatements(statements, true) if err != nil { return err } t.expiration = expiration t.graph = trustgraph.NewMemoryGraph(grants) logrus.Debugf("Reloaded graph with %d grants expiring at %s", len(grants), expiration) if t.autofetch { nextFetch := expiration.Sub(time.Now()) if nextFetch < 0 { nextFetch = defaultFetchtime } else { nextFetch = time.Duration(0.8 * (float64)(nextFetch)) } t.fetcher = time.AfterFunc(nextFetch, t.fetch) } return nil } func (t *TrustStore) fetchBaseGraph(u *url.URL) (*trustgraph.Statement, error) { req := &http.Request{ Method: "GET", URL: u, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: make(http.Header), Body: nil, Host: u.Host, } resp, err := t.httpClient.Do(req) if err != nil { return nil, err } if resp.StatusCode == 404 { return nil, errors.New("base graph does not exist") } defer resp.Body.Close() return trustgraph.LoadStatement(resp.Body, t.caPool) } // fetch retrieves updated base graphs. This function cannot error, it // should only log errors func (t *TrustStore) fetch() { t.Lock() defer t.Unlock() if t.autofetch && t.fetcher == nil { // Do nothing ?? return } fetchCount := 0 for bg, ep := range t.baseEndpoints { statement, err := t.fetchBaseGraph(ep) if err != nil { logrus.Infof("Trust graph fetch failed: %s", err) continue } b, err := statement.Bytes() if err != nil { logrus.Infof("Bad trust graph statement: %s", err) continue } // TODO check if value differs if err := ioutil.WriteFile(path.Join(t.path, bg+".json"), b, 0600); err != nil { logrus.Infof("Error writing trust graph statement: %s", err) } fetchCount++ } logrus.Debugf("Fetched %d base graphs at %s", fetchCount, time.Now()) if fetchCount > 0 { go func() { if err := t.reload(); err != nil { logrus.Infof("Reload of trust graph failed: %s", err) } }() t.fetchTime = defaultFetchtime t.fetcher = nil } else if t.autofetch { maxTime := 10 * defaultFetchtime t.fetchTime = time.Duration(1.5 * (float64)(t.fetchTime+time.Second)) if t.fetchTime > maxTime { t.fetchTime = maxTime } t.fetcher = time.AfterFunc(t.fetchTime, t.fetch) } }<|fim▁end|>
autofetch bool httpClient *http.Client
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2015 The TensorFlow Authors. All Rights Reserved. #<|fim▁hole|># 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. # ============================================================================== """contrib module containing volatile or experimental code.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Add projects here, they will show up under tf.contrib. from tensorflow.contrib import bayesflow from tensorflow.contrib import cloud from tensorflow.contrib import compiler from tensorflow.contrib import copy_graph from tensorflow.contrib import crf from tensorflow.contrib import cudnn_rnn from tensorflow.contrib import data from tensorflow.contrib import deprecated from tensorflow.contrib import distributions from tensorflow.contrib import factorization from tensorflow.contrib import framework from tensorflow.contrib import graph_editor from tensorflow.contrib import grid_rnn from tensorflow.contrib import image from tensorflow.contrib import input_pipeline from tensorflow.contrib import integrate from tensorflow.contrib import keras from tensorflow.contrib import kernel_methods from tensorflow.contrib import labeled_tensor from tensorflow.contrib import layers from tensorflow.contrib import learn from tensorflow.contrib import legacy_seq2seq from tensorflow.contrib import linalg from tensorflow.contrib import linear_optimizer from tensorflow.contrib import lookup from tensorflow.contrib import losses from tensorflow.contrib import memory_stats from tensorflow.contrib import metrics from tensorflow.contrib import nccl from tensorflow.contrib import nn from tensorflow.contrib import opt from tensorflow.contrib import quantization from tensorflow.contrib import rnn from tensorflow.contrib import saved_model from tensorflow.contrib import seq2seq from tensorflow.contrib import signal from tensorflow.contrib import slim from tensorflow.contrib import solvers from tensorflow.contrib import sparsemax from tensorflow.contrib import staging from tensorflow.contrib import stat_summarizer from tensorflow.contrib import stateless from tensorflow.contrib import tensor_forest from tensorflow.contrib import tensorboard from tensorflow.contrib import testing from tensorflow.contrib import tfprof from tensorflow.contrib import training from tensorflow.contrib import util from tensorflow.contrib.ndlstm import python as ndlstm from tensorflow.contrib.specs import python as specs from tensorflow.python.util.lazy_loader import LazyLoader ffmpeg = LazyLoader("ffmpeg", globals(), "tensorflow.contrib.ffmpeg") del LazyLoader del absolute_import del division del print_function<|fim▁end|>
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.
<|file_name|>AbinsCalculateDWSingleCrystalTest.py<|end_file_name|><|fim▁begin|>from __future__ import (absolute_import, division, print_function) import unittest from mantid.simpleapi import * import numpy as np import json from AbinsModules import CalculateDWSingleCrystal, LoadCASTEP, AbinsTestHelpers class AbinsCalculateDWSingleCrystalTest(unittest.TestCase): temperature = 10 # 10 K # data # Use case: one k-point _c6h6 = "benzene_CalculateDWSingleCrystal" # Use case: many k-points _si2 = "Si2-sc_CalculateDWSingleCrystal" def tearDown(self): AbinsTestHelpers.remove_output_files(list_of_names=["CalculateDWSingleCrystal"]) # simple tests def test_wrong_input(self): filename = self._si2 + ".phonon" castep_reader = LoadCASTEP(input_dft_filename=AbinsTestHelpers.find_file(filename=filename)) good_data = castep_reader.read_phonon_file() # wrong temperature self.assertRaises(ValueError, CalculateDWSingleCrystal, temperature=-10, abins_data=good_data) # data from object of type AtomsData instead of object of type AbinsData bad_data = good_data.extract()["atoms_data"] self.assertRaises(ValueError, CalculateDWSingleCrystal, temperature=self.temperature, abins_data=bad_data) <|fim▁hole|> self._good_case(name=self._si2) # helper functions def _good_case(self, name=None): # calculation of DW good_data = self._get_good_data(filename=name) good_tester = CalculateDWSingleCrystal(temperature=self.temperature, abins_data=good_data["DFT"]) calculated_data = good_tester.calculate_data() # check if evaluated DW are correct self.assertEqual(True, np.allclose(good_data["DW"], calculated_data.extract())) def _get_good_data(self, filename=None): castep_reader = LoadCASTEP(input_dft_filename=AbinsTestHelpers.find_file(filename=filename + ".phonon")) dw = self._prepare_data(filename=AbinsTestHelpers.find_file(filename=filename + "_crystal_DW.txt")) return {"DFT": castep_reader.read_phonon_file(), "DW": dw} # noinspection PyMethodMayBeStatic def _prepare_data(self, filename=None): """Reads a correct values from ASCII file.""" with open(filename) as data_file: correct_data = json.loads(data_file.read().replace("\n", " ")) return np.asarray(correct_data) if __name__ == '__main__': unittest.main()<|fim▁end|>
# main test def test_good_case(self): self._good_case(name=self._c6h6)
<|file_name|>rollup.config.js<|end_file_name|><|fim▁begin|>import uglify from 'rollup-plugin-uglify' import buble from 'rollup-plugin-buble' export default {<|fim▁hole|>}<|fim▁end|>
entry: 'js/index.js', dest: 'public/bundle.js', format: 'iife', plugins: [buble(), uglify()],
<|file_name|>test_PositionIncrement.py<|end_file_name|><|fim▁begin|># ==================================================================== # 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 sys, lucene, unittest from lucene import JArray from PyLuceneTestCase import PyLuceneTestCase from MultiSpansWrapper import MultiSpansWrapper from java.io import StringReader from org.apache.lucene.analysis import Analyzer from org.apache.lucene.analysis.core import \ LowerCaseTokenizer, WhitespaceTokenizer from org.apache.lucene.analysis.tokenattributes import \ CharTermAttribute, OffsetAttribute, PayloadAttribute, \ PositionIncrementAttribute from org.apache.lucene.document import Document, Field, TextField from org.apache.lucene.index import MultiFields, Term from org.apache.lucene.queryparser.classic import QueryParser from org.apache.lucene.search import MultiPhraseQuery, PhraseQuery from org.apache.lucene.search.payloads import PayloadSpanUtil from org.apache.lucene.search.spans import SpanNearQuery, SpanTermQuery from org.apache.lucene.util import BytesRef, Version from org.apache.pylucene.analysis import \ PythonAnalyzer, PythonFilteringTokenFilter, PythonTokenFilter, \ PythonTokenizer class PositionIncrementTestCase(PyLuceneTestCase): """ Unit tests ported from Java Lucene """ def testSetPosition(self): class _tokenizer(PythonTokenizer): def __init__(_self, reader): super(_tokenizer, _self).__init__(reader) _self.TOKENS = ["1", "2", "3", "4", "5"] _self.INCREMENTS = [1, 2, 1, 0, 1] _self.i = 0 _self.posIncrAtt = _self.addAttribute(PositionIncrementAttribute.class_) _self.termAtt = _self.addAttribute(CharTermAttribute.class_) _self.offsetAtt = _self.addAttribute(OffsetAttribute.class_) def incrementToken(_self): if _self.i == len(_self.TOKENS): return False _self.clearAttributes() _self.termAtt.append(_self.TOKENS[_self.i]) _self.offsetAtt.setOffset(_self.i, _self.i) _self.posIncrAtt.setPositionIncrement(_self.INCREMENTS[_self.i]) _self.i += 1 return True def end(_self): pass def reset(_self): pass def close(_self): pass class _analyzer(PythonAnalyzer): def createComponents(_self, fieldName, reader): return Analyzer.TokenStreamComponents(_tokenizer(reader)) writer = self.getWriter(analyzer=_analyzer()) d = Document() d.add(Field("field", "bogus", TextField.TYPE_STORED)) writer.addDocument(d) writer.commit() writer.close() searcher = self.getSearcher() reader = searcher.getIndexReader() pos = MultiFields.getTermPositionsEnum(reader, MultiFields.getLiveDocs(reader), "field", BytesRef("1")) pos.nextDoc() # first token should be at position 0 self.assertEqual(0, pos.nextPosition()) <|fim▁hole|> q = PhraseQuery() q.add(Term("field", "1")) q.add(Term("field", "2")) hits = searcher.search(q, None, 1000).scoreDocs self.assertEqual(0, len(hits)) # same as previous, just specify positions explicitely. q = PhraseQuery() q.add(Term("field", "1"), 0) q.add(Term("field", "2"), 1) hits = searcher.search(q, None, 1000).scoreDocs self.assertEqual(0, len(hits)) # specifying correct positions should find the phrase. q = PhraseQuery() q.add(Term("field", "1"), 0) q.add(Term("field", "2"), 2) hits = searcher.search(q, None, 1000).scoreDocs self.assertEqual(1, len(hits)) q = PhraseQuery() q.add(Term("field", "2")) q.add(Term("field", "3")) hits = searcher.search(q, None, 1000).scoreDocs self.assertEqual(1, len(hits)) q = PhraseQuery() q.add(Term("field", "3")) q.add(Term("field", "4")) hits = searcher.search(q, None, 1000).scoreDocs self.assertEqual(0, len(hits)) # phrase query would find it when correct positions are specified. q = PhraseQuery() q.add(Term("field", "3"), 0) q.add(Term("field", "4"), 0) hits = searcher.search(q, None, 1000).scoreDocs self.assertEqual(1, len(hits)) # phrase query should fail for non existing searched term # even if there exist another searched terms in the same searched # position. q = PhraseQuery() q.add(Term("field", "3"), 0) q.add(Term("field", "9"), 0) hits = searcher.search(q, None, 1000).scoreDocs self.assertEqual(0, len(hits)) # multi-phrase query should succed for non existing searched term # because there exist another searched terms in the same searched # position. mq = MultiPhraseQuery() mq.add([Term("field", "3"), Term("field", "9")], 0) hits = searcher.search(mq, None, 1000).scoreDocs self.assertEqual(1, len(hits)) q = PhraseQuery() q.add(Term("field", "2")) q.add(Term("field", "4")) hits = searcher.search(q, None, 1000).scoreDocs self.assertEqual(1, len(hits)) q = PhraseQuery() q.add(Term("field", "3")) q.add(Term("field", "5")) hits = searcher.search(q, None, 1000).scoreDocs self.assertEqual(1, len(hits)) q = PhraseQuery() q.add(Term("field", "4")) q.add(Term("field", "5")) hits = searcher.search(q, None, 1000).scoreDocs self.assertEqual(1, len(hits)) q = PhraseQuery() q.add(Term("field", "2")) q.add(Term("field", "5")) hits = searcher.search(q, None, 1000).scoreDocs self.assertEqual(0, len(hits)) def testPayloadsPos0(self): writer = self.getWriter(analyzer=TestPayloadAnalyzer()) doc = Document() doc.add(Field("content", "a a b c d e a f g h i j a b k k", TextField.TYPE_STORED)) writer.addDocument(doc) reader = writer.getReader() writer.close() tp = MultiFields.getTermPositionsEnum(reader, MultiFields.getLiveDocs(reader), "content", BytesRef("a")) count = 0 self.assert_(tp.nextDoc() != tp.NO_MORE_DOCS) # "a" occurs 4 times self.assertEqual(4, tp.freq()) expected = 0 self.assertEqual(expected, tp.nextPosition()) self.assertEqual(1, tp.nextPosition()) self.assertEqual(3, tp.nextPosition()) self.assertEqual(6, tp.nextPosition()) # only one doc has "a" self.assert_(tp.nextDoc() == tp.NO_MORE_DOCS) searcher = self.getSearcher(reader=reader) stq1 = SpanTermQuery(Term("content", "a")) stq2 = SpanTermQuery(Term("content", "k")) sqs = [stq1, stq2] snq = SpanNearQuery(sqs, 30, False) count = 0 sawZero = False pspans = MultiSpansWrapper.wrap(searcher.getTopReaderContext(), snq) while pspans.next(): payloads = pspans.getPayload() sawZero |= pspans.start() == 0 it = payloads.iterator() while it.hasNext(): count += 1 it.next() self.assertEqual(5, count) self.assert_(sawZero) spans = MultiSpansWrapper.wrap(searcher.getTopReaderContext(), snq) count = 0 sawZero = False while spans.next(): count += 1 sawZero |= spans.start() == 0 self.assertEqual(4, count) self.assert_(sawZero) sawZero = False psu = PayloadSpanUtil(searcher.getTopReaderContext()) pls = psu.getPayloadsForQuery(snq) count = pls.size() it = pls.iterator() while it.hasNext(): bytes = JArray('byte').cast_(it.next()) s = bytes.string_ sawZero |= s == "pos: 0" self.assertEqual(5, count) self.assert_(sawZero) class StopWhitespaceAnalyzer(PythonAnalyzer): def __init__(self, enablePositionIncrements): super(StopWhitespaceAnalyzer, self).__init__() self.enablePositionIncrements = enablePositionIncrements def createComponents(self, fieldName, reader): class _stopFilter(PythonFilteringTokenFilter): def __init__(_self, tokenStream): super(_stopFilter, _self).__init__(Version.LUCENE_CURRENT, tokenStream) _self.termAtt = _self.addAttribute(CharTermAttribute.class_); def accept(_self): return _self.termAtt.toString() != "stop" source = WhitespaceTokenizer(Version.LUCENE_CURRENT, reader) return Analyzer.TokenStreamComponents(source, _stopFilter(source)) class TestPayloadAnalyzer(PythonAnalyzer): def createComponents(self, fieldName, reader): source = LowerCaseTokenizer(Version.LUCENE_CURRENT, reader) return Analyzer.TokenStreamComponents(source, PayloadFilter(source, fieldName)) class PayloadFilter(PythonTokenFilter): def __init__(self, input, fieldName): super(PayloadFilter, self).__init__(input) self.input = input self.fieldName = fieldName self.pos = 0 self.i = 0 self.posIncrAttr = input.addAttribute(PositionIncrementAttribute.class_) self.payloadAttr = input.addAttribute(PayloadAttribute.class_) self.termAttr = input.addAttribute(CharTermAttribute.class_) def incrementToken(self): if self.input.incrementToken(): bytes = JArray('byte')("pos: %d" %(self.pos)) self.payloadAttr.setPayload(BytesRef(bytes)) if self.pos == 0 or self.i % 2 == 1: posIncr = 1 else: posIncr = 0 self.posIncrAttr.setPositionIncrement(posIncr) self.pos += posIncr self.i += 1 return True return False if __name__ == "__main__": lucene.initVM(vmargs=['-Djava.awt.headless=true']) if '-loop' in sys.argv: sys.argv.remove('-loop') while True: try: unittest.main() except: pass else: unittest.main()<|fim▁end|>
pos = MultiFields.getTermPositionsEnum(reader, MultiFields.getLiveDocs(reader), "field", BytesRef("2")) pos.nextDoc() # second token should be at position 2 self.assertEqual(2, pos.nextPosition())
<|file_name|>ek_silverlight.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- try: import re2 as re except ImportError: import re from lib.cuckoo.common.abstracts import Signature class Silverlight_JS(Signature): name = "silverlight_js" description = "执行伪装过的包含一个Silverlight对象的JavaScript,可能被用于漏洞攻击尝试" weight = 3 severity = 3 categories = ["exploit_kit", "silverlight"] authors = ["Kevin Ross"] minimum = "1.3" evented = True def __init__(self, *args, **kwargs):<|fim▁hole|> filter_categories = set(["browser"]) # backward compat filter_apinames = set(["JsEval", "COleScript_Compile", "COleScript_ParseScriptText"]) def on_call(self, call, process): if call["api"] == "JsEval": buf = self.get_argument(call, "Javascript") else: buf = self.get_argument(call, "Script") if re.search("application\/x\-silverlight.*?\<param name[ \t\n]*=.*?value[ \t\n]*=.*?\<\/object\>.*", buf, re.IGNORECASE|re.DOTALL): return True<|fim▁end|>
Signature.__init__(self, *args, **kwargs)
<|file_name|>mixins.py<|end_file_name|><|fim▁begin|>#!/bin/env python2 # -*- coding: utf-8 -*- # # This file is part of the VecNet Zika modeling interface. # For copyright and licensing information about this package, see the # NOTICE.txt and LICENSE.txt files in its top-level directory; they are # available at https://github.com/vecnet/zika #<|fim▁hole|> import json from django.contrib.auth.decorators import login_required from django.http import HttpResponse class LoginRequiredMixin(object): """ This works: class InterviewListView(LoginRequiredMixin, ListView) This DOES NOT work: class InterviewListView(ListView, LoginRequiredMixin) I'm not 100% sure that wrapping as_view function using Mixin is a good idea though, but whatever """ @classmethod def as_view(cls, **initkwargs): # Ignore PyCharm warning below, this is a Mixin class after all view = super(LoginRequiredMixin, cls).as_view(**initkwargs) return login_required(view)<|fim▁end|>
# This Source Code Form is subject to the terms of the Mozilla Public # License (MPL), version 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/.
<|file_name|>subauth.rs<|end_file_name|><|fim▁begin|>// Copyright © 2015, skdltmxn // Licensed under the MIT License <LICENSE.md> //! Types and macros for Subauthentication Packages. STRUCT!{struct UNICODE_STRING { Length: ::USHORT, MaximumLength: ::USHORT, Buffer: ::PWSTR, }} pub type PUNICODE_STRING = *mut UNICODE_STRING; STRUCT!{struct STRING { Length: ::USHORT, MaximumLength: ::USHORT, Buffer: ::PCHAR, }} pub type PSTRING = *mut STRING; STRUCT!{struct OLD_LARGE_INTEGER { LowPart: ::ULONG, HighPart: ::LONG, }} pub type POLD_LARGE_INTEGER = *mut OLD_LARGE_INTEGER; pub type SAM_HANDLE = ::PVOID; pub type PSAM_HANDLE = *mut ::PVOID; pub const USER_ACCOUNT_DISABLED: ::ULONG = 0x00000001; pub const USER_HOME_DIRECTORY_REQUIRED: ::ULONG = 0x00000002; pub const USER_PASSWORD_NOT_REQUIRED: ::ULONG = 0x00000004; pub const USER_TEMP_DUPLICATE_ACCOUNT: ::ULONG = 0x00000008; pub const USER_NORMAL_ACCOUNT: ::ULONG = 0x00000010; pub const USER_MNS_LOGON_ACCOUNT: ::ULONG = 0x00000020; pub const USER_INTERDOMAIN_TRUST_ACCOUNT: ::ULONG = 0x00000040; pub const USER_WORKSTATION_TRUST_ACCOUNT: ::ULONG = 0x00000080; pub const USER_SERVER_TRUST_ACCOUNT: ::ULONG = 0x00000100; pub const USER_DONT_EXPIRE_PASSWORD: ::ULONG = 0x00000200; pub const USER_ACCOUNT_AUTO_LOCKED: ::ULONG = 0x00000400; pub const USER_ENCRYPTED_TEXT_PASSWORD_ALLOWED: ::ULONG = 0x00000800; pub const USER_SMARTCARD_REQUIRED: ::ULONG = 0x00001000; pub const USER_TRUSTED_FOR_DELEGATION: ::ULONG = 0x00002000; pub const USER_NOT_DELEGATED: ::ULONG = 0x00004000; pub const USER_USE_DES_KEY_ONLY: ::ULONG = 0x00008000; pub const USER_DONT_REQUIRE_PREAUTH: ::ULONG = 0x00010000; pub const USER_PASSWORD_EXPIRED: ::ULONG = 0x00020000; pub const USER_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: ::ULONG = 0x00040000; pub const USER_NO_AUTH_DATA_REQUIRED: ::ULONG = 0x00080000; pub const USER_PARTIAL_SECRETS_ACCOUNT: ::ULONG = 0x00100000; pub const USER_USE_AES_KEYS: ::ULONG = 0x00200000; pub const NEXT_FREE_ACCOUNT_CONTROL_BIT: ::ULONG = USER_USE_AES_KEYS << 1; pub const USER_MACHINE_ACCOUNT_MASK: ::ULONG = USER_INTERDOMAIN_TRUST_ACCOUNT | USER_WORKSTATION_TRUST_ACCOUNT | USER_SERVER_TRUST_ACCOUNT; pub const USER_ACCOUNT_TYPE_MASK: ::ULONG = USER_TEMP_DUPLICATE_ACCOUNT | USER_NORMAL_ACCOUNT | USER_MACHINE_ACCOUNT_MASK; pub const USER_COMPUTED_ACCOUNT_CONTROL_BITS: ::ULONG = USER_ACCOUNT_AUTO_LOCKED | USER_PASSWORD_EXPIRED; pub const SAM_DAYS_PER_WEEK: ::USHORT = 7; pub const SAM_HOURS_PER_WEEK: ::USHORT = 24 * SAM_DAYS_PER_WEEK; pub const SAM_MINUTES_PER_WEEK: ::USHORT = 60 * SAM_HOURS_PER_WEEK; STRUCT!{struct LOGON_HOURS { UnitsPerWeek: ::USHORT, LogonHours: ::PUCHAR, }} pub type PLOGON_HOURS = *mut LOGON_HOURS; STRUCT!{struct SR_SECURITY_DESCRIPTOR { Length: ::ULONG, SecurityDescriptor: ::PUCHAR, }} pub type PSR_SECURITY_DESCRIPTOR = *mut SR_SECURITY_DESCRIPTOR; STRUCT!{struct USER_ALL_INFORMATION { LastLogon: ::LARGE_INTEGER, LastLogoff: ::LARGE_INTEGER, PasswordLastSet: ::LARGE_INTEGER, AccountExpires: ::LARGE_INTEGER, PasswordCanChange: ::LARGE_INTEGER, PasswordMustChange: ::LARGE_INTEGER, UserName: UNICODE_STRING, FullName: UNICODE_STRING, HomeDirectory: UNICODE_STRING, HomeDirectoryDrive: UNICODE_STRING, ScriptPath: UNICODE_STRING, ProfilePath: UNICODE_STRING, AdminComment: UNICODE_STRING, WorkStations: UNICODE_STRING, UserComment: UNICODE_STRING, Parameters: UNICODE_STRING, LmPassword: UNICODE_STRING, NtPassword: UNICODE_STRING, PrivateData: UNICODE_STRING, SecurityDescriptor: SR_SECURITY_DESCRIPTOR, UserId: ::ULONG, PrimaryGroupId: ::ULONG, UserAccountControl: ::ULONG, WhichFields: ::ULONG, LogonHours: LOGON_HOURS, BadPasswordCount: ::USHORT, LogonCount: ::USHORT, CountryCode: ::USHORT, CodePage: ::USHORT, LmPasswordPresent: ::BOOLEAN, NtPasswordPresent: ::BOOLEAN, PasswordExpired: ::BOOLEAN, PrivateDataSensitive: ::BOOLEAN, }} pub type PUSER_ALL_INFORMATION = *mut USER_ALL_INFORMATION; pub const USER_ALL_PARAMETERS: ::ULONG = 0x00200000; pub const CLEAR_BLOCK_LENGTH: usize = 8; STRUCT!{struct CLEAR_BLOCK { data: [::CHAR; CLEAR_BLOCK_LENGTH], }} pub type PCLEAR_BLOCK = *mut CLEAR_BLOCK; pub const CYPHER_BLOCK_LENGTH: usize = 8; STRUCT!{struct CYPHER_BLOCK { data: [::CHAR; CYPHER_BLOCK_LENGTH], }} pub type PCYPHER_BLOCK = *mut CYPHER_BLOCK; STRUCT!{struct LM_OWF_PASSWORD { data: [CYPHER_BLOCK; 2], }} pub type PLM_OWF_PASSWORD = *mut LM_OWF_PASSWORD; pub type LM_CHALLENGE = CLEAR_BLOCK; pub type PLM_CHALLENGE = *mut LM_CHALLENGE; pub type NT_OWF_PASSWORD = LM_OWF_PASSWORD; pub type PNT_OWF_PASSWORD = *mut NT_OWF_PASSWORD; pub type NT_CHALLENGE = LM_CHALLENGE; pub type PNT_CHALLENGE = *mut NT_CHALLENGE; pub const USER_SESSION_KEY_LENGTH: usize = CYPHER_BLOCK_LENGTH * 2; STRUCT!{struct USER_SESSION_KEY { data: [CYPHER_BLOCK; 2], }} pub type PUSER_SESSION_KEY = *mut USER_SESSION_KEY; ENUM!{enum NETLOGON_LOGON_INFO_CLASS { NetlogonInteractiveInformation = 1, NetlogonNetworkInformation, NetlogonServiceInformation, NetlogonGenericInformation, NetlogonInteractiveTransitiveInformation, NetlogonNetworkTransitiveInformation, NetlogonServiceTransitiveInformation, }} STRUCT!{struct NETLOGON_LOGON_IDENTITY_INFO { LogonDomainName: UNICODE_STRING, ParameterControl: ::ULONG, LogonId: OLD_LARGE_INTEGER, UserName: UNICODE_STRING, Workstation: UNICODE_STRING, }} pub type PNETLOGON_LOGON_IDENTITY_INFO = *mut NETLOGON_LOGON_IDENTITY_INFO; STRUCT!{struct NETLOGON_INTERACTIVE_INFO { Identity: NETLOGON_LOGON_IDENTITY_INFO, LmOwfPassword: LM_OWF_PASSWORD, NtOwfPassword: NT_OWF_PASSWORD, }} pub type PNETLOGON_INTERACTIVE_INFO = *mut NETLOGON_INTERACTIVE_INFO; STRUCT!{struct NETLOGON_SERVICE_INFO { Identity: NETLOGON_LOGON_IDENTITY_INFO, LmOwfPassword: LM_OWF_PASSWORD, NtOwfPassword: NT_OWF_PASSWORD, }} pub type PNETLOGON_SERVICE_INFO = *mut NETLOGON_SERVICE_INFO; STRUCT!{struct NETLOGON_NETWORK_INFO { Identity: NETLOGON_LOGON_IDENTITY_INFO, LmChallenge: LM_CHALLENGE, NtChallengeResponse: STRING,<|fim▁hole|>}} pub type PNETLOGON_NETWORK_INFO = *mut NETLOGON_NETWORK_INFO; STRUCT!{struct NETLOGON_GENERIC_INFO { Identity: NETLOGON_LOGON_IDENTITY_INFO, PackageName: UNICODE_STRING, DataLength: ::ULONG, LogonData: ::PUCHAR, }} pub type PNETLOGON_GENERIC_INFO = *mut NETLOGON_GENERIC_INFO; pub const MSV1_0_PASSTHRU: ::ULONG = 0x01; pub const MSV1_0_GUEST_LOGON: ::ULONG = 0x02; STRUCT!{struct MSV1_0_VALIDATION_INFO { LogoffTime: ::LARGE_INTEGER, KickoffTime: ::LARGE_INTEGER, LogonServer: UNICODE_STRING, LogonDomainName: UNICODE_STRING, SessionKey: USER_SESSION_KEY, Authoritative: ::BOOLEAN, UserFlags: ::ULONG, WhichFields: ::ULONG, UserId: ::ULONG, }} pub type PMSV1_0_VALIDATION_INFO = *mut MSV1_0_VALIDATION_INFO; pub const MSV1_0_VALIDATION_LOGOFF_TIME: ::ULONG = 0x00000001; pub const MSV1_0_VALIDATION_KICKOFF_TIME: ::ULONG = 0x00000002; pub const MSV1_0_VALIDATION_LOGON_SERVER: ::ULONG = 0x00000004; pub const MSV1_0_VALIDATION_LOGON_DOMAIN: ::ULONG = 0x00000008; pub const MSV1_0_VALIDATION_SESSION_KEY: ::ULONG = 0x00000010; pub const MSV1_0_VALIDATION_USER_FLAGS: ::ULONG = 0x00000020; pub const MSV1_0_VALIDATION_USER_ID: ::ULONG = 0x00000040; pub const MSV1_0_SUBAUTH_ACCOUNT_DISABLED: ::ULONG = 0x00000001; pub const MSV1_0_SUBAUTH_PASSWORD: ::ULONG = 0x00000002; pub const MSV1_0_SUBAUTH_WORKSTATIONS: ::ULONG = 0x00000004; pub const MSV1_0_SUBAUTH_LOGON_HOURS: ::ULONG = 0x00000008; pub const MSV1_0_SUBAUTH_ACCOUNT_EXPIRY: ::ULONG = 0x00000010; pub const MSV1_0_SUBAUTH_PASSWORD_EXPIRY: ::ULONG = 0x00000020; pub const MSV1_0_SUBAUTH_ACCOUNT_TYPE: ::ULONG = 0x00000040; pub const MSV1_0_SUBAUTH_LOCKOUT: ::ULONG = 0x00000080;<|fim▁end|>
LmChallengeResponse: STRING,
<|file_name|>extern-prelude-extern-crate-proc-macro.rs<|end_file_name|><|fim▁begin|>// compile-pass // edition:2018 extern crate proc_macro;<|fim▁hole|>use proc_macro::TokenStream; // OK fn main() {}<|fim▁end|>
<|file_name|>run.py<|end_file_name|><|fim▁begin|>from flask import Flask, request, redirect, session import twilio.twiml import navigation SECRET_KEY = 'donuts' logging = True app = Flask(__name__) app.config.from_object(__name__) def log(mesagge=""): if logging: print mesagge @app.route("/", methods=['GET', 'POST']) def main_reply(): # Log values from request from_number = request.values.get('From', None) log(from_number) recieved_message = request.values.get('Body')<|fim▁hole|> log(recieved_message) # pick reply to message reply = navigation.choose_script(bodyText=recieved_message) # trim the length of the reply to one text if len(reply) > 160: reply = reply[0:159] if reply == "": reply = "Error." # get the response scheme from twilio and add reply as message body resp = twilio.twiml.Response() resp.message(reply.encode("utf-8")) # log server reply log(reply) # store previous queries of the user in a cookie searchs = session.get('searchs', []) searchs.append(recieved_message) replies = session.get('searchs', []) replies.append(reply) # Save the new cmds/searchs list in the session session['searchs'] = searchs return str(resp) if __name__ == "__main__": app.run(debug=True)<|fim▁end|>
<|file_name|>AsakoTsuki.js<|end_file_name|><|fim▁begin|>const DrawCard = require('../../drawcard.js'); const { CardTypes } = require('../../Constants'); class AsakoTsuki extends DrawCard { setupCardAbilities(ability) {<|fim▁hole|> when: { onClaimRing: event => event.conflict && event.conflict.hasElement('water') }, target: { cardType: CardTypes.Character, cardCondition: card => card.hasTrait('scholar'), gameAction: ability.actions.honor() } }); } } AsakoTsuki.id = 'asako-tsuki'; module.exports = AsakoTsuki;<|fim▁end|>
this.reaction({ title: 'Honor a scholar character',
<|file_name|>server.js<|end_file_name|><|fim▁begin|>var express = require('express'); var app = express(); var request = require("request"); var bodyParser = require('body-parser'); app.use(express.static(__dirname+"/public")); app.use(express.static(__dirname+"/bower_components")); app.use(bodyParser.json()); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*");<|fim▁hole|> res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.get('/getNames', function(req, res) { request({ url: 'http://localhost:8080/names.min.json', json: true }, function (error, response, body) { if (!error && response.statusCode === 200) res.send(body); }); }); app.use(function(req, res) { // Use res.sendfile, as it streams instead of reading the file into memory. res.sendFile(__dirname + '/public/index.html'); }); app.listen(666); console.log(__dirname); console.log('running server at 666');<|fim▁end|>
<|file_name|>user.js<|end_file_name|><|fim▁begin|>import * as types from 'constants/ActionTypes' import jsCookie from 'js-cookie' import history from 'history' export const setUser = (user) => (dispatch) => { dispatch({ type: types.SET_USER,<|fim▁hole|> payload: { ...user } }) }<|fim▁end|>
<|file_name|>app.component.ts<|end_file_name|><|fim▁begin|>import {Component, OnInit} from '@angular/core'; import {AuthService} from "./auth/auth.service"; @Component({ moduleId: module.id, selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css']<|fim▁hole|>export class AppComponent implements OnInit{ public isLoggedIn : boolean; public email : string = ''; constructor(private authService: AuthService) { } ngOnInit() { this.authService.isLoggedInEmitter.subscribe( (show: boolean) => this.isLoggedIn = show ); if (localStorage.getItem('auth_token')) { this.isLoggedIn = true; var token = localStorage.getItem('auth_token') var base64Url = token.split('.')[1]; var base64 = base64Url.replace('-', '+').replace('_', '/'); var email = JSON.parse(window.atob(base64)); this.email = email["email"]; } if (!this.isLoggedIn) { this.authService.logout(); } } }<|fim▁end|>
})
<|file_name|>listdir.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 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. //! Helpers for reading directory structures from the local filesystem. use std::fs; use std::path::PathBuf; use std::sync::mpsc; use threadpool; pub trait PathHandler<D> { fn handle_path(&self, D, PathBuf) -> Option<D>; } pub fn iterate_recursively<P: 'static + Send + Clone, W: 'static + PathHandler<P> + Send + Clone> (root: (PathBuf, P), worker: &mut W) { let threads = 10; let (push_ch, work_ch) = mpsc::sync_channel(threads); let pool = threadpool::ThreadPool::new(threads); // Insert the first task into the queue: push_ch.send(Some(root)).unwrap(); let mut running_workers = 0 as i32; // Master thread: loop { match work_ch.recv() { Err(_) => unreachable!(), Ok(None) => { // A worker has completed a task. // We are done when no more workers are active (i.e. all tasks are done): running_workers -= 1; if running_workers == 0 { break } }, Ok(Some((root, payload))) => { // Execute the task in a pool thread: running_workers += 1; let _worker = worker.clone(); let _push_ch = push_ch.clone(); pool.execute(move|| { let res = fs::read_dir(&root); if res.is_ok() { for entry in res.unwrap() { if entry.is_ok() { let entry = entry.unwrap(); let file = entry.path(); let path = PathBuf::from(file.to_str().unwrap()); let dir_opt = _worker.handle_path(payload.clone(), path); if dir_opt.is_some() { _push_ch.send(Some((file.clone(), dir_opt.unwrap()))).unwrap(); } } } } // Count this pool thread as idle: _push_ch.send(None).unwrap(); }); } } } } struct PrintPathHandler; impl Clone for PrintPathHandler { fn clone(&self) -> PrintPathHandler { PrintPathHandler } }<|fim▁hole|> impl PathHandler<()> for PrintPathHandler { fn handle_path(&self, _: (), path: PathBuf) -> Option<()> { println!("{}", path.display()); match fs::metadata(&path) { Ok(ref m) if m.is_dir() => Some(()), _ => None, } } }<|fim▁end|>
<|file_name|>Sparkline.js<|end_file_name|><|fim▁begin|>dojo.provide("dojox.charting.widget.Sparkline"); dojo.require("dojox.charting.widget.Chart2D"); dojo.require("dojox.charting.themes.ET.greys"); (function(){ var d = dojo; dojo.declare("dojox.charting.widget.Sparkline", dojox.charting.widget.Chart2D, { theme: dojox.charting.themes.ET.greys, margins: { l: 0, r: 0, t: 0, b: 0 }, type: "Lines", valueFn: "Number(x)", store: "", field: "", query: "", queryOptions: "", start: "0", count: "Infinity", sort: "", data: "", name: "default", buildRendering: function(){ var n = this.srcNodeRef; if( !n.childNodes.length || // shortcut the query !d.query("> .axis, > .plot, > .action, > .series", n).length){ var plot = document.createElement("div"); d.attr(plot, { "class": "plot", "name": "default", "type": this.type }); n.appendChild(plot); var series = document.createElement("div"); d.attr(series, { "class": "series", plot: "default", name: this.name, start: this.start, count: this.count, valueFn: this.valueFn }); d.forEach( ["store", "field", "query", "queryOptions", "sort", "data"], function(i){ if(this[i].length){ <|fim▁hole|> }, this ); n.appendChild(series); } this.inherited(arguments); } } ); })();<|fim▁end|>
d.attr(series, i, this[i]); }
<|file_name|>x11_window.cpp<|end_file_name|><|fim▁begin|>#include "nova_renderer/util/platform.hpp" #ifdef NOVA_LINUX #include "x11_window.hpp" namespace nova::renderer { x11_window::x11_window(uint32_t width, uint32_t height, const std::string& title) { display = XOpenDisplay(nullptr); if(display == nullptr) { throw window_creation_error("Failed to open XDisplay"); } // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) int screen = DefaultScreen(display); window = XCreateSimpleWindow(display, RootWindow(display, screen), // NOLINT(cppcoreguidelines-pro-type-cstyle-cast) 50, 50, width, height, 1, BlackPixel(display, screen), // NOLINT(cppcoreguidelines-pro-type-cstyle-cast) WhitePixel(display, screen)); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast) XStoreName(display, window, title.c_str()); wm_protocols = XInternAtom(display, "WM_PROTOCOLS", 0); wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", 0); XSetWMProtocols(display, window, &wm_delete_window, 1); XSelectInput(display, window, ExposureMask | ButtonPressMask | KeyPressMask); XMapWindow(display, window); } <|fim▁hole|> XCloseDisplay(display); } Window& x11_window::get_x11_window() { return window; } Display* x11_window::get_display() { return display; } void x11_window::on_frame_end() { XEvent event; while(XPending(display) != 0) { XNextEvent(display, &event); switch(event.type) { case ClientMessage: { if(event.xclient.message_type == wm_protocols && event.xclient.data.l[0] == static_cast<long>(wm_delete_window)) { should_window_close = true; } break; } default: break; } } } bool x11_window::should_close() const { return should_window_close; } glm::uvec2 x11_window::get_window_size() const { Window root_window; int x_pos; int y_pos; uint32_t width; uint32_t height; uint32_t border_width; uint32_t depth; XGetGeometry(display, window, &root_window, &x_pos, &y_pos, &width, &height, &border_width, &depth); return {width, height}; } } // namespace nova::renderer #endif<|fim▁end|>
x11_window::~x11_window() { XUnmapWindow(display, window); XDestroyWindow(display, window);
<|file_name|>ChangePasswordData.js<|end_file_name|><|fim▁begin|>"use strict"; tutao.provide('tutao.entity.sys.ChangePasswordData'); /** * @constructor * @param {Object=} data The json data to store in this entity. */ tutao.entity.sys.ChangePasswordData = function(data) { if (data) { this.updateData(data); } else { this.__format = "0"; this._code = null; this._pwEncUserGroupKey = null; this._salt = null; this._verifier = null; } this._entityHelper = new tutao.entity.EntityHelper(this); this.prototype = tutao.entity.sys.ChangePasswordData.prototype; }; /** * Updates the data of this entity. * @param {Object=} data The json data to store in this entity. */ tutao.entity.sys.ChangePasswordData.prototype.updateData = function(data) { this.__format = data._format; this._code = data.code; this._pwEncUserGroupKey = data.pwEncUserGroupKey; this._salt = data.salt; this._verifier = data.verifier; }; /** * The version of the model this type belongs to. * @const */ tutao.entity.sys.ChangePasswordData.MODEL_VERSION = '10'; /** * The url path to the resource. * @const */ tutao.entity.sys.ChangePasswordData.PATH = '/rest/sys/changepasswordservice'; /** * The encrypted flag. * @const */ tutao.entity.sys.ChangePasswordData.prototype.ENCRYPTED = false; /** * Provides the data of this instances as an object that can be converted to json. * @return {Object} The json object. */ tutao.entity.sys.ChangePasswordData.prototype.toJsonData = function() { return { _format: this.__format, code: this._code, pwEncUserGroupKey: this._pwEncUserGroupKey, salt: this._salt, verifier: this._verifier }; }; /** * The id of the ChangePasswordData type. */ tutao.entity.sys.ChangePasswordData.prototype.TYPE_ID = 534; /** * The id of the code attribute. */ tutao.entity.sys.ChangePasswordData.prototype.CODE_ATTRIBUTE_ID = 539; /** * The id of the pwEncUserGroupKey attribute. */ tutao.entity.sys.ChangePasswordData.prototype.PWENCUSERGROUPKEY_ATTRIBUTE_ID = 538; /** * The id of the salt attribute. */ tutao.entity.sys.ChangePasswordData.prototype.SALT_ATTRIBUTE_ID = 537; /** * The id of the verifier attribute. */ tutao.entity.sys.ChangePasswordData.prototype.VERIFIER_ATTRIBUTE_ID = 536; /** * Sets the format of this ChangePasswordData. * @param {string} format The format of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setFormat = function(format) { this.__format = format; return this; }; /** * Provides the format of this ChangePasswordData. * @return {string} The format of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getFormat = function() { return this.__format; }; /** * Sets the code of this ChangePasswordData. * @param {string} code The code of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setCode = function(code) { this._code = code; return this; }; /** * Provides the code of this ChangePasswordData. * @return {string} The code of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getCode = function() { return this._code; }; /** * Sets the pwEncUserGroupKey of this ChangePasswordData. * @param {string} pwEncUserGroupKey The pwEncUserGroupKey of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setPwEncUserGroupKey = function(pwEncUserGroupKey) { this._pwEncUserGroupKey = pwEncUserGroupKey; return this; }; /** * Provides the pwEncUserGroupKey of this ChangePasswordData.<|fim▁hole|> */ tutao.entity.sys.ChangePasswordData.prototype.getPwEncUserGroupKey = function() { return this._pwEncUserGroupKey; }; /** * Sets the salt of this ChangePasswordData. * @param {string} salt The salt of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setSalt = function(salt) { this._salt = salt; return this; }; /** * Provides the salt of this ChangePasswordData. * @return {string} The salt of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getSalt = function() { return this._salt; }; /** * Sets the verifier of this ChangePasswordData. * @param {string} verifier The verifier of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setVerifier = function(verifier) { this._verifier = verifier; return this; }; /** * Provides the verifier of this ChangePasswordData. * @return {string} The verifier of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getVerifier = function() { return this._verifier; }; /** * Posts to a service. * @param {Object.<string, string>} parameters The parameters to send to the service. * @param {?Object.<string, string>} headers The headers to send to the service. If null, the default authentication data is used. * @return {Promise.<null=>} Resolves to the string result of the server or rejects with an exception if the post failed. */ tutao.entity.sys.ChangePasswordData.prototype.setup = function(parameters, headers) { if (!headers) { headers = tutao.entity.EntityHelper.createAuthHeaders(); } parameters["v"] = 10; this._entityHelper.notifyObservers(false); return tutao.locator.entityRestClient.postService(tutao.entity.sys.ChangePasswordData.PATH, this, parameters, headers, null); }; /** * Provides the entity helper of this entity. * @return {tutao.entity.EntityHelper} The entity helper. */ tutao.entity.sys.ChangePasswordData.prototype.getEntityHelper = function() { return this._entityHelper; };<|fim▁end|>
* @return {string} The pwEncUserGroupKey of this ChangePasswordData.
<|file_name|>AirplaySharp.js<|end_file_name|><|fim▁begin|>import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M6 22h12l-6-6-6 6zM23 3H1v16h6v-2H3V5h18v12h-4v2h6V3z" /><|fim▁hole|>, 'AirplaySharp');<|fim▁end|>
<|file_name|>package.py<|end_file_name|><|fim▁begin|><|fim▁hole|> from spack import * class Voropp(MakefilePackage): """Voro++ is a open source software library for the computation of the Voronoi diagram, a widely-used tessellation that has applications in many scientific fields.""" homepage = "http://math.lbl.gov/voro++/about.html" url = "http://math.lbl.gov/voro++/download/dir/voro++-0.4.6.tar.gz" variant('pic', default=True, description='Position independent code') version('0.4.6', sha256='ef7970071ee2ce3800daa8723649ca069dc4c71cc25f0f7d22552387f3ea437e') def edit(self, spec, prefix): filter_file(r'CC=g\+\+', 'CC={0}'.format(self.compiler.cxx), 'config.mk') filter_file(r'PREFIX=/usr/local', 'PREFIX={0}'.format(self.prefix), 'config.mk') # We can safely replace the default CFLAGS which are: # CFLAGS=-Wall -ansi -pedantic -O3 cflags = '' if '+pic' in spec: cflags += self.compiler.cc_pic_flag filter_file(r'CFLAGS=.*', 'CFLAGS={0}'.format(cflags), 'config.mk')<|fim▁end|>
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT)
<|file_name|>fallible_impl_from.rs<|end_file_name|><|fim▁begin|>use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::ty::is_type_diagnostic_item; use clippy_utils::{is_expn_of, match_panic_def_id, method_chain_args}; use if_chain::if_chain; use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{sym, Span}; declare_clippy_lint! { /// ### What it does /// Checks for impls of `From<..>` that contain `panic!()` or `unwrap()` /// /// ### Why is this bad? /// `TryFrom` should be used if there's a possibility of failure. /// /// ### Example /// ```rust /// struct Foo(i32); /// /// // Bad /// impl From<String> for Foo { /// fn from(s: String) -> Self { /// Foo(s.parse().unwrap()) /// } /// } /// ``` /// /// ```rust /// // Good /// struct Foo(i32); /// /// use std::convert::TryFrom; /// impl TryFrom<String> for Foo { /// type Error = (); /// fn try_from(s: String) -> Result<Self, Self::Error> { /// if let Ok(parsed) = s.parse() { /// Ok(Foo(parsed)) /// } else { /// Err(()) /// } /// } /// } /// ``` pub FALLIBLE_IMPL_FROM, nursery, "Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`" } declare_lint_pass!(FallibleImplFrom => [FALLIBLE_IMPL_FROM]); impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) { // check for `impl From<???> for ..` if_chain! { if let hir::ItemKind::Impl(impl_) = &item.kind; if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.def_id); if cx.tcx.is_diagnostic_item(sym::From, impl_trait_ref.def_id); then { lint_impl_body(cx, item.span, impl_.items); } } } } fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef]) { use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath}; struct FindPanicUnwrap<'a, 'tcx> { lcx: &'a LateContext<'tcx>,<|fim▁hole|> result: Vec<Span>, } impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> { type Map = Map<'tcx>; fn visit_expr(&mut self, expr: &'tcx Expr<'_>) { // check for `begin_panic` if_chain! { if let ExprKind::Call(func_expr, _) = expr.kind; if let ExprKind::Path(QPath::Resolved(_, path)) = func_expr.kind; if let Some(path_def_id) = path.res.opt_def_id(); if match_panic_def_id(self.lcx, path_def_id); if is_expn_of(expr.span, "unreachable").is_none(); then { self.result.push(expr.span); } } // check for `unwrap` if let Some(arglists) = method_chain_args(expr, &["unwrap"]) { let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs(); if is_type_diagnostic_item(self.lcx, reciever_ty, sym::Option) || is_type_diagnostic_item(self.lcx, reciever_ty, sym::Result) { self.result.push(expr.span); } } // and check sub-expressions intravisit::walk_expr(self, expr); } fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { NestedVisitorMap::None } } for impl_item in impl_items { if_chain! { if impl_item.ident.name == sym::from; if let ImplItemKind::Fn(_, body_id) = cx.tcx.hir().impl_item(impl_item.id).kind; then { // check the body for `begin_panic` or `unwrap` let body = cx.tcx.hir().body(body_id); let mut fpu = FindPanicUnwrap { lcx: cx, typeck_results: cx.tcx.typeck(impl_item.id.def_id), result: Vec::new(), }; fpu.visit_expr(&body.value); // if we've found one, lint if !fpu.result.is_empty() { span_lint_and_then( cx, FALLIBLE_IMPL_FROM, impl_span, "consider implementing `TryFrom` instead", move |diag| { diag.help( "`From` is intended for infallible conversions only. \ Use `TryFrom` if there's a possibility for the conversion to fail"); diag.span_note(fpu.result, "potential failure(s)"); }); } } } } }<|fim▁end|>
typeck_results: &'tcx ty::TypeckResults<'tcx>,
<|file_name|>PointTargetGRG.py<|end_file_name|><|fim▁begin|># coding: utf-8 # # Esri start of added imports import sys, os, arcpy # Esri end of added imports # Esri start of added variables g_ESRI_variable_1 = 'lyrFC' g_ESRI_variable_2 = 'lyrTmp' g_ESRI_variable_3 = 'ID' g_ESRI_variable_4 = 'lyrOut' g_ESRI_variable_5 = ';' # Esri end of added variables #------------------------------------------------------------------------------ # Copyright 2014 Esri # 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. #------------------------------------------------------------------------------ # # ================================================== # PointTargetGRG.py # -------------------------------------------------- # Built on ArcGIS # ================================================== # # Creates a Gridded Reference Graphic # # # ================================================== # HISTORY: # # 8/25/2015 - mf - Needed to update script for non-ArcMap/Pro testing environment # # ================================================== import os, sys, math, traceback import arcpy from arcpy import env import Utilities # Read in the parameters targetPointOrigin = arcpy.GetParameterAsText(0) numberCellsHo = arcpy.GetParameterAsText(1) numberCellsVert = arcpy.GetParameterAsText(2) cellWidth = arcpy.GetParameterAsText(3) cellHeight = arcpy.GetParameterAsText(4) cellUnits = arcpy.GetParameterAsText(5) gridSize = arcpy.GetParameterAsText(6) labelStartPos = arcpy.GetParameterAsText(7) labelStyle = arcpy.GetParameterAsText(8) outputFeatureClass = arcpy.GetParameterAsText(9) tempOutput = os.path.join("in_memory", "tempFishnetGrid") sysPath = sys.path[0] appEnvironment = None DEBUG = True mxd = None mapList = None df, aprx = None, None def labelFeatures(layer, field): ''' set up labeling for layer ''' if appEnvironment == "ARCGIS_PRO": if layer.supports("SHOWLABELS"): for lblclass in layer.listLabelClasses(): lblclass.visible = True lblclass.expression = " [" + str(field) + "]" layer.showLabels = True elif appEnvironment == "ARCMAP": if layer.supports("LABELCLASSES"): for lblclass in layer.labelClasses: lblclass.showClassLabels = True lblclass.expression = " [" + str(field) + "]" layer.showLabels = True arcpy.RefreshActiveView() else: pass # if returns "OTHER" def findLayerByName(layerName): ''' find layer in app ''' global mapList global mxd #UPDATE # if isPro: if appEnvironment == "ARCGIS_PRO": for layer in mapList.listLayers(): if layer.name == layerName: arcpy.AddMessage("Found matching layer [" + layer.name + "]") return layer else: arcpy.AddMessage("Incorrect layer: [" + layer.name + "]") # else: elif appEnvironment == "ARCMAP": for layer in arcpy.mapping.ListLayers(mxd): if layer.name == layerName: arcpy.AddMessage("Found matching layer [" + layer.name + "]") return layer else: arcpy.AddMessage("Incorrect layer: [" + layer.name + "]") else: arcpy.AddMessage("Non-map application (ArcCatalog, stand-alone test, etc.") def RotateFeatureClass(inputFC, outputFC, angle=0, pivot_point=None): """Rotate Feature Class inputFC Input features outputFC Output feature class angle Angle to rotate, in degrees pivot_point X,Y coordinates (as space-separated string) Default is lower-left of inputFC As the output feature class no longer has a "real" xy locations, after rotation, it no coordinate system defined. """ def RotateXY(x, y, xc=0, yc=0, angle=0, units="DEGREES"): """Rotate an xy cooordinate about a specified origin x,y xy coordinates xc,yc center of rotation angle angle units "DEGREES" (default) or "RADIANS" """ import math x = x - xc y = y - yc # make angle clockwise (like Rotate_management) angle = angle * -1 if units == "DEGREES": angle = math.radians(angle) xr = (x * math.cos(angle)) - (y * math.sin(angle)) + xc yr = (x * math.sin(angle)) + (y * math.cos(angle)) + yc return xr, yr # temp names for cleanup env_file = None lyrFC, lyrTmp, lyrOut = [None] * 3 # layers tmpFC = None # temp dataset Row, Rows, oRow, oRows = [None] * 4 # cursors try: # process parameters try: xcen, ycen = [float(xy) for xy in pivot_point.split()] pivot_point = xcen, ycen except: # if pivot point was not specified, get it from # the lower-left corner of the feature class ext = arcpy.Describe(inputFC).extent xcen, ycen = ext.XMin, ext.YMin pivot_point = xcen, ycen angle = float(angle) # set up environment env_file = arcpy.CreateScratchName("xxenv",".xml","file", os.environ["TEMP"]) arcpy.SaveSettings(env_file) # Disable any GP environment clips or project on the fly arcpy.ClearEnvironment("extent") arcpy.ClearEnvironment("outputCoordinateSystem") WKS = env.workspace if not WKS: if os.path.dirname(outputFC): WKS = os.path.dirname(outputFC) else: WKS = os.path.dirname( arcpy.Describe(inputFC).catalogPath) env.workspace = env.scratchWorkspace = WKS # Disable GP environment clips or project on the fly arcpy.ClearEnvironment("extent") arcpy.ClearEnvironment("outputCoordinateSystem") # get feature class properties lyrFC = g_ESRI_variable_1 arcpy.MakeFeatureLayer_management(inputFC, lyrFC) dFC = arcpy.Describe(lyrFC) shpField = dFC.shapeFieldName shpType = dFC.shapeType FID = dFC.OIDFieldName # create temp feature class tmpFC = arcpy.CreateScratchName("xxfc", "", "featureclass") arcpy.CreateFeatureclass_management(os.path.dirname(tmpFC), os.path.basename(tmpFC), shpType) lyrTmp = g_ESRI_variable_2 arcpy.MakeFeatureLayer_management(tmpFC, lyrTmp) # set up id field (used to join later) TFID = "XXXX_FID" arcpy.AddField_management(lyrTmp, TFID, "LONG") arcpy.DeleteField_management(lyrTmp, g_ESRI_variable_3) # rotate the feature class coordinates # only points, polylines, and polygons are supported # open read and write cursors Rows = arcpy.SearchCursor(lyrFC, "", "", "%s;%s" % (shpField,FID)) oRows = arcpy.InsertCursor(lyrTmp) arcpy.AddMessage("Opened search cursor") if shpType == "Point": for Row in Rows: shp = Row.getValue(shpField) pnt = shp.getPart() pnt.X, pnt.Y = RotateXY(pnt.X, pnt.Y, xcen, ycen, angle) oRow = oRows.newRow() oRow.setValue(shpField, pnt) oRow.setValue(TFID, Row. getValue(FID)) oRows.insertRow(oRow) elif shpType in ["Polyline", "Polygon"]: parts = arcpy.Array() rings = arcpy.Array() ring = arcpy.Array() for Row in Rows: shp = Row.getValue(shpField) p = 0 for part in shp: for pnt in part: if pnt: x, y = RotateXY(pnt.X, pnt.Y, xcen, ycen, angle) ring.add(arcpy.Point(x, y, pnt.ID)) else: # if we have a ring, save it if len(ring) > 0: rings.add(ring) ring.removeAll() # we have our last ring, add it rings.add(ring) ring.removeAll() # if only one, remove nesting if len(rings) == 1: rings = rings.getObject(0) parts.add(rings) rings.removeAll() p += 1 # if only one, remove nesting if len(parts) == 1: parts = parts.getObject(0) if dFC.shapeType == "Polyline": shp = arcpy.Polyline(parts) else: shp = arcpy.Polygon(parts) parts.removeAll() oRow = oRows.newRow() oRow.setValue(shpField, shp) oRow.setValue(TFID,Row.getValue(FID)) oRows.insertRow(oRow) else: #raise Exception, "Shape type {0} is not supported".format(shpType) #UPDATE raise Exception("Shape type {0} is not supported".format(shpType)) del oRow, oRows # close write cursor (ensure buffer written) oRow, oRows = None, None # restore variables for cleanup # join attributes, and copy to output arcpy.AddJoin_management(lyrTmp, TFID, lyrFC, FID) env.qualifiedFieldNames = False arcpy.Merge_management(lyrTmp, outputFC) lyrOut = g_ESRI_variable_4 arcpy.MakeFeatureLayer_management(outputFC, lyrOut) # drop temp fields 2,3 (TFID, FID) fnames = [f.name for f in arcpy.ListFields(lyrOut)] dropList = g_ESRI_variable_5.join(fnames[2:4]) arcpy.DeleteField_management(lyrOut, dropList) #except MsgError, xmsg: #UPDATE except MsgError as xmsg: arcpy.AddError(str(xmsg)) except arcpy.ExecuteError: tbinfo = traceback.format_tb(sys.exc_info()[2])[0] arcpy.AddError(tbinfo.strip()) arcpy.AddError(arcpy.GetMessages()) numMsg = arcpy.GetMessageCount() for i in range(0, numMsg): arcpy.AddReturnMessage(i) #except Exception, xmsg: #UPDATE except Exception as xmsg: tbinfo = traceback.format_tb(sys.exc_info()[2])[0] arcpy.AddError(tbinfo + str(xmsg)) finally: # reset environment if env_file: arcpy.LoadSettings(env_file) # Clean up temp files for f in [lyrFC, lyrTmp, lyrOut, tmpFC, env_file]: try: if f: arcpy.Delete_management(f) except: pass # delete cursors try: for c in [Row, Rows, oRow, oRows]: del c except: pass # return pivot point try: pivot_point = "{0} {1}".format(*pivot_point) except: pivot_point = None return pivot_point def ColIdxToXlName(index): ''' Converts an index into a letter, labeled like excel columns, A to Z, AA to ZZ, etc. ''' if index < 1: raise ValueError("Index is too small") result = "" while True: if index > 26: index, r = divmod(index - 1, 26) result = chr(r + ord('A')) + result else: return chr(index + ord('A') - 1) + result def main(): ''' main method ''' try: #UPDATE gisVersion = arcpy.GetInstallInfo()["Version"] global appEnvironment appEnvironment = Utilities.GetApplication() if DEBUG == True: arcpy.AddMessage("App environment: " + appEnvironment) global aprx global mapList global mxd global df isPro = False #if gisVersion == "1.0": #Pro: if appEnvironment == "ARCGIS_PRO": from arcpy import mp aprx = arcpy.mp.ArcGISProject("CURRENT") mapList = aprx.listMaps()[0] isPro = True #else: elif appEnvironment == "ARCMAP": from arcpy import mapping mxd = arcpy.mapping.MapDocument('CURRENT') df = arcpy.mapping.ListDataFrames(mxd)[0] isPro = False else: if DEBUG == True: arcpy.AddMessage("Non-map application...") # If grid size is drawn on the map, use this instead of cell width and cell height inputExtentDrawnFromMap = False angleDrawn = 0 workspace = arcpy.env.workspace topLeftDrawn = 0 global cellWidth global cellHeight if float(cellWidth) == 0 and float(cellHeight) == 0: inputExtentDrawnFromMap = True tempGridFC = os.path.join(arcpy.env.scratchWorkspace, "GridSize") arcpy.CopyFeatures_management(gridSize, tempGridFC) pts = None with arcpy.da.SearchCursor(tempGridFC, 'SHAPE@XY', explode_to_points=True) as cursor: pts = [r[0] for r in cursor][0:4] arcpy.Delete_management(tempGridFC) # Find the highest points in the drawn rectangle, to calculate the top left and top right coordinates. highestPoint = None nextHighestPoint = None for pt in pts: if highestPoint is None or pt[1] > highestPoint[1]: nextHighestPoint = highestPoint highestPoint = pt elif nextHighestPoint is None or pt[1] > nextHighestPoint[1]: nextHighestPoint = pt topLeft = highestPoint if highestPoint[0] < nextHighestPoint[0] else nextHighestPoint topRight = highestPoint if highestPoint[0] > nextHighestPoint[0] else nextHighestPoint topLeftDrawn = topLeft # Calculate the cell height and cell width cellWidth= math.sqrt((pts[0][0] - pts[1][0]) ** 2 + (pts[0][1] - pts[1][1]) ** 2) cellHeight = math.sqrt((pts[1][0] - pts[2][0]) ** 2 + (pts[1][1] - pts[2][1]) ** 2) # Calculate angle hypotenuse = math.sqrt(math.pow(topLeft[0] - topRight[0], 2) + math.pow(topLeft[1] - topRight[1], 2)) adjacent = topRight[0] - topLeft[0] numberToCos = float(adjacent)/float(hypotenuse) angleInRadians = math.acos(numberToCos) angleDrawn = math.degrees(angleInRadians) if (topRight[1] > topLeft[1]): angleDrawn = 360 - angleDrawn else: if (cellUnits == "Feet"): cellWidth = float(cellWidth) * 0.3048 cellHeight = float(cellHeight) * 0.3048 # Get the coordinates of the point inputExtentDrawnFromMap. rows = arcpy.SearchCursor(targetPointOrigin) extent = None for row in rows: shape = row.getValue("SHAPE") extent = shape.extent pointExtents = str.split(str(extent)) ''' This seemed to be shifting the grid when it was not required so commented out # Shift the grid center point if the rows and/or columns are even. if (float(numberCellsHo)%2 == 0.0): hoShiftAmt = float(cellHeight) / 2.0 # Determines shift up/down based on where box was inputExtentDrawnFromMap if inputExtentDrawnFromMap == False: pointExtents[1] = str(float(pointExtents[1]) - hoShiftAmt) elif (float(topLeftDrawn[1]) > float(pointExtents[1])): pointExtents[1] = str(float(pointExtents[1]) - hoShiftAmt) else: pointExtents[1] = str(float(pointExtents[1]) + hoShiftAmt) if (float(numberCellsVert)%2 == 0.0): vertShiftAmt = float(cellWidth) / 2.0 # Determines shift left/right based on where box was inputExtentDrawnFromMap if inputExtentDrawnFromMap == False: pointExtents[0] = str(float(pointExtents[0]) - vertShiftAmt) elif (float(topLeftDrawn[0]) > float(pointExtents[0])): pointExtents[0] = str(float(pointExtents[0]) - vertShiftAmt) else: pointExtents[0] = str(float(pointExtents[0]) + vertShiftAmt) ''' # From the template extent, get the origin, y axis, and opposite corner coordinates rightCorner = float(pointExtents[0]) + ((float(cellWidth) * float(numberCellsVert)) /2.0) leftCorner = float(pointExtents[0]) - ((float(cellWidth) * float(numberCellsVert)) /2.0) topCorner = float(pointExtents[1]) + ((float(cellHeight) * float(numberCellsHo)) /2.0) bottomCorner = float(pointExtents[1]) - ((float(cellHeight) * float(numberCellsHo)) /2.0) originCoordinate = str(leftCorner) + " " + str(bottomCorner) yAxisCoordinate = str(leftCorner) + " " + str(bottomCorner + 10) oppCornerCoordinate = str(rightCorner) + " " + str(topCorner) fullExtent = str(leftCorner) + " " + str(bottomCorner) + " " + str(rightCorner) + " " + str(topCorner) # If grid size is drawn on the map, then calculate the rotation of the grid if inputExtentDrawnFromMap: # Find the highest two points in the inputExtentDrawnFromMap shape highestPoint = None nextHighestPoint = None for pt in pts: if highestPoint is None or pt[1] > highestPoint[1]: nextHighestPoint = highestPoint highestPoint = pt elif nextHighestPoint is None or pt[1] > nextHighestPoint[1]: nextHighestPoint = pt topLeft = highestPoint if highestPoint[0] < nextHighestPoint[0] else nextHighestPoint topRight = highestPoint if highestPoint[0] > nextHighestPoint[0] else nextHighestPoint yDiff = topRight[1] - topLeft[1] xDiff = topRight[0] - topLeft[0] # Set the Y-Axis Coordinate so that the grid rotates properly extentHeight = float(topCorner) - float(bottomCorner) # Set the start position for labeling startPos = None if (labelStartPos == "Upper-Right"): startPos = "UR" elif (labelStartPos == "Upper-Left"): startPos = "UL" elif (labelStartPos == "Lower-Left"): startPos = "LL" elif (labelStartPos == "Lower-Right"): startPos = "LR" arcpy.AddMessage("Creating Fishnet Grid") arcpy.CreateFishnet_management(tempOutput, originCoordinate, yAxisCoordinate, 0, 0, str(numberCellsHo), str(numberCellsVert), oppCornerCoordinate, "NO_LABELS", fullExtent, "POLYGON") # Sort the grid upper left to lower right, and delete the in memory one arcpy.AddMessage("Sorting the grid for labeling") tempSort = os.path.join("in_memory", "tempSort") arcpy.Sort_management(tempOutput, tempSort, [["Shape", "ASCENDING"]], startPos) # arcpy.Delete_management("in_memory") #Not sure why we are trying to delete in_memory # Add a field which will be used to add the grid labels arcpy.AddMessage("Adding field for labeling the grid") gridField = "Grid" arcpy.AddField_management(tempSort, gridField, "TEXT") # Number the fields arcpy.AddMessage("Numbering the grids") letterIndex = 1 secondLetterIndex = 1 letter = 'A' secondLetter = 'A' number = 1 lastY = -9999 cursor = arcpy.UpdateCursor(tempSort) for row in cursor: yPoint = row.getValue("SHAPE").firstPoint.Y if (lastY != yPoint) and (lastY != -9999): letterIndex += 1 letter = ColIdxToXlName(letterIndex) if (labelStyle != "Numeric"): number = 1 secondLetter = 'A' secondLetterIndex = 1 lastY = yPoint if (labelStyle == "Alpha-Numeric"): row.setValue(gridField, str(letter) + str(number)) elif (labelStyle == "Alpha-Alpha"): row.setValue(gridField, str(letter) + str(secondLetter)) elif (labelStyle == "Numeric"): row.setValue(gridField, str(number)) cursor.updateRow(row) number += 1 secondLetterIndex += 1 secondLetter = ColIdxToXlName(secondLetterIndex) # Rotate the shape, if needed. if (inputExtentDrawnFromMap): arcpy.AddMessage("Rotating the grid") RotateFeatureClass(tempSort, outputFeatureClass, angleDrawn, pointExtents[0] + " " + pointExtents[1]) else: arcpy.CopyFeatures_management(tempSort, outputFeatureClass) arcpy.Delete_management(tempSort) # Get and label the output feature #UPDATE targetLayerName = os.path.basename(outputFeatureClass) if appEnvironment == "ARCGIS_PRO": #params = arcpy.GetParameterInfo() ## get the symbology from the GRG.lyr #scriptPath = sys.path[0] #layerFilePath = os.path.join(scriptPath,r"commondata\userdata\GRG.lyrx") #arcpy.AddMessage("Applying Symbology from {0}".format(layerFilePath)) #params[8].symbology = layerFilePath arcpy.AddMessage("Do not apply symbology it will be done in the next task step") elif appEnvironment == "ARCMAP": #arcpy.AddMessage("Adding features to map (" + str(targetLayerName) + ")...") #arcpy.MakeFeatureLayer_management(outputFeatureClass, targetLayerName) # create a layer object #layer = arcpy.mapping.Layer(targetLayerName) # get the symbology from the NumberedStructures.lyr #layerFilePath = os.path.join(os.getcwd(),"data\Layers\GRG.lyr") #layerFilePath = os.path.join(os.path.dirname(os.path.dirname(__file__)),"layers\GRG.lyr") # apply the symbology to the layer #arcpy.ApplySymbologyFromLayer_management(layer, layerFilePath) # add layer to map #arcpy.mapping.AddLayer(df, layer, "AUTO_ARRANGE") # find the target layer in the map #mapLyr = arcpy.mapping.ListLayers(mxd, targetLayerName)[0] #arcpy.AddMessage("Labeling output features (" + str(targetLayerName) + ")...") # Work around needed as ApplySymbologyFromLayer_management does not honour labels #labelLyr = arcpy.mapping.Layer(layerFilePath) # copy the label info from the source to the map layer #mapLyr.labelClasses = labelLyr.labelClasses # turn labels on #mapLyr.showLabels = True arcpy.AddMessage("Non-map environment, skipping labeling based on best practices") else: arcpy.AddMessage("Non-map environment, skipping labeling...") # Apply symbology to the GRG layer #UPDATE #symbologyPath = os.path.dirname(workspace) + "\\Layers\GRG.lyr" #arcpy.ApplySymbologyFromLayer_management(layer, symbologyPath) # Set tool output arcpy.SetParameter(8, outputFeatureClass) except arcpy.ExecuteError: # Get the tool error messages msgs = arcpy.GetMessages() arcpy.AddError(msgs) print(msgs) except: # Get the traceback object tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a message string pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + \ "\nError Info:\n" + str(sys.exc_info()[1])<|fim▁hole|> # Return python error messages for use in script tool or Python Window arcpy.AddError(pymsg) arcpy.AddError(msgs) # Print Python error messages for use in Python / Python Window print(pymsg + "\n") print(msgs) # MAIN ============================================= if __name__ == "__main__": main()<|fim▁end|>
msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n"
<|file_name|>pythonlight.py<|end_file_name|><|fim▁begin|>import sys from PyQt4 import QtCore, QtGui, uic import light qtCreatorFile = "pythonlight.ui" # Enter file here. Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) class LightApp(QtGui.QMainWindow, Ui_MainWindow): def __init__(self): QtGui.QMainWindow.__init__(self)<|fim▁hole|> self.lightDisplay.setText(self.light.show()) self.lightSwitch.released.connect(self.toggle) def toggle(self): self.light.switch() self.lightDisplay.setText(self.light.show()) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) window = LightApp() window.show() sys.exit(app.exec_())<|fim▁end|>
Ui_MainWindow.__init__(self) self.setupUi(self) self.light = light.Light()
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range ) from random import randint author = 'Your name here' doc = """ Your app description """ class Constants(BaseConstants): name_in_url = 'T1' players_per_group = None num_rounds = 1 c_winning_number = 5 c_player_endowment = c(100) c_charity_endowment = c(100) c_winning_payoff = c(50) c_charity_deduction = c(50) class Subsession(BaseSubsession): def creating_session(self): for p in self.get_players(): p.charity_account = Constants.c_charity_endowment p.payoff = Constants.c_player_endowment # "In addition to your show-up fee, you start with an endowment of 100 tokens" p.random_number = randint(1, 6) class Group(BaseGroup): pass<|fim▁hole|> class Player(BasePlayer): failed_captcha = models.BooleanField(initial=False) roll3_report3_bonus_question = models.PositiveIntegerField( label="What is the bonus payment if you roll a 3 and report a 3 ? (enter the number in tokens)", ) roll3_report5_bonus_question = models.PositiveIntegerField( label="What is the bonus payment if you roll a 3 and report a 5 ? (enter the number in tokens)", ) roll5_report5_bonus_question = models.PositiveIntegerField( label="What is the bonus payment if you roll a 5 and report a 5 ? (enter the number in tokens)", ) roll3_report3_charity_question = models.PositiveIntegerField( label="What amount will be subtracted from the charity if you roll a 3 and report a 3 ? " "(enter the number in tokens)", ) roll3_report5_charity_question = models.PositiveIntegerField( label="What amount will be subtracted from the charity if you roll a 3 and report a 5 ? " "(enter the number in tokens)", ) roll5_report5_charity_question = models.PositiveIntegerField( label="What amount will be subtracted from the charity if you roll a 5 and report a 5 ? " "(enter the number in tokens)", ) charity_account = models.CurrencyField(initial=c(0)) random_number = models.IntegerField(min=1, max=6) reported_number = models.IntegerField(verbose_name="", min=1, max=6) def compute_payoff(self): # Add the gain according to reported number if self.reported_number == Constants.c_winning_number: self.payoff += Constants.c_winning_payoff if self.reported_number != self.random_number: # Deduct the punishment to the charity account self.charity_account -= Constants.c_charity_deduction<|fim▁end|>
<|file_name|>Game.py<|end_file_name|><|fim▁begin|>from Start_up import* from Player import Player, HealthBar from Bullet import Bullet from Enemy import Enemy from Stopper import Stopper from Particle import Particle from Stars import Star, create_stars from Package import EnemyDrop, HealthPack from Notes import NoteController class Game: def __init__(self, play, health_bar): self.own_state = game_state self.next_state = self.own_state self.player = play self.enemy_id_tracker = 0 self.left_stop = Stopper((-30, 0), True, False) self.right_stop = Stopper((width, 0), False, True) self.bullet_list = [] self.enemy_list = [] self.kill_list = [] self.particle_list = [] self.package_list = [] self.to_update = [] self.to_display = [] self.to_text = [] self.star_list = create_stars("game") self.info_bar = pygame.Surface((width, 30)) self.info_bar.fill(main_theme) self.info_bar.set_alpha(100) self.health_bar = health_bar self.note_controller = NoteController((width - 10, 40)) def reset(self, play): self.own_state = game_state self.next_state = self.own_state self.player = play self.health_bar = HealthBar(self.player) self.enemy_id_tracker = 0 self.bullet_list = [] self.enemy_list = [] self.kill_list = [] self.particle_list = [] self.package_list = [] self.to_update = [] self.to_display = [] self.to_text = []<|fim▁hole|> def update_all(self): # a check for all update elements, providing the # relevant information for the objects update for x in range(0, len(self.to_update)): if isinstance(self.to_update[x], Particle): self.to_update[x].update() elif isinstance(self.to_update[x], Star): self.to_update[x].update() elif isinstance(self.to_update[x], Enemy): self.to_update[x].update(self.bullet_list) elif isinstance(self.to_update[x], Player): self.to_update[x].update(self.package_list, self.note_controller, self.bullet_list, self.health_bar) elif isinstance(self.to_update[x], Bullet): self.to_update[x].update() elif isinstance(self.to_update[x], EnemyDrop): self.to_update[x].update() elif isinstance(self.to_update[x], HealthPack): self.to_update[x].update() elif isinstance(self.to_update[x], NoteController): self.to_update[x].update() elif isinstance(self.to_update[x], Stopper): self.to_update[x].update(self.bullet_list, self.enemy_list, self.player, self.note_controller) elif isinstance(self.to_update[x], HealthBar): self.to_update[x].update() def display_all(self): # fill screen with black and display all game information main_s.fill((20, 20, 20)) for x in range(0, len(self.to_display)): if isinstance(self.to_display[x], Player): if self.to_display[x].alive: self.to_display[x].display() else: self.to_display[x].display() main_s.blit(self.info_bar, (0, 0)) main_s.blit(font.render("ESC TO PAUSE", True, (255, 255, 255)), (width - 115, 5)) def text_all(self): # display all text needed at the top of the screen total_length = 0 for x in range(0, len(self.to_text)): main_s.blit(font.render(str(self.to_text[x]), True, (255, 255, 255)), (5 + (15 * total_length), 5)) total_length += len(self.to_text[x]) def hit_particles(self, rect_hit, colour): # create particles with random speeds, directions and sizes numbers_z = range(-10, 10) numbers_nz = range(-10, -1) + range(1, 10) for x in range(0, settings.loaded_enemy_particles): x_temp = random.choice(numbers_z) y_temp = random.choice(numbers_z) dy = y_temp dx = x_temp # make sure that dx and dy are not both 0 so that there # are no particles static on the screen if x_temp == 0 and y_temp != 0: dy = y_temp dx = x_temp if y_temp == 0 and x_temp != 0: dy = y_temp dx = x_temp if x_temp == y_temp == 0: dy = random.choice(numbers_nz) dx = random.choice(numbers_nz) particle = Particle(random.randint(1, 3), (dx, dy), rect_hit, colour) self.particle_list.append(particle) def remove_particles(self): # remove particles that are no longer colliding with the screen # removed from the end first so that the list does not effect # later elements to remove for x in range(0, len(self.particle_list)): try: if not pygame.sprite.collide_rect(screen_rect, self.particle_list[len(self.particle_list) - x - 1]): del self.particle_list[len(self.particle_list) - x - 1] except: # break in case [len(p_list) - x - 1] is out of range break def remove_stars(self): # remove stars that are no longer colliding with the screen # removed from the end first so that the list does not effect # later elements to remove for x in range(0, len(self.star_list)): try: if not pygame.sprite.collide_rect(screen_rect, self.star_list[len(self.star_list) - x - 1]): del self.star_list[len(self.star_list) - x - 1] except: # break in case [len(p_list) - x - 1] is out of range break def remove_packages(self): print(len(self.package_list)) for i in range(0, len(self.package_list)): try: if not pygame.sprite.collide_rect(screen_rect, self.package_list[len(self.package_list) - i - 1]): del self.package_list[len(self.package_list) - i - 1] except IndexError: # break in case [len(p_list) - x - 1] is out of range break def check_enemy_alive(self): # add enemies to a removal list if they are dead for x in range(0, len(self.enemy_list)): if self.enemy_list[x].dead: self.kill_list.append(self.enemy_list[x]) def kill_enemies(self): # remove enemies from enemy list that are on the kill list # create a package and give the player the coins dropped # create particles originating from the now dead enemy # create a notification for the user saying they have found money for x in range(0, len(self.kill_list)): for y in range(0, len(self.enemy_list)): try: if self.kill_list[len(self.kill_list) - x - 1].id == self.enemy_list[len(self.enemy_list) - y - 1].id: del self.kill_list[len(self.kill_list) - x - 1] self.note_controller.add_note("+ " + str(self.enemy_list[len(self.enemy_list) - y - 1].money * self.player.money_collection) + " coins", main_theme) self.player.get_coins(self.enemy_list[len(self.enemy_list) - y - 1].money) self.hit_particles(self.enemy_list[len(self.enemy_list) - y - 1].rect, white) self.random_enemy_drop(self.enemy_list[len(self.enemy_list) - y - 1].dx, self.enemy_list[len(self.enemy_list) - y - 1].rect.center) del self.enemy_list[len(self.enemy_list) - y - 1] break except: break def random_event_enemy(self): # create an enemy if the random variable is 1 if random.randint(1, settings.loaded_enemy_chance) == 1: enemy = Enemy(self.enemy_id_tracker) self.enemy_list.append(enemy) self.enemy_id_tracker += 1 def random_event_star(self): if random.randint(1, star_chance) == 1: # create a star starting at the right and set to move to the left s = Star(width + 10, # x pos (start a little off screen) random.randint(0, height), # y pos random.randint(1, 2), # dx 0) # dy self.star_list.append(s) def random_enemy_drop(self, speed, pos): # random chance that package will be created if random.randint(1, package_chance) == 1: e = EnemyDrop(speed, pos) self.package_list.append(e) def random_health_pack(self): pos = (width + 10, random.randint(20, height - 20)) # random chance that package will be created if random.randint(1, package_chance * 50) == 1: h = HealthPack(-random.randint(1, 2), pos) self.package_list.append(h) def input(self, event_list): # player input key = pygame.key.get_pressed() if key[pygame.K_UP]: self.player.move(-1) if key[pygame.K_DOWN]: self.player.move(1) if key[pygame.K_SPACE]: self.bullet_list = self.player.shoot(self.bullet_list) for event in event_list: if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.next_state = pause_state def run(self, event_list): # run all game functions self.input(event_list) self.random_event_enemy() self.random_event_star() self.random_health_pack() self.check_enemy_alive() self.kill_enemies() self.remove_particles() self.remove_stars() #self.remove_packages() # reload all lists self.to_display = self.package_list + self.star_list + self.bullet_list + self.enemy_list + \ self.particle_list + [self.player, self.note_controller, self.health_bar] self.to_update = [self.player, self.note_controller, self.left_stop, self.right_stop] + \ self.package_list + self.star_list + self.bullet_list + self.enemy_list + self.particle_list self.to_text = [str(self.player.money) + " COINS"] if not self.player.alive: self.hit_particles(self.player.rect, main_theme) self.next_state = game_over_state if self.player.hit: self.health_bar.update_health() self.hit_particles(self.player.rect, main_theme) if self.player.health_update: self.health_bar.update_health() self.player.health_update = False self.update_all() self.display_all() self.text_all() #print(len(self.package_list)) # by default return the games own state value # otherwise this will be changed in the user input return self.next_state<|fim▁end|>
self.star_list = create_stars("game") self.note_controller = NoteController((width - 10, 40))
<|file_name|>test_write_xf.py<|end_file_name|><|fim▁begin|>############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, [email protected] # import unittest from ...compatibility import StringIO from ...styles import Styles from ...format import Format class TestWriteXf(unittest.TestCase): """ Test the Styles _write_xf() method. """ def setUp(self): self.fh = StringIO() self.styles = Styles() self.styles._set_filehandle(self.fh) def test_write_xf_1(self): """Test the _write_xf() method. Default properties.""" properties = {} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_2(self): """Test the _write_xf() method. Has font but is first XF.""" properties = {'has_font': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_3(self): """Test the _write_xf() method. Has font but isn't first XF.""" properties = {'has_font': 1, 'font_index': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_4(self): """Test the _write_xf() method. Uses built-in number format.""" properties = {'num_format_index': 2} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="2" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_5(self): """Test the _write_xf() method. Uses built-in number format + font.""" properties = {'num_format_index': 2, 'has_font': 1, 'font_index': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="2" fontId="1" fillId="0" borderId="0" xfId="0" applyNumberFormat="1" applyFont="1"/>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_6(self): """Test the _write_xf() method. Vertical alignment = top.""" properties = {'align': 'top'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment vertical="top"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_7(self): """Test the _write_xf() method. Vertical alignment = centre.""" properties = {'align': 'vcenter'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment vertical="center"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_8(self): """Test the _write_xf() method. Vertical alignment = bottom.""" properties = {'align': 'bottom'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"/>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_9(self): """Test the _write_xf() method. Vertical alignment = justify.""" properties = {'align': 'vjustify'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment vertical="justify"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_10(self): """Test the _write_xf() method. Vertical alignment = distributed.""" properties = {'align': 'vdistributed'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment vertical="distributed"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_11(self): """Test the _write_xf() method. Horizontal alignment = left.""" properties = {'align': 'left'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="left"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_12(self): """Test the _write_xf() method. Horizontal alignment = center.""" properties = {'align': 'center'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="center"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_13(self): """Test the _write_xf() method. Horizontal alignment = right.""" properties = {'align': 'right'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="right"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_14(self): """Test the _write_xf() method. Horizontal alignment = left + indent.""" properties = {'align': 'left', 'indent': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="left" indent="1"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_15(self): """Test the _write_xf() method. Horizontal alignment = right + indent.""" properties = {'align': 'right', 'indent': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="right" indent="1"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_16(self): """Test the _write_xf() method. Horizontal alignment = fill.""" properties = {'align': 'fill'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="fill"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_17(self): """Test the _write_xf() method. Horizontal alignment = justify."""<|fim▁hole|> properties = {'align': 'justify'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="justify"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_18(self): """Test the _write_xf() method. Horizontal alignment = center across.""" properties = {'align': 'center_across'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="centerContinuous"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_19(self): """Test the _write_xf() method. Horizontal alignment = distributed.""" properties = {'align': 'distributed'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="distributed"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_20(self): """Test the _write_xf() method. Horizontal alignment = distributed + indent.""" properties = {'align': 'distributed', 'indent': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="distributed" indent="1"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_21(self): """Test the _write_xf() method. Horizontal alignment = justify distributed.""" properties = {'align': 'justify_distributed'} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="distributed" justifyLastLine="1"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_22(self): """Test the _write_xf() method. Horizontal alignment = indent only.""" properties = {'indent': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="left" indent="1"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_23(self): """Test the _write_xf() method. Horizontal alignment = distributed + indent.""" properties = {'align': 'justify_distributed', 'indent': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment horizontal="distributed" indent="1"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_24(self): """Test the _write_xf() method. Alignment = text wrap""" properties = {'text_wrap': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment wrapText="1"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_25(self): """Test the _write_xf() method. Alignment = shrink to fit""" properties = {'shrink': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment shrinkToFit="1"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_26(self): """Test the _write_xf() method. Alignment = reading order""" properties = {'reading_order': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment readingOrder="1"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_27(self): """Test the _write_xf() method. Alignment = reading order""" properties = {'reading_order': 2} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment readingOrder="2"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_28(self): """Test the _write_xf() method. Alignment = rotation""" properties = {'rotation': 45} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment textRotation="45"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_29(self): """Test the _write_xf() method. Alignment = rotation""" properties = {'rotation': -45} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment textRotation="135"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_30(self): """Test the _write_xf() method. Alignment = rotation""" properties = {'rotation': 270} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment textRotation="255"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_31(self): """Test the _write_xf() method. Alignment = rotation""" properties = {'rotation': 90} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment textRotation="90"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_32(self): """Test the _write_xf() method. Alignment = rotation""" properties = {'rotation': -90} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1"><alignment textRotation="180"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_33(self): """Test the _write_xf() method. With cell protection.""" properties = {'locked': 0} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyProtection="1"><protection locked="0"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_34(self): """Test the _write_xf() method. With cell protection.""" properties = {'hidden': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyProtection="1"><protection hidden="1"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_35(self): """Test the _write_xf() method. With cell protection.""" properties = {'locked': 0, 'hidden': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyProtection="1"><protection locked="0" hidden="1"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_xf_36(self): """Test the _write_xf() method. With cell protection + align.""" properties = {'align': 'right', 'locked': 0, 'hidden': 1} xf_format = Format(properties) self.styles._write_xf(xf_format) exp = """<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0" applyAlignment="1" applyProtection="1"><alignment horizontal="right"/><protection locked="0" hidden="1"/></xf>""" got = self.fh.getvalue() self.assertEqual(got, exp)<|fim▁end|>
<|file_name|>longest-increasing-subsequence.py<|end_file_name|><|fim▁begin|>__author__ = 'yinjun' class Solution: """ @param nums: The integer array<|fim▁hole|> if nums == None or nums == []: return 0 l = len(nums) length = [0 for i in range()] maxLength = 0 for i in range(l): length[i] = 1 for j in range(0, i): if nums[j] <= nums[i]: length[i] = max(length[i], length[j] + 1) maxLength = max(maxLength, length[i]) return maxLength<|fim▁end|>
@return: The length of LIS (longest increasing subsequence) """ def longestIncreasingSubsequence(self, nums): # write your code here
<|file_name|>menu.py<|end_file_name|><|fim▁begin|>def app_logo_attr(): """ Return app logo LI attributes. """ attr = { '_class': 'navbar-brand', '_role': 'button'} if request.controller == 'studies': attr['_onclick'] = 'tocModal(event);' attr['_title'] = 'Chapter Studies' elif request.controller == 'poems' and request.function == 'chapter': page = (int(request.args(0)) + 8) / 9 if page == 1: attr['_href'] = URL('poems', 'index') attr['_title'] = 'Poems' else: attr['_href'] = URL('poems', 'page', args=[str(page)]) attr['_title'] = 'Poems page %d' % page else: attr['_href'] = URL('poems', 'index') attr['_title'] = 'Poems' return attr def auth_navbar(): """ Set up right navbar for logged-in user. """ navbar_right = auth.navbar(mode='dropdown') menu = navbar_right.element('.dropdown-menu') menu.insert(0, LI(A('Blacklist', _href=URL('blacklist', 'index')))) menu.insert(0, LI(A('Whitelist', _href=URL('whitelist', 'index')))) menu.insert(0, LI('', _class='divider')) menu.insert(0, LI(A('Unihan Dump', _href=URL('unihan', 'dump')))) if request.controller != 'studies': menu.insert(0, LI(A('Studies', _href=URL('studies', 'index')))) menu.insert(0, LI(A('Manage Poems', _href=URL('poems', 'manage')))) if request.controller != 'poems': menu.insert(0, LI(A('Poems', _href=URL('poems', 'index')))) if request.controller != 'about': menu.insert(0, LI(A('About', _href=URL('about', 'index')))) return UL(navbar_right, _class='nav navbar-nav navbar-right') def default_study(): """ Return a URL for the default study app chapter. """ public, private = cache.ram('toc', lambda: studies_toc()) if auth.user: toc_map = private else: toc_map = public if toc_map: return URL('studies', 'chapter', args=[toc_map.items()[0][0]]) return URL('poems', 'index') def plain_navbar(): """ Return right navbar for non-logged-in user. """ return UL( LI(<|fim▁hole|> LI( A('Studies', _class='nav-link', _href=URL('studies', 'index')), _class='nav-item', ), LI( A('About', _class='nav-link', _href=URL('about', 'index')), _class='nav-item', ), _class='nav navbar-nav navbar-right' ) def studies_toc(): """ Return a tuple of ordered dicts that map chapter id to toc links. The first dict contains chapters that don't have an associated English poem, the second dict contains chapters that do. """ from collections import OrderedDict def study_link(chapter): verse = db.verse[chapter] url = URL('studies', 'chapter', args=[verse.chapter.number]) cls = 'studies-toc-link' lnk = '%i %s' % (verse.chapter.number, verse.chapter.title or '') return DIV(A(lnk, _class=cls, _href=url)) public = OrderedDict() private = OrderedDict() for poem in db(db.poem).select(orderby=db.poem.chapter): link = study_link(poem.chapter) public[int(poem.chapter)] = link for chapter in range(1, 82): link = study_link(chapter) private[int(chapter)] = link return public, private # Set navbar elements. response.navbar_logo = LI(A('Daoistic', **app_logo_attr())) if auth.user: response.navbar_right = auth_navbar() else: response.navbar_right = cache.ram('navbar_right', lambda: plain_navbar())<|fim▁end|>
A('Poems', _class='nav-link', _href=URL('poems', 'index')), _class='nav-item', ),
<|file_name|>users_config_test.go<|end_file_name|><|fim▁begin|>package main import ( "path/filepath" "testing" "github.com/stretchr/testify/assert" ) var testDataDir = "testdata" func TestUserConfig(t *testing.T) { type testCase struct { filename string exepctedMapping map[string]string expectedErrorNil bool } testCases := []testCase{ testCase{"does-not-exist.yml", nil, false}, testCase{"single-user.yml", map[string]string{ "user_id": "@username"}, true},<|fim▁hole|> testCase{"not-yaml.txt", map[string]string{"who": "cares"}, false}, } for _, tc := range testCases { mapping, err := ReadUsersFile(filepath.Join(testDataDir, tc.filename)) if tc.expectedErrorNil { assert.Nil(t, err) assert.Equal(t, tc.exepctedMapping, mapping) } else { assert.NotNil(t, err) } } }<|fim▁end|>
testCase{"multiple-users.yml", map[string]string{ "[email protected]": "@alice", "Robert Johnson": "@robby"}, true},
<|file_name|>a00455.js<|end_file_name|><|fim▁begin|>var a00455 = [ [ "UnicharIdArrayUtils", "a02761.html", null ], [ "AmbigSpec", "a02765.html", "a02765" ], [ "UnicharAmbigs", "a02769.html", "a02769" ], [ "MAX_AMBIG_SIZE", "a00455.html#a66b35d22667233a1566433c6dd864463", null ], [ "UnicharAmbigsVector", "a00455.html#aa63fceec9a01c185fac83c0e7d04fe08", null ],<|fim▁hole|> [ "REPLACE_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222a4de7fc7ae32fd87a4c53e4b6bf3322de", null ], [ "DEFINITE_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222a36712914249ab1d96c4f395c06bc7009", null ], [ "SIMILAR_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222aba0a03f0cccfdd9e45817623613dd740", null ], [ "CASE_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222a29c650e9672a75e50491fc10c0f07ec5", null ], [ "AMBIG_TYPE_COUNT", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222a79854db5a6d73c698dd9b003f426918f", null ] ] ], [ "ELISTIZEH", "a00455.html#aad9b817c74cee6bd76a4912e7f54ff7b", null ] ];<|fim▁end|>
[ "UnicharIdVector", "a00455.html#a3dad1b2dad5ed3069bdb4c971116b9c5", null ], [ "AmbigType", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222", [ [ "NOT_AMBIG", "a00455.html#aa13017f5f891a1f9f95074bf26a5b222af40a6c3f3fbd83ba09a6607f534349dc", null ],
<|file_name|>test_npa.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest from pyparsing import ParseException from tests.utils.grammar import get_record_grammar """ CWR Non-Roman Alphabet Agreement Party Name grammar tests. The following cases are tested: """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' class TestNPAGrammar(unittest.TestCase): """ Tests that the NPA grammar decodes correctly formatted strings """ def setUp(self): self.grammar = get_record_grammar('nra_agreement_party')<|fim▁hole|> def test_valid_full(self): """ Tests that IPA grammar decodes correctly formatted record prefixes. This test contains all the optional fields. """ record = 'NPA0000123400000023012345678PARTY NAME PARTY WRITER NAME ES' result = self.grammar.parseString(record)[0] self.assertEqual('NPA', result.record_type) self.assertEqual(1234, result.transaction_sequence_n) self.assertEqual(23, result.record_sequence_n) self.assertEqual('012345678', result.ip_n) self.assertEqual('PARTY NAME', result.ip_name) self.assertEqual('PARTY WRITER NAME', result.ip_writer_name) self.assertEqual('ES', result.language_code) def test_valid_min(self): """ Tests that IPA grammar decodes correctly formatted record prefixes. This test contains none of the optional fields. """ record = 'NPA0000123400000023000000000PARTY NAME PARTY WRITER NAME ' result = self.grammar.parseString(record)[0] self.assertEqual('NPA', result.record_type) self.assertEqual(1234, result.transaction_sequence_n) self.assertEqual(23, result.record_sequence_n) self.assertEqual('000000000', result.ip_n) self.assertEqual('PARTY NAME', result.ip_name) self.assertEqual('PARTY WRITER NAME', result.ip_writer_name) self.assertEqual(None, result.language_code) def test_extended_character(self): """ Tests that IPA grammar decodes correctly formatted record prefixes. This test contains none of the optional fields. """ record = 'NPA0000123400000023000000000PARTY NAME \xc6\x8f PARTY WRITER NAME \xc6\x8f ' result = self.grammar.parseString(record)[0] self.assertEqual('NPA', result.record_type) self.assertEqual(1234, result.transaction_sequence_n) self.assertEqual(23, result.record_sequence_n) self.assertEqual('000000000', result.ip_n) self.assertEqual('PARTY NAME \xc6\x8f', result.ip_name) self.assertEqual('PARTY WRITER NAME \xc6\x8f', result.ip_writer_name) self.assertEqual(None, result.language_code) class TestNPAGrammarException(unittest.TestCase): def setUp(self): self.grammar = get_record_grammar('nra_agreement_party') def test_empty(self): """ Tests that a exception is thrown when the the works number is zero. """ record = '' self.assertRaises(ParseException, self.grammar.parseString, record) def test_invalid(self): record = 'This is an invalid string' self.assertRaises(ParseException, self.grammar.parseString, record)<|fim▁end|>
<|file_name|>page_privacy.py<|end_file_name|><|fim▁begin|>from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404 from wagtail.wagtailcore.models import Page, PageViewRestriction from wagtail.wagtailadmin.forms import PageViewRestrictionForm from wagtail.wagtailadmin.modal_workflow import render_modal_workflow def set_privacy(request, page_id): page = get_object_or_404(Page, id=page_id) page_perms = page.permissions_for_user(request.user) if not page_perms.can_set_view_restrictions(): raise PermissionDenied # fetch restriction records in depth order so that ancestors appear first restrictions = page.get_view_restrictions().order_by('page__depth') if restrictions: restriction = restrictions[0] restriction_exists_on_ancestor = (restriction.page != page) else: restriction = None restriction_exists_on_ancestor = False if request.POST: form = PageViewRestrictionForm(request.POST) if form.is_valid() and not restriction_exists_on_ancestor: if form.cleaned_data['restriction_type'] == 'none': # remove any existing restriction if restriction: restriction.delete() else: # restriction_type = 'password' if restriction: restriction.password = form.cleaned_data['password'] restriction.save() else: # create a new restriction object PageViewRestriction.objects.create( page=page, password=form.cleaned_data['password']) return render_modal_workflow( request, None, 'wagtailadmin/page_privacy/set_privacy_done.js', { 'is_public': (form.cleaned_data['restriction_type'] == 'none')<|fim▁hole|> else: # request is a GET if not restriction_exists_on_ancestor: if restriction: form = PageViewRestrictionForm(initial={ 'restriction_type': 'password', 'password': restriction.password }) else: # no current view restrictions on this page form = PageViewRestrictionForm(initial={ 'restriction_type': 'none' }) if restriction_exists_on_ancestor: # display a message indicating that there is a restriction at ancestor level - # do not provide the form for setting up new restrictions return render_modal_workflow( request, 'wagtailadmin/page_privacy/ancestor_privacy.html', None, { 'page_with_restriction': restriction.page, } ) else: # no restriction set at ancestor level - can set restrictions here return render_modal_workflow( request, 'wagtailadmin/page_privacy/set_privacy.html', 'wagtailadmin/page_privacy/set_privacy.js', { 'page': page, 'form': form, } )<|fim▁end|>
} )
<|file_name|>issue-3953.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-tidy-linelength use std::cmp::PartialEq; trait Hahaha: PartialEq + PartialEq { //~^ ERROR trait `PartialEq` already appears in the list of bounds } struct Lol(int); impl Hahaha for Lol { } impl PartialEq for Lol { fn eq(&self, other: &Lol) -> bool { **self != **other } fn ne(&self, other: &Lol) -> bool { **self == **other } } fn main() { if Lol(2) == Lol(4) {<|fim▁hole|> println!("2 == 4"); } else { println!("2 != 4"); } }<|fim▁end|>
<|file_name|>auth.go<|end_file_name|><|fim▁begin|>package controllers import ( "github.com/revel/revel" "AuthKeyPush/app/models" ) type Auth struct { *revel.Controller } func (c Auth) Github(code string) revel.Result { login := models.GitHub(code) if login == true { c.Session["login"] = "true" } else { c.Session["login"] = "false" c.Session["msg"] = "Login faied. Check conf/site.json or README.md" } <|fim▁hole|><|fim▁end|>
return c.Redirect("/") }
<|file_name|>vm.plugins.scratch.browser.js<|end_file_name|><|fim▁begin|>"use strict"; /* * Copyright (c) 2013-2019 Bert Freudenberg * * 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. */ Object.extend(Squeak.Primitives.prototype, 'ScratchPluginAdditions', { // methods not handled by generated ScratchPlugin scratch_primitiveOpenURL: function(argCount) {<|fim▁hole|> var path = Squeak.splitFilePath(url), template = Squeak.Settings["squeak-template:" + path.dirname]; if (template) url = JSON.parse(template).url + "/" + path.basename; } window.open(url, "_blank"); // likely blocked as pop-up, but what can we do? return this.popNIfOK(argCount); }, scratch_primitiveGetFolderPath: function(argCount) { var index = this.stackInteger(0); if (!this.success) return false; var path; switch (index) { case 1: path = '/'; break; // home dir // case 2: path = '/desktop'; break; // desktop // case 3: path = '/documents'; break; // documents // case 4: path = '/pictures'; break; // my pictures // case 5: path = '/music'; break; // my music } if (!path) return false; this.vm.popNandPush(argCount + 1, this.makeStString(this.filenameToSqueak(path))); return true; }, });<|fim▁end|>
var url = this.stackNonInteger(0).bytesAsString(); if (url == "") return false; if (/^\/SqueakJS\//.test(url)) { url = url.slice(10); // remove file root
<|file_name|>ModelDefinition.java<|end_file_name|><|fim▁begin|>/* * Copyright 2017 StreamSets 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.streamsets.datacollector.config; import com.streamsets.pipeline.api.impl.Utils; import java.util.HashMap; import java.util.List; import java.util.Map; public class ModelDefinition { private final ModelType modelType; private final String valuesProviderClass; private final List<ConfigDefinition> configDefinitions; private final Map<String, ConfigDefinition> configDefinitionsAsMap; private List<String> values; private List<String> labels; private final Class listBeanClass; public static ModelDefinition localizedValueChooser(ModelDefinition model, List<String> values, List<String> labels) { return new ModelDefinition(model.getModelType(), model.getValuesProviderClass(), values, labels, model.getListBeanClass(), model.getConfigDefinitions()); } public static ModelDefinition localizedComplexField(ModelDefinition model, List<ConfigDefinition> configDefs) { return new ModelDefinition(model.getModelType(), model.getValuesProviderClass(), model.getValues(), model.getLabels(), model.getListBeanClass(), configDefs); } public ModelDefinition(ModelType modelType, String valuesProviderClass, List<String> values, List<String> labels, Class listBeanClass, List<ConfigDefinition> configDefinitions) { this.modelType = modelType; this.valuesProviderClass = valuesProviderClass; this.configDefinitions = configDefinitions; configDefinitionsAsMap = new HashMap<>(); if (configDefinitions != null) { for (ConfigDefinition def : configDefinitions) { configDefinitionsAsMap.put(def.getName(), def); } } this.values = values; this.labels = labels; this.listBeanClass = listBeanClass; } public ModelType getModelType() { return modelType; } public List<String> getValues() { return values; } public List<String> getLabels() { return labels; } public String getValuesProviderClass() { return valuesProviderClass; } public void setValues(List<String> values) { this.values = values; } public void setLabels(List<String> labels) { this.labels = labels; } public Class getListBeanClass() { return listBeanClass; } public List<ConfigDefinition> getConfigDefinitions() { return configDefinitions; } public Map<String, ConfigDefinition> getConfigDefinitionsAsMap() { return configDefinitionsAsMap; }<|fim▁hole|> @Override public String toString() { return Utils.format("ModelDefinition[type='{}' valuesProviderClass='{}' values='{}']", getModelType(), getValues(), getValuesProviderClass()); } }<|fim▁end|>
<|file_name|>utils.py<|end_file_name|><|fim▁begin|># Copyright 2015 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools import os from perfkitbenchmarker import flags from perfkitbenchmarker import vm_util from perfkitbenchmarker.vm_util import POLL_INTERVAL FLAGS = flags.FLAGS flags.DEFINE_string('openstack_auth_url', os.environ.get('OS_AUTH_URL', 'http://localhost:5000'), ('Url for Keystone authentication service, defaults to ' '$OS_AUTH_URL. Required for discovery of other OpenStack ' 'service URLs.')) flags.DEFINE_string('openstack_username', os.getenv('OS_USERNAME', 'admin'), 'OpenStack login username, defaults to $OS_USERNAME.') flags.DEFINE_string('openstack_tenant', os.getenv('OS_TENANT_NAME', 'admin'), 'OpenStack tenant name, defaults to $OS_TENANT_NAME.') flags.DEFINE_string('openstack_password_file', os.getenv('OPENSTACK_PASSWORD_FILE', '~/.config/openstack-password.txt'), 'Path to file containing the openstack password, ' 'defaults to $OPENSTACK_PASSWORD_FILE. Alternatively, ' 'setting the password itself in $OS_PASSWORD is also ' 'supported.') flags.DEFINE_string('openstack_nova_endpoint_type', os.getenv('NOVA_ENDPOINT_TYPE', 'publicURL'), 'OpenStack Nova endpoint type, ' 'defaults to $NOVA_ENDPOINT_TYPE.') class KeystoneAuth(object): """ Usage example: auth = KeystoneAuth(auth_url, auth_tenant, auth_user, auth_password) token = auth.get_token() tenant_id = auth.get_tenant_id() token and tenant_id are required to use all OpenStack python clients """ def __init__(self, url, tenant, user, password): self.__url = url self.__tenant = tenant self.__user = user self.__password = password self.__connection = None self.__session = None def GetConnection(self):<|fim▁hole|> def __authenticate(self): import keystoneclient.v2_0.client as ksclient self.__connection = ksclient.Client( auth_url=self.__url, username=self.__user, password=self.__password, tenant=self.__tenant) self.__connection.authenticate() def get_token(self): return self.GetConnection().get_token(self.__session) def get_tenant_id(self): raw_token = self.GetConnection().get_raw_token_from_identity_service( auth_url=self.__url, username=self.__user, password=self.__password, tenant_name=self.__tenant ) return raw_token['token']['tenant']['id'] class NovaClient(object): def __getattribute__(self, item): try: return super(NovaClient, self).__getattribute__(item) except AttributeError: return self.__client.__getattribute__(item) def GetPassword(self): # For compatibility with Nova CLI, use 'OS'-prefixed environment value # if present. Also support reading the password from a file. error_msg = ('No OpenStack password specified. ' 'Either set the environment variable OS_PASSWORD to the ' 'admin password, or provide the name of a file ' 'containing the password using the OPENSTACK_PASSWORD_FILE ' 'environment variable or --openstack_password_file flag.') password = os.getenv('OS_PASSWORD') if password is not None: return password try: with open(os.path.expanduser(FLAGS.openstack_password_file)) as pwfile: password = pwfile.readline().rstrip() return password except IOError as e: raise Exception(error_msg + ' ' + str(e)) raise Exception(error_msg) def __init__(self): from novaclient import client as noclient self.url = FLAGS.openstack_auth_url self.user = FLAGS.openstack_username self.tenant = FLAGS.openstack_tenant self.endpoint_type = FLAGS.openstack_nova_endpoint_type self.password = self.GetPassword() self.__auth = KeystoneAuth(self.url, self.tenant, self.user, self.password) self.__client = noclient.Client('2', auth_url=self.url, username=self.user, auth_token=self.__auth.get_token(), tenant_id=self.__auth.get_tenant_id(), endpoint_type=self.endpoint_type, ) def reconnect(self): from novaclient import client as noclient self.__auth = KeystoneAuth(self.url, self.tenant, self.user, self.password) self.__client = noclient.Client('2', auth_url=self.url, username=self.user, auth_token=self.__auth.get_token(), tenant_id=self.__auth.get_tenant_id(), endpoint_type=self.endpoint_type, ) class AuthException(Exception): """Wrapper for NovaClient auth exceptions.""" pass def retry_authorization(max_retries=1, poll_interval=POLL_INTERVAL): def decored(function): @vm_util.Retry(max_retries=max_retries, poll_interval=poll_interval, retryable_exceptions=AuthException, log_errors=False) @functools.wraps(function) def decor(*args, **kwargs): from novaclient.exceptions import Unauthorized try: return function(*args, **kwargs) except Unauthorized as e: NovaClient.instance.reconnect() raise AuthException(str(e)) return decor return decored<|fim▁end|>
if self.__connection is None: self.__authenticate() return self.__connection
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from flask.ext.sqlalchemy import SQLAlchemy from . import db class Role(db.Model): __tablename__='roles' id=db.Column(db.Integer,primary_key=True) name=db.Column(db.String(64),unique=True) users=db.relationship('User',backref='role') def __repr__(self): return '<Role>{}</Role>'.format(self.name) class User(db.Model): __tablename__='users' id=db.Column(db.Integer,primary_key=True) role_id=db.Column(db.Integer,db.ForeignKey('roles.id')) username=db.Column(db.String(64),unique=True,index=True)<|fim▁hole|><|fim▁end|>
def __repr__(self): return '<Username>{}</Username>'.format(self.username)
<|file_name|>qa_mosaics_T1w.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import os from glob import glob from vlpp.utils import save_json from vlpp.qamosaic import Mosaic def main(): # Usefull directories os.mkdir("data") # Informations participant_id = "${sub.sub}" # Images Path try: anat = glob("${sub.anat}")[0] except: anat = None try: brainmask = glob("${sub.brainmask}")[0] except: brainmask = None try: atlas = glob("${sub.atlas}")[0] except: atlas = None try: pet = glob("${sub.pet}")[0] except: pet = None try: cerebellumCortex = glob("${sub.cerebellumCortex}")[0] except: cerebellumCortex = None try: atlasBaker = glob("${sub.atlasBaker}")[0] except: atlasBaker = None try: suvrBaker = glob("${sub.suvrBaker}")[0] except: suvrBaker = None # Anat tag = "anat" m = Mosaic(anat, mask=brainmask, cmap="gray") target = "data/{0}_{1}_mosaic.jpg".format(participant_id, tag) m.save(target) # Atlas tag = "atlas" m = Mosaic(anat, mask=brainmask, overlay=atlas, cmap="gray") target = "data/{0}_{1}_mosaic.jpg".format(participant_id, tag) m.save(target) # Pet tag = "pet" m = Mosaic(pet, mask=brainmask, contour=cerebellumCortex) target = "data/{0}_{1}_mosaic.jpg".format(participant_id, tag) m.save(target) # SUVR Baker tag = "suvrbaker" m = Mosaic(suvrBaker, mask=brainmask) target = "data/{0}_{1}_mosaic.jpg".format(participant_id, tag) m.save(target) # Atlas Baker tag = "atlasbaker" m = Mosaic(anat, mask=brainmask, overlay=atlasBaker, cmap="gray") target = "data/{0}_{1}_mosaic.jpg".format(participant_id, tag) m.save(target) # Pet Atlas tag = "petatlas"<|fim▁hole|> m = Mosaic(pet, mask=brainmask, overlay=atlas, cmap="gray") target = "data/{0}_{1}_mosaic.jpg".format(participant_id, tag) participant_info = m.save(target) participant_info["participant_id"] = participant_id jsonPath = "data/{}_registration_T1w.json".format(participant_id) save_json(jsonPath, participant_info) if __name__ == "__main__": main()<|fim▁end|>
<|file_name|>ExtendedErrorBar.py<|end_file_name|><|fim▁begin|>#======================================================================= # Author: Donovan Parks # # Extended error bar plot. # # Copyright 2011 Donovan Parks # # This file is part of STAMP. # # STAMP is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # STAMP 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 STAMP. If not, see <http://www.gnu.org/licenses/>. #======================================================================= from PyQt4 import QtGui, QtCore import sys import math import numpy as np from mpl_toolkits.axes_grid import make_axes_locatable, Size from stamp.plugins.groups.AbstractGroupPlotPlugin import AbstractGroupPlotPlugin, TestWindow, ConfigureDialog from stamp.plugins.groups.plots.configGUI.extendedErrorBarUI import Ui_ExtendedErrorBarDialog from stamp.metagenomics import TableHelper from matplotlib.patches import Rectangle class ExtendedErrorBar(AbstractGroupPlotPlugin): ''' Extended error bar plot. ''' def __init__(self, preferences, parent=None): AbstractGroupPlotPlugin.__init__(self, preferences, parent) self.name = 'Extended error bar' self.type = 'Statistical' self.bSupportsHighlight = True self.bPlotFeaturesIndividually = False self.settings = preferences['Settings'] self.figWidth = self.settings.value('group: ' + self.name + '/width', 7.0).toDouble()[0] self.figHeightPerRow = self.settings.value('group: ' + self.name + '/row height', 0.2).toDouble()[0] self.sortingField = self.settings.value('group: ' + self.name + '/field', 'p-values').toString() self.bShowBarPlot = self.settings.value('group: ' + self.name + '/sequences subplot', True).toBool() self.bShowPValueLabels = self.settings.value('group: ' + self.name + '/p-value labels', True).toBool() self.bShowCorrectedPvalues = self.settings.value('group: ' + self.name + '/show corrected p-values', True).toBool() self.bCustomLimits = self.settings.value('group: ' + self.name + '/use custom limits', False).toBool() self.minX = self.settings.value('group: ' + self.name + '/minimum', 0.0).toDouble()[0] self.maxX = self.settings.value('group: ' + self.name + '/maximum', 1.0).toDouble()[0] self.markerSize = self.settings.value('group: ' + self.name + '/marker size', 30).toInt()[0] self.bShowStdDev = self.settings.value('group: ' + self.name + '/show std. dev.', False).toBool() self.endCapSize = self.settings.value('group: ' + self.name + '/end cap size', 0.0).toInt()[0] self.legendPos = self.settings.value('group: ' + self.name + '/legend position', -1).toInt()[0] def mirrorProperties(self, plotToCopy): self.name = plotToCopy.name self.figWidth = plotToCopy.figWidth self.figHeightPerRow = plotToCopy.figHeightPerRow self.sortingField = plotToCopy.sortingField self.bShowBarPlot = plotToCopy.bShowBarPlot self.bShowPValueLabels = plotToCopy.bShowPValueLabels self.bShowCorrectedPvalues = plotToCopy.bShowCorrectedPvalues self.bCustomLimits = plotToCopy.bCustomLimits self.minX = plotToCopy.minX self.maxX = plotToCopy.maxX self.markerSize = plotToCopy.markerSize self.bShowStdDev = plotToCopy.bShowStdDev self.endCapSize = plotToCopy.endCapSize self.legendPos = plotToCopy.legendPos def plot(self, profile, statsResults): # *** Check if there is sufficient data to generate the plot if len(statsResults.activeData) <= 0: self.emptyAxis() return features = statsResults.getColumn('Features') if len(features) > 200: QtGui.QApplication.instance().setOverrideCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) reply = QtGui.QMessageBox.question(self, 'Continue?', 'Profile contains ' + str(len(features)) + ' features. ' + 'It may take several seconds to generate this plot. We recommend filtering your profile first. ' + 'Do you wish to continue?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) QtGui.QApplication.instance().restoreOverrideCursor() if reply == QtGui.QMessageBox.No: self.emptyAxis() return # *** Colour of plot elements axesColour = str(self.preferences['Axes colour'].name()) group1Colour = str(self.preferences['Group colours'][profile.groupName1].name()) group2Colour = str(self.preferences['Group colours'][profile.groupName2].name()) # *** Colour of plot elements highlightColor = (0.9, 0.9, 0.9) # *** Sort data if self.sortingField == 'p-values': statsResults.activeData = TableHelper.SortTable(statsResults.activeData,\ [statsResults.dataHeadings['pValues']], False) elif self.sortingField == 'Effect sizes': statsResults.activeData = TableHelper.SortTable(statsResults.activeData,\ [statsResults.dataHeadings['EffectSize']], True, True, False) elif self.sortingField == 'Feature labels': statsResults.activeData = TableHelper.SortTableStrCol(statsResults.activeData,\ statsResults.dataHeadings['Features'], False) features = statsResults.getColumn('Features') # get sorted feature labels # *** Create lists for each quantity of interest if statsResults.multCompCorrection.method == 'False discovery rate': pValueTitle = 'q-value' else: pValueTitle = 'p-value' if self.bShowCorrectedPvalues: pValueLabels = statsResults.getColumnAsStr('pValuesCorrected') if statsResults.multCompCorrection.method != 'No correction': pValueTitle += ' (corrected)' else: pValueLabels = statsResults.getColumnAsStr('pValues') effectSizes = statsResults.getColumn('EffectSize') lowerCIs = statsResults.getColumn('LowerCI') upperCIs = statsResults.getColumn('UpperCI') ciTitle = ('%.3g' % (statsResults.oneMinusAlpha()*100)) + '% confidence intervals' # *** Truncate feature labels highlightedFeatures = list(self.preferences['Highlighted group features']) if self.preferences['Truncate feature names']: length = self.preferences['Length of truncated feature names'] for i in xrange(0, len(features)): if len(features[i]) > length+3: features[i] = features[i][0:length] + '...' for i in xrange(0, len(highlightedFeatures)): if len(highlightedFeatures[i]) > length+3: highlightedFeatures[i] = highlightedFeatures[i][0:length] + '...' # *** Check that there is at least one significant feature if len(features) <= 0: self.emptyAxis('No significant features') return # *** Adjust effect size for axis scale dominateInSample2 = [] percentage1 = [] percentage2 = [] for i in xrange(0, len(effectSizes)): if statsResults.bConfIntervRatio: if effectSizes[i] < 1: # mirror CI across y-axis effectSizes[i] = 1.0 / effectSizes[i] lowerCI = effectSizes[i] - (1.0 / upperCIs[i]) upperCI = (1.0 / lowerCIs[i]) - effectSizes[i] lowerCIs[i] = lowerCI upperCIs[i] = upperCI dominateInSample2.append(i) else: lowerCIs[i] = effectSizes[i] - lowerCIs[i] upperCIs[i] = upperCIs[i] - effectSizes[i] else: lowerCIs[i] = effectSizes[i] - lowerCIs[i] upperCIs[i] = upperCIs[i] - effectSizes[i] if effectSizes[i] < 0.0: dominateInSample2.append(i) # *** Set figure size if self.legendPos == 3 or self.legendPos == 4 or self.legendPos == 8: # bottom legend heightBottomLabels = 0.56 # inches else: heightBottomLabels = 0.4 # inches heightTopLabels = 0.25 plotHeight = self.figHeightPerRow*len(features) self.imageWidth = self.figWidth self.imageHeight = plotHeight + heightBottomLabels + heightTopLabels if self.imageWidth > 256 or self.imageHeight > 256: QtGui.QApplication.instance().setOverrideCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.emptyAxis() reply = QtGui.QMessageBox.question(self, 'Excessively large plot', 'The resulting plot is too large to display.') QtGui.QApplication.instance().restoreOverrideCursor() return self.fig.set_size_inches(self.imageWidth, self.imageHeight) # *** Determine width of y-axis labels yLabelBounds = self.yLabelExtents(features, 8) # *** Size plots which comprise the extended errorbar plot self.fig.clear() spacingBetweenPlots = 0.25 # inches widthNumSeqPlot = 1.25 # inches if self.bShowBarPlot == False: widthNumSeqPlot = 0.0 spacingBetweenPlots = 0.0 widthPvalueLabels = 0.75 # inches if self.bShowPValueLabels == False: widthPvalueLabels = 0.1 yPlotOffsetFigSpace = heightBottomLabels / self.imageHeight heightPlotFigSpace = plotHeight / self.imageHeight xPlotOffsetFigSpace = yLabelBounds.width + 0.1 / self.imageWidth pValueLabelWidthFigSpace = widthPvalueLabels / self.imageWidth widthPlotFigSpace = 1.0 - pValueLabelWidthFigSpace - xPlotOffsetFigSpace widthErrorBarPlot = widthPlotFigSpace*self.imageWidth - widthNumSeqPlot - spacingBetweenPlots axInitAxis = self.fig.add_axes([xPlotOffsetFigSpace,yPlotOffsetFigSpace,widthPlotFigSpace,heightPlotFigSpace]) divider = make_axes_locatable(axInitAxis) divider.get_vertical()[0] = Size.Fixed(len(features)*self.figHeightPerRow) if self.bShowBarPlot == True: divider.get_horizontal()[0] = Size.Fixed(widthNumSeqPlot) axErrorbar = divider.new_horizontal(widthErrorBarPlot, pad=spacingBetweenPlots, sharey=axInitAxis) self.fig.add_axes(axErrorbar) else: divider.get_horizontal()[0] = Size.Fixed(widthErrorBarPlot) axErrorbar = axInitAxis # *** Plot of sequences for each subsystem if self.bShowBarPlot == True: axNumSeq = axInitAxis meanRelFreqSeqs1 = statsResults.getColumn('MeanRelFreq1') meanRelFreqSeqs2 = statsResults.getColumn('MeanRelFreq2') if self.bShowStdDev: stdDev1 = statsResults.getColumn('StdDevRelFreq1') stdDev2 = statsResults.getColumn('StdDevRelFreq2') endCapSize = self.endCapSize else: stdDev1 = [0] * len(meanRelFreqSeqs1) stdDev2 = [0] * len(meanRelFreqSeqs2) endCapSize = 0 axNumSeq.barh(np.arange(len(features))+0.0, meanRelFreqSeqs1, height = 0.3, xerr=stdDev1, color=group1Colour, ecolor='black', capsize=endCapSize) axNumSeq.barh(np.arange(len(features))-0.3, meanRelFreqSeqs2, height = 0.3, xerr=stdDev2, color=group2Colour, ecolor='black', capsize=endCapSize) for value in np.arange(-0.5, len(features)-1, 2): axNumSeq.axhspan(value, value+1, facecolor=highlightColor,edgecolor='none',zorder=-1) axNumSeq.set_xlabel('Mean proportion (%)') maxPercentage = max(max(meanRelFreqSeqs1), max(meanRelFreqSeqs2)) axNumSeq.set_xticks([0, maxPercentage]) axNumSeq.set_xlim([0, maxPercentage*1.05]) maxPercentageStr = '%.1f' % maxPercentage axNumSeq.set_xticklabels(['0.0', maxPercentageStr]) axNumSeq.set_yticks(np.arange(len(features))) axNumSeq.set_yticklabels(features) axNumSeq.set_ylim([-1, len(features)]) for label in axNumSeq.get_yticklabels(): if label.get_text() in highlightedFeatures: label.set_color('red') for a in axNumSeq.yaxis.majorTicks: a.tick1On=False a.tick2On=False for a in axNumSeq.xaxis.majorTicks: a.tick1On=True a.tick2On=False for line in axNumSeq.yaxis.get_ticklines(): line.set_color(axesColour) for line in axNumSeq.xaxis.get_ticklines(): line.set_color(axesColour) for loc, spine in axNumSeq.spines.iteritems(): if loc in ['left', 'right','top']: spine.set_color('none') else: spine.set_color(axesColour) # *** Plot confidence intervals for each subsystem lastAxes = axErrorbar markerSize = math.sqrt(float(self.markerSize)) axErrorbar.errorbar(effectSizes, np.arange(len(features)), xerr=[lowerCIs,upperCIs], fmt='o', ms=markerSize, mfc=group1Colour, mec='black', ecolor='black', zorder=10) effectSizesSample2 = [effectSizes[value] for value in dominateInSample2] axErrorbar.plot(effectSizesSample2, dominateInSample2, ls='', marker='o', ms=markerSize, mfc=group2Colour, mec='black', zorder=100) if statsResults.bConfIntervRatio: axErrorbar.vlines(1, -1, len(features), linestyle='dashed', color=axesColour) else: axErrorbar.vlines(0, -1, len(features), linestyle='dashed', color=axesColour) for value in np.arange(-0.5, len(features)-1, 2): axErrorbar.axhspan(value, value+1, facecolor=highlightColor,edgecolor='none',zorder=1) axErrorbar.set_title(ciTitle) axErrorbar.set_xlabel('Difference in mean proportions (%)') if self.bCustomLimits: axErrorbar.set_xlim([self.minX, self.maxX]) else: self.minX, self.maxX = axErrorbar.get_xlim() if self.bShowBarPlot == False: axErrorbar.set_yticks(np.arange(len(features))) axErrorbar.set_yticklabels(features)<|fim▁hole|> if label.get_text() in self.preferences['Highlighted group features']: label.set_color('red') else: for label in axErrorbar.get_yticklabels(): label.set_visible(False) for a in axErrorbar.yaxis.majorTicks: a.set_visible(False) for a in axErrorbar.xaxis.majorTicks: a.tick1On=True a.tick2On=False for a in axErrorbar.yaxis.majorTicks: a.tick1On=False a.tick2On=False for line in axErrorbar.yaxis.get_ticklines(): line.set_visible(False) for line in axErrorbar.xaxis.get_ticklines(): line.set_color(axesColour) for loc, spine in axErrorbar.spines.iteritems(): if loc in ['left','right','top']: spine.set_color('none') else: spine.set_color(axesColour) # *** Show p-values on right of last plot if self.bShowPValueLabels == True: axRight = lastAxes.twinx() axRight.set_yticks(np.arange(len(pValueLabels))) axRight.set_yticklabels(pValueLabels) axRight.set_ylim([-1, len(pValueLabels)]) axRight.set_ylabel(pValueTitle) for a in axRight.yaxis.majorTicks: a.tick1On=False a.tick2On=False for loc, spine in axRight.spines.iteritems(): spine.set_color('none') # *** Legend if self.legendPos != -1: legend1 = Rectangle((0, 0), 1, 1, fc=group1Colour) legend2 = Rectangle((0, 0), 1, 1, fc=group2Colour) legend = self.fig.legend([legend1, legend2], (profile.groupName1, profile.groupName2), loc=self.legendPos, ncol=2) legend.get_frame().set_linewidth(0) self.updateGeometry() self.draw() def configure(self, profile, statsResults): self.statsResults = statsResults self.configDlg = ConfigureDialog(Ui_ExtendedErrorBarDialog) # set enabled state of controls self.configDlg.ui.chkShowStdDev.setChecked(self.bShowBarPlot) self.configDlg.ui.spinEndCapSize.setValue(self.bShowBarPlot) self.configDlg.ui.spinMinimumX.setEnabled(self.bCustomLimits) self.configDlg.ui.spinMaximumX.setEnabled(self.bCustomLimits) # set current value of controls self.configDlg.ui.cboSortingField.setCurrentIndex(self.configDlg.ui.cboSortingField.findText(self.sortingField)) self.configDlg.ui.spinFigWidth.setValue(self.figWidth) self.configDlg.ui.spinFigRowHeight.setValue(self.figHeightPerRow) self.configDlg.ui.chkShowBarPlot.setChecked(self.bShowBarPlot) self.configDlg.ui.chkPValueLabels.setChecked(self.bShowPValueLabels) self.configDlg.ui.chkCorrectedPvalues.setChecked(self.bShowCorrectedPvalues) self.configDlg.ui.chkCustomLimits.setChecked(self.bCustomLimits) self.configDlg.ui.spinMinimumX.setValue(self.minX) self.configDlg.ui.spinMaximumX.setValue(self.maxX) self.configDlg.ui.spinMarkerSize.setValue(self.markerSize) self.configDlg.ui.chkShowStdDev.setChecked(self.bShowStdDev) self.configDlg.ui.spinEndCapSize.setValue(self.endCapSize) if self.legendPos == 2: self.configDlg.ui.radioLegendPosUpperLeft.setChecked(True) elif self.legendPos == 3: self.configDlg.ui.radioLegendPosLowerLeft.setChecked(True) elif self.legendPos == 4: self.configDlg.ui.radioLegendPosLowerRight.setChecked(True) elif self.legendPos == 8: self.configDlg.ui.radioLegendPosLowerCentre.setChecked(True) else: self.configDlg.ui.radioLegendPosNone.setChecked(True) if self.configDlg.exec_() == QtGui.QDialog.Accepted: QtGui.QApplication.instance().setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) self.sortingField = str(self.configDlg.ui.cboSortingField.currentText()) self.figWidth = self.configDlg.ui.spinFigWidth.value() self.figHeightPerRow = self.configDlg.ui.spinFigRowHeight.value() self.bShowBarPlot = self.configDlg.ui.chkShowBarPlot.isChecked() self.bShowPValueLabels = self.configDlg.ui.chkPValueLabels.isChecked() self.bShowCorrectedPvalues = self.configDlg.ui.chkCorrectedPvalues.isChecked() self.bCustomLimits = self.configDlg.ui.chkCustomLimits.isChecked() self.minX = self.configDlg.ui.spinMinimumX.value() self.maxX = self.configDlg.ui.spinMaximumX.value() self.markerSize = self.configDlg.ui.spinMarkerSize.value() self.bShowStdDev = self.configDlg.ui.chkShowStdDev.isChecked() self.endCapSize = self.configDlg.ui.spinEndCapSize.value() # legend position if self.configDlg.ui.radioLegendPosUpperLeft.isChecked() == True: self.legendPos = 2 elif self.configDlg.ui.radioLegendPosLowerLeft.isChecked() == True: self.legendPos = 3 elif self.configDlg.ui.radioLegendPosLowerCentre.isChecked() == True: self.legendPos = 8 elif self.configDlg.ui.radioLegendPosLowerRight.isChecked() == True: self.legendPos = 4 else: self.legendPos = -1 self.settings.setValue('group: ' + self.name + '/width', self.figWidth) self.settings.setValue('group: ' + self.name + '/row height', self.figHeightPerRow) self.settings.setValue('group: ' + self.name + '/field', self.sortingField) self.settings.setValue('group: ' + self.name + '/sequences subplot', self.bShowBarPlot) self.settings.setValue('group: ' + self.name + '/p-value labels', self.bShowPValueLabels) self.settings.setValue('group: ' + self.name + '/show corrected p-values', self.bShowCorrectedPvalues) self.settings.setValue('group: ' + self.name + '/use custom limits', self.bCustomLimits) self.settings.setValue('group: ' + self.name + '/minimum', self.minX) self.settings.setValue('group: ' + self.name + '/maximum', self.maxX) self.settings.setValue('group: ' + self.name + '/marker size', self.markerSize) self.settings.setValue('group: ' + self.name + '/show std. dev.', self.bShowStdDev) self.settings.setValue('group: ' + self.name + '/end cap size', self.endCapSize) self.settings.setValue('group: ' + self.name + '/legend position', self.legendPos) self.plot(profile, statsResults) QtGui.QApplication.instance().restoreOverrideCursor() if __name__ == "__main__": app = QtGui.QApplication(sys.argv) testWindow = TestWindow(ExtendedErrorBar) testWindow.show() sys.exit(app.exec_())<|fim▁end|>
axErrorbar.set_ylim([-1, len(features)]) for label in axErrorbar.get_yticklabels():
<|file_name|>reports.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit } from '@angular/core'; import { DataService } from '../service/data.service'; import { ReportModel } from '../model/reportmodel'; import { Utils } from '../util/utils' import { RouterModule, Routes, Router, ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-reports', templateUrl: './reports.component.html', styleUrls: ['./reports.component.css'], providers: [DataService] }) export class ReportsComponent implements OnInit { constructor(private dataService: DataService, private router: Router, private route: ActivatedRoute) { } reports: ReportModel[]; ngOnInit() { this.dataService.getReports() .subscribe(res => { this.reports = res as Array<ReportModel>; }); } navigateToNewReport() { this.router.navigate(['../new-report'], { relativeTo: this.route }); } private openReport(report : ReportModel) { if(Utils.checkNullEmpty(report.sub_type)) { this.router.navigate(['../report', report.type], { relativeTo: this.route });<|fim▁hole|> } else { this.router.navigate(['../report', report.type, report.sub_type], { relativeTo: this.route }); } } }<|fim▁end|>
<|file_name|>window.rs<|end_file_name|><|fim▁begin|>use std::{collections::VecDeque, rc::Rc}; use crate::{ api::prelude::*, proc_macros::*, shell::prelude::WindowRequest, themes::theme_orbtk::*, }; // --- KEYS -- pub static STYLE_WINDOW: &str = "window"; // --- KEYS -- // internal type to handle dirty widgets. type DirtyWidgets = Vec<Entity>; #[derive(Clone)] enum Action { WindowEvent(WindowEvent), FocusEvent(FocusEvent), } // The `WindowState` handles the window events. #[derive(Default, AsAny)] struct WindowState { actions: VecDeque<Action>, background: Brush, title: String, } impl WindowState { fn push_action(&mut self, action: Action) { self.actions.push_front(action); } fn resize(&self, width: f64, height: f64, ctx: &mut Context) { Window::bounds_mut(&mut ctx.window()).set_size(width, height); Window::constraint_mut(&mut ctx.window()).set_size(width, height); } fn active_changed(&self, active: bool, ctx: &mut Context) { Window::active_set(&mut ctx.widget(), active); // if !active { // // remove focus if the window is not active // if let Some(focused_widget) = ctx.window().get::<Global>("global").focused_widget { // ctx.window().get_mut::<Global>("global").focused_widget = None; // if ctx.get_widget(focused_widget).has::<bool>("focused") { // ctx.get_widget(focused_widget).set("focused", false); // ctx.get_widget(focused_widget).update_theme_by_state(false); // } // } // } } fn request_focus(&self, entity: Entity, ctx: &mut Context) { let mut focus_state: FocusState = Window::focus_state_clone(&ctx.widget()); focus_state.request_focus(entity, ctx); Window::focus_state_set(&mut ctx.widget(), focus_state); } fn remove_focus(&self, entity: Entity, ctx: &mut Context) { let mut focus_state: FocusState = Window::focus_state_clone(&ctx.widget()); focus_state.remove_focus(entity, ctx); Window::focus_state_set(&mut ctx.widget(), focus_state); } fn set_background(&mut self, ctx: &mut Context) { let background: Brush = ctx.widget().clone("background"); if let Brush::SolidColor(color) = background { ctx.render_context_2_d().set_background(color); }; self.background = background; } } impl State for WindowState { fn init(&mut self, _: &mut Registry, ctx: &mut Context) { self.set_background(ctx); self.title = ctx.widget().clone("title"); } fn update(&mut self, _: &mut Registry, ctx: &mut Context) { if self.background != *Window::background_ref(&ctx.widget()) { self.set_background(ctx); } let window = ctx.widget(); if !self.title.eq(Window::title_ref(&window)) { self.title = Window::title_clone(&window); ctx.send_window_request(WindowRequest::ChangeTitle(self.title.clone())); } if let Some(action) = self.actions.pop_front() { match action { Action::WindowEvent(window_event) => match window_event { WindowEvent::Resize { width, height } => {<|fim▁hole|> WindowEvent::ActiveChanged(active) => { self.active_changed(active, ctx); } _ => {} }, Action::FocusEvent(focus_event) => match focus_event { FocusEvent::RequestFocus(entity) => { self.request_focus(entity, ctx); } FocusEvent::RemoveFocus(entity) => { self.remove_focus(entity, ctx); } }, } } } } widget!( /// The `Window` widget provides access to the properties of an application window. /// It also contains global properties like keyboard modifier and focused widget. /// /// **style:** `window` Window<WindowState>: ActivateHandler { /// Sets or shares the background property. background: Brush, /// Sets or shares the title property. title: String, /// Sets or shares the resizable property. resizable: bool, /// Sets or shares the property if this window should always be on top. always_on_top: bool, /// Sets or shares the flag if the window is borderless. borderless: bool, /// Sets or shares a value that describes if the current window is active. active: bool, /// Access the current keyboard state e.g. to check modifiers. keyboard_state: KeyboardState, /// Access the current window theme. theme: Theme, /// Access the current focus state. focus_state: FocusState, /// Internal property to handle dirty widgets. dirty_widgets: DirtyWidgets } ); impl Window { fn on_window_event<H: Fn(&mut StatesContext, WindowEvent) -> bool + 'static>( self, handler: H, ) -> Self { self.insert_handler(WindowEventHandler { handler: Rc::new(handler), }) } fn on_focus_event<H: Fn(&mut StatesContext, FocusEvent) -> bool + 'static>( self, handler: H, ) -> Self { self.insert_handler(FocusEventHandler { handler: Rc::new(handler), }) } /// Sets or shares the resizable property. #[inline(always)] #[deprecated = "Use resizable instead"] pub fn resizeable<P: IntoPropertySource<bool>>(self, resizeable: P) -> Self { self.resizable(resizeable) } /// Clones the property value. Panics if it is the wrong widget type. #[inline(always)] #[deprecated = "Use resizable_clone instead"] pub fn resizeable_clone(widget: &WidgetContainer<'_>) -> bool { Window::resizable_clone(widget) } /// Sets the property value. Panics if it is the wrong widget type. #[inline(always)] #[deprecated = "Use resizable_set instead"] pub fn resizeable_set(widget: &mut WidgetContainer<'_>, value: impl Into<bool>) { Window::resizable_set(widget, value) } /// Gets a mutable reference of the property value. Panics if it is the wrong widget type. #[inline(always)] #[deprecated = "Use resizable_mut instead"] pub fn resizeable_mut<'a>(widget: &'a mut WidgetContainer<'a>) -> &'a mut bool { Window::resizable_mut(widget) } /// Gets a reference of the property value. Panics if it is the wrong widget type. #[inline(always)] #[deprecated = "Use resizable_ref instead"] pub fn resizeable_ref<'a>(widget: &'a WidgetContainer<'a>) -> &'a bool { Window::resizable_ref(widget) } } impl Template for Window { fn template(self, id: Entity, _: &mut BuildContext) -> Self { self.name("Window") .background(colors::BRIGHT_GRAY_COLOR) .size(100.0, 100.0) .style(STYLE_WINDOW) .title("Window") .resizable(false) .always_on_top(false) .on_window_event(move |ctx, event| { ctx.get_mut::<WindowState>(id) .push_action(Action::WindowEvent(event)); true }) .on_focus_event(move |ctx, event| { ctx.get_mut::<WindowState>(id) .push_action(Action::FocusEvent(event)); true }) } fn render_object(&self) -> Box<dyn RenderObject> { RectangleRenderObject.into() } fn layout(&self) -> Box<dyn Layout> { GridLayout::new().into() } }<|fim▁end|>
self.resize(width, height, ctx); }
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .. import Provider as CompanyProvider class Provider(CompanyProvider): formats = ( "{{last_name}} {{company_suffix}}", "{{last_name}} {{last_name}} {{company_suffix}}", "{{large_company}}", ) large_companies = ( "AZAL", "Azergold", "SOCAR", "Socar Polymer", "Global Export Fruits", "Baku Steel Company", "Azersun", "Sun Food", "Azərbaycan Şəkər İstehsalat Birliyi", "Azərsu", "Xəzər Dəniz Gəmiçiliyi", "Azərenerji", "Bakıelektrikşəbəkə", "Azəralüminium", "Bravo", "Azərpambıq Aqrar Sənaye Kompleksi", "CTS-Agro", "Azərtütün Aqrar Sənaye Kompleksi", "Azəripək",<|fim▁hole|> "Azpetrol", "Azərtexnolayn", "Bakı Gəmiqayırma Zavodu", "Gəncə Tekstil Fabriki", "Mətanət A", "İrşad Electronics", ) company_suffixes = ( "ASC", "QSC", "MMC", ) def large_company(self): """ :example: 'SOCAR' """ return self.random_element(self.large_companies)<|fim▁end|>
"Azfruittrade", "AF Holding", "Azinko Holding", "Gilan Holding",
<|file_name|>create_pretraining_data.py<|end_file_name|><|fim▁begin|># Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Create masked LM/next sentence masked_lm TF examples for BERT.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import random from absl import app from absl import flags from absl import logging import tensorflow as tf from official.nlp.bert import tokenization FLAGS = flags.FLAGS flags.DEFINE_string("input_file", None, "Input raw text file (or comma-separated list of files).") flags.DEFINE_string( "output_file", None, "Output TF example file (or comma-separated list of files).") flags.DEFINE_string("vocab_file", None, "The vocabulary file that the BERT model was trained on.") flags.DEFINE_bool( "do_lower_case", True, "Whether to lower case the input text. Should be True for uncased " "models and False for cased models.") flags.DEFINE_bool( "do_whole_word_mask", False, "Whether to use whole word masking rather than per-WordPiece masking.") flags.DEFINE_bool( "gzip_compress", False, "Whether to use `GZIP` compress option to get compressed TFRecord files.") flags.DEFINE_integer("max_seq_length", 128, "Maximum sequence length.") flags.DEFINE_integer("max_predictions_per_seq", 20, "Maximum number of masked LM predictions per sequence.") flags.DEFINE_integer("random_seed", 12345, "Random seed for data generation.") flags.DEFINE_integer( "dupe_factor", 10, "Number of times to duplicate the input data (with different masks).") flags.DEFINE_float("masked_lm_prob", 0.15, "Masked LM probability.") flags.DEFINE_float( "short_seq_prob", 0.1, "Probability of creating sequences which are shorter than the " "maximum length.") class TrainingInstance(object): """A single training instance (sentence pair).""" def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels, is_random_next): self.tokens = tokens self.segment_ids = segment_ids self.is_random_next = is_random_next self.masked_lm_positions = masked_lm_positions self.masked_lm_labels = masked_lm_labels def __str__(self): s = "" s += "tokens: %s\n" % (" ".join( [tokenization.printable_text(x) for x in self.tokens])) s += "segment_ids: %s\n" % (" ".join([str(x) for x in self.segment_ids])) s += "is_random_next: %s\n" % self.is_random_next s += "masked_lm_positions: %s\n" % (" ".join( [str(x) for x in self.masked_lm_positions])) s += "masked_lm_labels: %s\n" % (" ".join( [tokenization.printable_text(x) for x in self.masked_lm_labels])) s += "\n" return s def __repr__(self): return self.__str__() def write_instance_to_example_files(instances, tokenizer, max_seq_length, max_predictions_per_seq, output_files): """Create TF example files from `TrainingInstance`s.""" writers = [] for output_file in output_files: writers.append( tf.io.TFRecordWriter( output_file, options="GZIP" if FLAGS.gzip_compress else "")) writer_index = 0 total_written = 0 for (inst_index, instance) in enumerate(instances): input_ids = tokenizer.convert_tokens_to_ids(instance.tokens) input_mask = [1] * len(input_ids) segment_ids = list(instance.segment_ids) assert len(input_ids) <= max_seq_length while len(input_ids) < max_seq_length: input_ids.append(0) input_mask.append(0) segment_ids.append(0) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length masked_lm_positions = list(instance.masked_lm_positions) masked_lm_ids = tokenizer.convert_tokens_to_ids(instance.masked_lm_labels) masked_lm_weights = [1.0] * len(masked_lm_ids) while len(masked_lm_positions) < max_predictions_per_seq: masked_lm_positions.append(0) masked_lm_ids.append(0) masked_lm_weights.append(0.0) next_sentence_label = 1 if instance.is_random_next else 0 features = collections.OrderedDict() features["input_ids"] = create_int_feature(input_ids) features["input_mask"] = create_int_feature(input_mask) features["segment_ids"] = create_int_feature(segment_ids) features["masked_lm_positions"] = create_int_feature(masked_lm_positions) features["masked_lm_ids"] = create_int_feature(masked_lm_ids) features["masked_lm_weights"] = create_float_feature(masked_lm_weights) features["next_sentence_labels"] = create_int_feature([next_sentence_label]) tf_example = tf.train.Example(features=tf.train.Features(feature=features)) writers[writer_index].write(tf_example.SerializeToString()) writer_index = (writer_index + 1) % len(writers) total_written += 1 if inst_index < 20: logging.info("*** Example ***") logging.info("tokens: %s", " ".join( [tokenization.printable_text(x) for x in instance.tokens])) for feature_name in features.keys(): feature = features[feature_name] values = [] if feature.int64_list.value: values = feature.int64_list.value elif feature.float_list.value: values = feature.float_list.value logging.info("%s: %s", feature_name, " ".join([str(x) for x in values])) for writer in writers: writer.close() logging.info("Wrote %d total instances", total_written) <|fim▁hole|>def create_int_feature(values): feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return feature def create_float_feature(values): feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values))) return feature def create_training_instances(input_files, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng): """Create `TrainingInstance`s from raw text.""" all_documents = [[]] # Input file format: # (1) One sentence per line. These should ideally be actual sentences, not # entire paragraphs or arbitrary spans of text. (Because we use the # sentence boundaries for the "next sentence prediction" task). # (2) Blank lines between documents. Document boundaries are needed so # that the "next sentence prediction" task doesn't span between documents. for input_file in input_files: with tf.io.gfile.GFile(input_file, "rb") as reader: while True: line = tokenization.convert_to_unicode(reader.readline()) if not line: break line = line.strip() # Empty lines are used as document delimiters if not line: all_documents.append([]) tokens = tokenizer.tokenize(line) if tokens: all_documents[-1].append(tokens) # Remove empty documents all_documents = [x for x in all_documents if x] rng.shuffle(all_documents) vocab_words = list(tokenizer.vocab.keys()) instances = [] for _ in range(dupe_factor): for document_index in range(len(all_documents)): instances.extend( create_instances_from_document( all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng)) rng.shuffle(instances) return instances def create_instances_from_document( all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates `TrainingInstance`s for a single document.""" document = all_documents[document_index] # Account for [CLS], [SEP], [SEP] max_num_tokens = max_seq_length - 3 # We *usually* want to fill up the entire sequence since we are padding # to `max_seq_length` anyways, so short sequences are generally wasted # computation. However, we *sometimes* # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter # sequences to minimize the mismatch between pre-training and fine-tuning. # The `target_seq_length` is just a rough target however, whereas # `max_seq_length` is a hard limit. target_seq_length = max_num_tokens if rng.random() < short_seq_prob: target_seq_length = rng.randint(2, max_num_tokens) # We DON'T just concatenate all of the tokens from a document into a long # sequence and choose an arbitrary split point because this would make the # next sentence prediction task too easy. Instead, we split the input into # segments "A" and "B" based on the actual "sentences" provided by the user # input. instances = [] current_chunk = [] current_length = 0 i = 0 while i < len(document): segment = document[i] current_chunk.append(segment) current_length += len(segment) if i == len(document) - 1 or current_length >= target_seq_length: if current_chunk: # `a_end` is how many segments from `current_chunk` go into the `A` # (first) sentence. a_end = 1 if len(current_chunk) >= 2: a_end = rng.randint(1, len(current_chunk) - 1) tokens_a = [] for j in range(a_end): tokens_a.extend(current_chunk[j]) tokens_b = [] # Random next is_random_next = False if len(current_chunk) == 1 or rng.random() < 0.5: is_random_next = True target_b_length = target_seq_length - len(tokens_a) # This should rarely go for more than one iteration for large # corpora. However, just to be careful, we try to make sure that # the random document is not the same as the document # we're processing. for _ in range(10): random_document_index = rng.randint(0, len(all_documents) - 1) if random_document_index != document_index: break random_document = all_documents[random_document_index] random_start = rng.randint(0, len(random_document) - 1) for j in range(random_start, len(random_document)): tokens_b.extend(random_document[j]) if len(tokens_b) >= target_b_length: break # We didn't actually use these segments so we "put them back" so # they don't go to waste. num_unused_segments = len(current_chunk) - a_end i -= num_unused_segments # Actual next else: is_random_next = False for j in range(a_end, len(current_chunk)): tokens_b.extend(current_chunk[j]) truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng) assert len(tokens_a) >= 1 assert len(tokens_b) >= 1 tokens = [] segment_ids = [] tokens.append("[CLS]") segment_ids.append(0) for token in tokens_a: tokens.append(token) segment_ids.append(0) tokens.append("[SEP]") segment_ids.append(0) for token in tokens_b: tokens.append(token) segment_ids.append(1) tokens.append("[SEP]") segment_ids.append(1) (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions( tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng) instance = TrainingInstance( tokens=tokens, segment_ids=segment_ids, is_random_next=is_random_next, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) instances.append(instance) current_chunk = [] current_length = 0 i += 1 return instances MaskedLmInstance = collections.namedtuple("MaskedLmInstance", ["index", "label"]) def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates the predictions for the masked LM objective.""" cand_indexes = [] for (i, token) in enumerate(tokens): if token == "[CLS]" or token == "[SEP]": continue # Whole Word Masking means that if we mask all of the wordpieces # corresponding to an original word. When a word has been split into # WordPieces, the first token does not have any marker and any subsequence # tokens are prefixed with ##. So whenever we see the ## token, we # append it to the previous set of word indexes. # # Note that Whole Word Masking does *not* change the training code # at all -- we still predict each WordPiece independently, softmaxed # over the entire vocabulary. if (FLAGS.do_whole_word_mask and len(cand_indexes) >= 1 and token.startswith("##")): cand_indexes[-1].append(i) else: cand_indexes.append([i]) rng.shuffle(cand_indexes) output_tokens = list(tokens) num_to_predict = min(max_predictions_per_seq, max(1, int(round(len(tokens) * masked_lm_prob)))) masked_lms = [] covered_indexes = set() for index_set in cand_indexes: if len(masked_lms) >= num_to_predict: break # If adding a whole-word mask would exceed the maximum number of # predictions, then just skip this candidate. if len(masked_lms) + len(index_set) > num_to_predict: continue is_any_index_covered = False for index in index_set: if index in covered_indexes: is_any_index_covered = True break if is_any_index_covered: continue for index in index_set: covered_indexes.add(index) masked_token = None # 80% of the time, replace with [MASK] if rng.random() < 0.8: masked_token = "[MASK]" else: # 10% of the time, keep original if rng.random() < 0.5: masked_token = tokens[index] # 10% of the time, replace with random word else: masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)] output_tokens[index] = masked_token masked_lms.append(MaskedLmInstance(index=index, label=tokens[index])) assert len(masked_lms) <= num_to_predict masked_lms = sorted(masked_lms, key=lambda x: x.index) masked_lm_positions = [] masked_lm_labels = [] for p in masked_lms: masked_lm_positions.append(p.index) masked_lm_labels.append(p.label) return (output_tokens, masked_lm_positions, masked_lm_labels) def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng): """Truncates a pair of sequences to a maximum sequence length.""" while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_num_tokens: break trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b assert len(trunc_tokens) >= 1 # We want to sometimes truncate from the front and sometimes from the # back to add more randomness and avoid biases. if rng.random() < 0.5: del trunc_tokens[0] else: trunc_tokens.pop() def main(_): tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) input_files = [] for input_pattern in FLAGS.input_file.split(","): input_files.extend(tf.io.gfile.glob(input_pattern)) logging.info("*** Reading from input files ***") for input_file in input_files: logging.info(" %s", input_file) rng = random.Random(FLAGS.random_seed) instances = create_training_instances( input_files, tokenizer, FLAGS.max_seq_length, FLAGS.dupe_factor, FLAGS.short_seq_prob, FLAGS.masked_lm_prob, FLAGS.max_predictions_per_seq, rng) output_files = FLAGS.output_file.split(",") logging.info("*** Writing to output files ***") for output_file in output_files: logging.info(" %s", output_file) write_instance_to_example_files(instances, tokenizer, FLAGS.max_seq_length, FLAGS.max_predictions_per_seq, output_files) if __name__ == "__main__": flags.mark_flag_as_required("input_file") flags.mark_flag_as_required("output_file") flags.mark_flag_as_required("vocab_file") app.run(main)<|fim▁end|>
<|file_name|>cellSpec.ts<|end_file_name|><|fim▁begin|>import * as Jungle from '../../../jungle' const {Construct, Composite, Domain, Cell, j, J} = Jungle; import * as Debug from '../../../util/debug' describe("A Cell", function () { Debug.Crumb.defaultOptions.log = console; Debug.Crumb.defaultOptions.debug = true; let cell; beforeEach(function(){ cell = J.recover(j('cell', { head:{ retain:true, }, mouth:j('inward'), stomach:j('cell',{ swallow :j('resolve',{ outer(food){ this.earth.contents = food } }), contents:'empty' }), oesophagus:j('media:direct', { law:':mouth->stomach:swallow' }), })) }) it('should deposit to the stomach, via oesophagus', function(){ let crumb = new Debug.Crumb("Beginning Feed"); cell.shell.contacts.mouth.put("Nachos", crumb); expect(cell.exposed.stomach.contents).toBe("Nachos"); }) it('should properly dispose', function(){ cell.dispose();<|fim▁hole|> });<|fim▁end|>
expect(cell.shell.scan(':mouth')[":mouth"]).toBe(undefined) })
<|file_name|>large_profile_extender.py<|end_file_name|><|fim▁begin|># Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from profile_creators import cookie_profile_extender from profile_creators import history_profile_extender from profile_creators import profile_extender class LargeProfileExtender(profile_extender.ProfileExtender): """This class creates a large profile by performing a large number of url navigations.""" def Run(self): extender = history_profile_extender.HistoryProfileExtender( self.finder_options) extender.Run() extender = cookie_profile_extender.CookieProfileExtender(<|fim▁hole|><|fim▁end|>
self.finder_options) extender.Run()
<|file_name|>glue.rs<|end_file_name|><|fim▁begin|>/* 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/. */ use cssparser::{Parser, ParserInput}; use cssparser::ToCss as ParserToCss; use env_logger::LogBuilder; use malloc_size_of::MallocSizeOfOps; use selectors::Element; use selectors::matching::{MatchingContext, MatchingMode, matches_selector}; use servo_arc::{Arc, ArcBorrow, RawOffsetArc}; use std::cell::RefCell; use std::env; use std::fmt::Write; use std::iter; use std::mem; use std::ptr; use style::applicable_declarations::ApplicableDeclarationBlock; use style::context::{CascadeInputs, QuirksMode, SharedStyleContext, StyleContext}; use style::context::ThreadLocalStyleContext; use style::data::{ElementStyles, self}; use style::dom::{ShowSubtreeData, TDocument, TElement, TNode}; use style::driver; use style::element_state::{DocumentState, ElementState}; use style::error_reporting::{NullReporter, ParseErrorReporter}; use style::font_metrics::{FontMetricsProvider, get_metrics_provider_for_product}; use style::gecko::data::{GeckoStyleSheet, PerDocumentStyleData, PerDocumentStyleDataImpl}; use style::gecko::global_style_data::{GLOBAL_STYLE_DATA, GlobalStyleData, STYLE_THREAD_POOL}; use style::gecko::restyle_damage::GeckoRestyleDamage; use style::gecko::selector_parser::PseudoElement; use style::gecko::traversal::RecalcStyleOnly; use style::gecko::wrapper::{GeckoElement, GeckoNode}; use style::gecko_bindings::bindings; use style::gecko_bindings::bindings::{RawGeckoElementBorrowed, RawGeckoElementBorrowedOrNull, RawGeckoNodeBorrowed}; use style::gecko_bindings::bindings::{RawGeckoKeyframeListBorrowed, RawGeckoKeyframeListBorrowedMut}; use style::gecko_bindings::bindings::{RawServoDeclarationBlockBorrowed, RawServoDeclarationBlockStrong}; use style::gecko_bindings::bindings::{RawServoDocumentRule, RawServoDocumentRuleBorrowed}; use style::gecko_bindings::bindings::{RawServoFontFeatureValuesRule, RawServoFontFeatureValuesRuleBorrowed}; use style::gecko_bindings::bindings::{RawServoImportRule, RawServoImportRuleBorrowed}; use style::gecko_bindings::bindings::{RawServoKeyframe, RawServoKeyframeBorrowed, RawServoKeyframeStrong}; use style::gecko_bindings::bindings::{RawServoKeyframesRule, RawServoKeyframesRuleBorrowed}; use style::gecko_bindings::bindings::{RawServoMediaListBorrowed, RawServoMediaListStrong}; use style::gecko_bindings::bindings::{RawServoMediaRule, RawServoMediaRuleBorrowed}; use style::gecko_bindings::bindings::{RawServoNamespaceRule, RawServoNamespaceRuleBorrowed}; use style::gecko_bindings::bindings::{RawServoPageRule, RawServoPageRuleBorrowed}; use style::gecko_bindings::bindings::{RawServoSelectorListBorrowed, RawServoSelectorListOwned}; use style::gecko_bindings::bindings::{RawServoSourceSizeListBorrowedOrNull, RawServoSourceSizeListOwned}; use style::gecko_bindings::bindings::{RawServoStyleSetBorrowed, RawServoStyleSetBorrowedOrNull, RawServoStyleSetOwned}; use style::gecko_bindings::bindings::{RawServoStyleSheetContentsBorrowed, ServoComputedDataBorrowed}; use style::gecko_bindings::bindings::{RawServoStyleSheetContentsStrong, ServoStyleContextBorrowed}; use style::gecko_bindings::bindings::{RawServoSupportsRule, RawServoSupportsRuleBorrowed}; use style::gecko_bindings::bindings::{ServoCssRulesBorrowed, ServoCssRulesStrong}; use style::gecko_bindings::bindings::{nsACString, nsAString, nsCSSPropertyIDSetBorrowedMut}; use style::gecko_bindings::bindings::Gecko_AddPropertyToSet; use style::gecko_bindings::bindings::Gecko_AppendPropertyValuePair; use style::gecko_bindings::bindings::Gecko_ConstructFontFeatureValueSet; use style::gecko_bindings::bindings::Gecko_GetOrCreateFinalKeyframe; use style::gecko_bindings::bindings::Gecko_GetOrCreateInitialKeyframe; use style::gecko_bindings::bindings::Gecko_GetOrCreateKeyframeAtStart; use style::gecko_bindings::bindings::Gecko_HaveSeenPtr; use style::gecko_bindings::bindings::Gecko_NewNoneTransform; use style::gecko_bindings::bindings::RawGeckoAnimationPropertySegmentBorrowed; use style::gecko_bindings::bindings::RawGeckoCSSPropertyIDListBorrowed; use style::gecko_bindings::bindings::RawGeckoComputedKeyframeValuesListBorrowedMut; use style::gecko_bindings::bindings::RawGeckoComputedTimingBorrowed; use style::gecko_bindings::bindings::RawGeckoFontFaceRuleListBorrowedMut; use style::gecko_bindings::bindings::RawGeckoServoAnimationValueListBorrowed; use style::gecko_bindings::bindings::RawGeckoServoAnimationValueListBorrowedMut; use style::gecko_bindings::bindings::RawGeckoServoStyleRuleListBorrowedMut; use style::gecko_bindings::bindings::RawServoAnimationValueBorrowed; use style::gecko_bindings::bindings::RawServoAnimationValueBorrowedOrNull; use style::gecko_bindings::bindings::RawServoAnimationValueMapBorrowedMut; use style::gecko_bindings::bindings::RawServoAnimationValueStrong; use style::gecko_bindings::bindings::RawServoAnimationValueTableBorrowed; use style::gecko_bindings::bindings::RawServoDeclarationBlockBorrowedOrNull; use style::gecko_bindings::bindings::RawServoStyleRuleBorrowed; use style::gecko_bindings::bindings::RawServoStyleSet; use style::gecko_bindings::bindings::ServoStyleContextBorrowedOrNull; use style::gecko_bindings::bindings::nsTArrayBorrowed_uintptr_t; use style::gecko_bindings::bindings::nsTimingFunctionBorrowed; use style::gecko_bindings::bindings::nsTimingFunctionBorrowedMut; use style::gecko_bindings::structs; use style::gecko_bindings::structs::{CallerType, CSSPseudoElementType, CompositeOperation}; use style::gecko_bindings::structs::{Loader, LoaderReusableStyleSheets}; use style::gecko_bindings::structs::{RawServoStyleRule, ServoStyleContextStrong, RustString}; use style::gecko_bindings::structs::{ServoStyleSheet, SheetParsingMode, nsAtom, nsCSSPropertyID}; use style::gecko_bindings::structs::{nsCSSFontFaceRule, nsCSSCounterStyleRule}; use style::gecko_bindings::structs::{nsRestyleHint, nsChangeHint, PropertyValuePair}; use style::gecko_bindings::structs::AtomArray; use style::gecko_bindings::structs::IterationCompositeOperation; use style::gecko_bindings::structs::MallocSizeOf as GeckoMallocSizeOf; use style::gecko_bindings::structs::OriginFlags; use style::gecko_bindings::structs::OriginFlags_Author; use style::gecko_bindings::structs::OriginFlags_User; use style::gecko_bindings::structs::OriginFlags_UserAgent; use style::gecko_bindings::structs::RawGeckoGfxMatrix4x4; use style::gecko_bindings::structs::RawGeckoPresContextOwned; use style::gecko_bindings::structs::RawServoSelectorList; use style::gecko_bindings::structs::RawServoSourceSizeList; use style::gecko_bindings::structs::SeenPtrs; use style::gecko_bindings::structs::ServoElementSnapshotTable; use style::gecko_bindings::structs::ServoStyleSetSizes; use style::gecko_bindings::structs::ServoTraversalFlags; use style::gecko_bindings::structs::StyleRuleInclusion; use style::gecko_bindings::structs::URLExtraData; use style::gecko_bindings::structs::gfxFontFeatureValueSet; use style::gecko_bindings::structs::nsCSSValueSharedList; use style::gecko_bindings::structs::nsCompatibility; use style::gecko_bindings::structs::nsIDocument; use style::gecko_bindings::structs::nsStyleTransformMatrix::MatrixTransformOperator; use style::gecko_bindings::structs::nsTArray; use style::gecko_bindings::structs::nsresult; use style::gecko_bindings::sugar::ownership::{FFIArcHelpers, HasFFI, HasArcFFI}; use style::gecko_bindings::sugar::ownership::{HasSimpleFFI, Strong}; use style::gecko_bindings::sugar::refptr::RefPtr; use style::gecko_properties; use style::invalidation::element::restyle_hints; use style::media_queries::{Device, MediaList, parse_media_query_list}; use style::parser::{Parse, ParserContext, self}; use style::properties::{CascadeFlags, ComputedValues, DeclarationSource, Importance}; use style::properties::{LonghandId, LonghandIdSet, PropertyDeclaration, PropertyDeclarationBlock, PropertyId}; use style::properties::{PropertyDeclarationId, ShorthandId}; use style::properties::{SourcePropertyDeclaration, StyleBuilder}; use style::properties::animated_properties::AnimationValue; use style::properties::animated_properties::compare_property_priority; use style::properties::parse_one_declaration_into; use style::rule_cache::RuleCacheConditions; use style::rule_tree::{CascadeLevel, StrongRuleNode, StyleSource}; use style::selector_parser::{PseudoElementCascadeType, SelectorImpl}; use style::shared_lock::{SharedRwLockReadGuard, StylesheetGuards, ToCssWithGuard, Locked}; use style::string_cache::{Atom, WeakAtom}; use style::style_adjuster::StyleAdjuster; use style::stylesheets::{CssRule, CssRules, CssRuleType, CssRulesHelpers, DocumentRule}; use style::stylesheets::{FontFeatureValuesRule, ImportRule, KeyframesRule, MediaRule}; use style::stylesheets::{NamespaceRule, Origin, OriginSet, PageRule, StyleRule}; use style::stylesheets::{StylesheetContents, SupportsRule}; use style::stylesheets::StylesheetLoader as StyleStylesheetLoader; use style::stylesheets::keyframes_rule::{Keyframe, KeyframeSelector, KeyframesStepValue}; use style::stylesheets::supports_rule::parse_condition_or_declaration; use style::stylist::{add_size_of_ua_cache, RuleInclusion, Stylist}; use style::thread_state; use style::timer::Timer; use style::traversal::DomTraversal; use style::traversal::resolve_style; use style::traversal_flags::{self, TraversalFlags}; use style::values::{CustomIdent, KeyframesName}; use style::values::animated::{Animate, Procedure, ToAnimatedZero}; use style::values::computed::{Context, ToComputedValue}; use style::values::distance::ComputeSquaredDistance; use style::values::specified; use style::values::specified::gecko::IntersectionObserverRootMargin; use style::values::specified::source_size_list::SourceSizeList; use style_traits::{ParsingMode, ToCss}; use super::error_reporter::ErrorReporter; use super::stylesheet_loader::StylesheetLoader; /* * For Gecko->Servo function calls, we need to redeclare the same signature that was declared in * the C header in Gecko. In order to catch accidental mismatches, we run rust-bindgen against * those signatures as well, giving us a second declaration of all the Servo_* functions in this * crate. If there's a mismatch, LLVM will assert and abort, which is a rather awful thing to * depend on but good enough for our purposes. */ // A dummy url data for where we don't pass url data in. // We need to get rid of this sooner than later. static mut DUMMY_URL_DATA: *mut URLExtraData = 0 as *mut URLExtraData; #[no_mangle] pub extern "C" fn Servo_Initialize(dummy_url_data: *mut URLExtraData) { use style::gecko_bindings::sugar::origin_flags; // Initialize logging. let mut builder = LogBuilder::new(); let default_level = if cfg!(debug_assertions) { "warn" } else { "error" }; match env::var("RUST_LOG") { Ok(v) => builder.parse(&v).init().unwrap(), _ => builder.parse(default_level).init().unwrap(), }; // Pretend that we're a Servo Layout thread, to make some assertions happy. thread_state::initialize(thread_state::ThreadState::LAYOUT); // Perform some debug-only runtime assertions. restyle_hints::assert_restyle_hints_match(); origin_flags::assert_flags_match(); parser::assert_parsing_mode_match(); traversal_flags::assert_traversal_flags_match(); specified::font::assert_variant_east_asian_matches(); specified::font::assert_variant_ligatures_matches(); // Initialize the dummy url data unsafe { DUMMY_URL_DATA = dummy_url_data; } } #[no_mangle] pub extern "C" fn Servo_InitializeCooperativeThread() { // Pretend that we're a Servo Layout thread to make some assertions happy. thread_state::initialize(thread_state::ThreadState::LAYOUT); } #[no_mangle] pub extern "C" fn Servo_Shutdown() { // The dummy url will be released after shutdown, so clear the // reference to avoid use-after-free. unsafe { DUMMY_URL_DATA = ptr::null_mut(); } Stylist::shutdown(); } unsafe fn dummy_url_data() -> &'static RefPtr<URLExtraData> { RefPtr::from_ptr_ref(&DUMMY_URL_DATA) } fn create_shared_context<'a>(global_style_data: &GlobalStyleData, guard: &'a SharedRwLockReadGuard, per_doc_data: &'a PerDocumentStyleDataImpl, traversal_flags: TraversalFlags, snapshot_map: &'a ServoElementSnapshotTable) -> SharedStyleContext<'a> { SharedStyleContext { stylist: &per_doc_data.stylist, visited_styles_enabled: per_doc_data.visited_styles_enabled(), options: global_style_data.options.clone(), guards: StylesheetGuards::same(guard), timer: Timer::new(), traversal_flags: traversal_flags, snapshot_map: snapshot_map, } } fn traverse_subtree(element: GeckoElement, raw_data: RawServoStyleSetBorrowed, traversal_flags: TraversalFlags, snapshots: &ServoElementSnapshotTable) { // When new content is inserted in a display:none subtree, we will call into // servo to try to style it. Detect that here and bail out. if let Some(parent) = element.traversal_parent() { if parent.borrow_data().map_or(true, |d| d.styles.is_display_none()) { debug!("{:?} has unstyled parent {:?} - ignoring call to traverse_subtree", element, parent); return; } } let per_doc_data = PerDocumentStyleData::from_ffi(raw_data).borrow(); debug_assert!(!per_doc_data.stylist.stylesheets_have_changed()); let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let shared_style_context = create_shared_context( &global_style_data, &guard, &per_doc_data, traversal_flags, snapshots, ); let token = RecalcStyleOnly::pre_traverse( element, &shared_style_context, ); if !token.should_traverse() { return; } debug!("Traversing subtree from {:?}", element); let thread_pool_holder = &*STYLE_THREAD_POOL; let thread_pool = if traversal_flags.contains(TraversalFlags::ParallelTraversal) { thread_pool_holder.style_thread_pool.as_ref() } else { None }; let traversal = RecalcStyleOnly::new(shared_style_context); driver::traverse_dom(&traversal, token, thread_pool); } /// Traverses the subtree rooted at `root` for restyling. /// /// Returns whether the root was restyled. Whether anything else was restyled or /// not can be inferred from the dirty bits in the rest of the tree. #[no_mangle] pub extern "C" fn Servo_TraverseSubtree( root: RawGeckoElementBorrowed, raw_data: RawServoStyleSetBorrowed, snapshots: *const ServoElementSnapshotTable, raw_flags: ServoTraversalFlags ) -> bool { let traversal_flags = TraversalFlags::from_bits_truncate(raw_flags); debug_assert!(!snapshots.is_null()); let element = GeckoElement(root); debug!("Servo_TraverseSubtree (flags={:?})", traversal_flags); debug!("{:?}", ShowSubtreeData(element.as_node())); // It makes no sense to do an animation restyle when we're styling // newly-inserted content. if !traversal_flags.contains(TraversalFlags::UnstyledOnly) { let needs_animation_only_restyle = element.has_animation_only_dirty_descendants() || element.has_animation_restyle_hints(); if needs_animation_only_restyle { debug!("Servo_TraverseSubtree doing animation-only restyle (aodd={})", element.has_animation_only_dirty_descendants()); traverse_subtree(element, raw_data, traversal_flags | TraversalFlags::AnimationOnly, unsafe { &*snapshots }); } } traverse_subtree(element, raw_data, traversal_flags, unsafe { &*snapshots }); debug!("Servo_TraverseSubtree complete (dd={}, aodd={}, lfcd={}, lfc={}, data={:?})", element.has_dirty_descendants(), element.has_animation_only_dirty_descendants(), element.descendants_need_frames(), element.needs_frame(), element.borrow_data().unwrap()); let element_was_restyled = element.borrow_data().unwrap().contains_restyle_data(); element_was_restyled } /// Checks whether the rule tree has crossed its threshold for unused nodes, and /// if so, frees them. #[no_mangle] pub extern "C" fn Servo_MaybeGCRuleTree(raw_data: RawServoStyleSetBorrowed) { let per_doc_data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); unsafe { per_doc_data.stylist.rule_tree().maybe_gc(); } } #[no_mangle] pub extern "C" fn Servo_AnimationValues_Interpolate( from: RawServoAnimationValueBorrowed, to: RawServoAnimationValueBorrowed, progress: f64, ) -> RawServoAnimationValueStrong { let from_value = AnimationValue::as_arc(&from); let to_value = AnimationValue::as_arc(&to); if let Ok(value) = from_value.animate(to_value, Procedure::Interpolate { progress }) { Arc::new(value).into_strong() } else { RawServoAnimationValueStrong::null() } } #[no_mangle] pub extern "C" fn Servo_AnimationValues_IsInterpolable(from: RawServoAnimationValueBorrowed, to: RawServoAnimationValueBorrowed) -> bool { let from_value = AnimationValue::as_arc(&from); let to_value = AnimationValue::as_arc(&to); from_value.animate(to_value, Procedure::Interpolate { progress: 0.5 }).is_ok() } #[no_mangle] pub extern "C" fn Servo_AnimationValues_Add( a: RawServoAnimationValueBorrowed, b: RawServoAnimationValueBorrowed, ) -> RawServoAnimationValueStrong { let a_value = AnimationValue::as_arc(&a); let b_value = AnimationValue::as_arc(&b); if let Ok(value) = a_value.animate(b_value, Procedure::Add) { Arc::new(value).into_strong() } else { RawServoAnimationValueStrong::null() } } #[no_mangle] pub extern "C" fn Servo_AnimationValues_Accumulate( a: RawServoAnimationValueBorrowed, b: RawServoAnimationValueBorrowed, count: u64, ) -> RawServoAnimationValueStrong { let a_value = AnimationValue::as_arc(&a); let b_value = AnimationValue::as_arc(&b); if let Ok(value) = a_value.animate(b_value, Procedure::Accumulate { count }) { Arc::new(value).into_strong() } else { RawServoAnimationValueStrong::null() } } #[no_mangle] pub extern "C" fn Servo_AnimationValues_GetZeroValue( value_to_match: RawServoAnimationValueBorrowed) -> RawServoAnimationValueStrong { let value_to_match = AnimationValue::as_arc(&value_to_match); if let Ok(zero_value) = value_to_match.to_animated_zero() { Arc::new(zero_value).into_strong() } else { RawServoAnimationValueStrong::null() } } #[no_mangle] pub extern "C" fn Servo_AnimationValues_ComputeDistance(from: RawServoAnimationValueBorrowed, to: RawServoAnimationValueBorrowed) -> f64 { let from_value = AnimationValue::as_arc(&from); let to_value = AnimationValue::as_arc(&to); // If compute_squared_distance() failed, this function will return negative value // in order to check whether we support the specified paced animation values. from_value.compute_squared_distance(to_value).map(|d| d.sqrt()).unwrap_or(-1.0) } /// Compute one of the endpoints for the interpolation interval, compositing it with the /// underlying value if needed. /// An None returned value means, "Just use endpoint_value as-is." /// It is the responsibility of the caller to ensure that |underlying_value| is provided /// when it will be used. fn composite_endpoint( endpoint_value: Option<&RawOffsetArc<AnimationValue>>, composite: CompositeOperation, underlying_value: Option<&AnimationValue>, ) -> Option<AnimationValue> { match endpoint_value { Some(endpoint_value) => { match composite { CompositeOperation::Add => { underlying_value .expect("We should have an underlying_value") .animate(endpoint_value, Procedure::Add).ok() }, CompositeOperation::Accumulate => { underlying_value .expect("We should have an underlying value") .animate(endpoint_value, Procedure::Accumulate { count: 1 }) .ok() }, _ => None, } }, None => underlying_value.map(|v| v.clone()), } } /// Accumulate one of the endpoints of the animation interval. /// A returned value of None means, "Just use endpoint_value as-is." fn accumulate_endpoint( endpoint_value: Option<&RawOffsetArc<AnimationValue>>, composited_value: Option<AnimationValue>, last_value: &AnimationValue, current_iteration: u64 ) -> Option<AnimationValue> { debug_assert!(endpoint_value.is_some() || composited_value.is_some(), "Should have a suitable value to use"); let count = current_iteration; match composited_value { Some(endpoint) => { last_value .animate(&endpoint, Procedure::Accumulate { count }) .ok() .or(Some(endpoint)) }, None => { last_value .animate(endpoint_value.unwrap(), Procedure::Accumulate { count }) .ok() }, } } /// Compose the animation segment. We composite it with the underlying_value and last_value if /// needed. /// The caller is responsible for providing an underlying value and last value /// in all situations where there are needed. fn compose_animation_segment( segment: RawGeckoAnimationPropertySegmentBorrowed, underlying_value: Option<&AnimationValue>, last_value: Option<&AnimationValue>, iteration_composite: IterationCompositeOperation, current_iteration: u64, total_progress: f64, segment_progress: f64, ) -> AnimationValue { // Extract keyframe values. let raw_from_value; let keyframe_from_value = if !segment.mFromValue.mServo.mRawPtr.is_null() { raw_from_value = unsafe { &*segment.mFromValue.mServo.mRawPtr }; Some(AnimationValue::as_arc(&raw_from_value)) } else { None }; let raw_to_value; let keyframe_to_value = if !segment.mToValue.mServo.mRawPtr.is_null() { raw_to_value = unsafe { &*segment.mToValue.mServo.mRawPtr }; Some(AnimationValue::as_arc(&raw_to_value)) } else { None }; let mut composited_from_value = composite_endpoint(keyframe_from_value, segment.mFromComposite, underlying_value); let mut composited_to_value = composite_endpoint(keyframe_to_value, segment.mToComposite, underlying_value); debug_assert!(keyframe_from_value.is_some() || composited_from_value.is_some(), "Should have a suitable from value to use"); debug_assert!(keyframe_to_value.is_some() || composited_to_value.is_some(), "Should have a suitable to value to use"); // Apply iteration composite behavior. if iteration_composite == IterationCompositeOperation::Accumulate && current_iteration > 0 { let last_value = last_value.unwrap_or_else(|| { underlying_value.expect("Should have a valid underlying value") }); composited_from_value = accumulate_endpoint(keyframe_from_value, composited_from_value, last_value, current_iteration); composited_to_value = accumulate_endpoint(keyframe_to_value, composited_to_value, last_value, current_iteration); } // Use the composited value if there is one, otherwise, use the original keyframe value. let from = composited_from_value.as_ref().unwrap_or_else(|| keyframe_from_value.unwrap()); let to = composited_to_value.as_ref().unwrap_or_else(|| keyframe_to_value.unwrap()); if segment.mToKey == segment.mFromKey { return if total_progress < 0. { from.clone() } else { to.clone() }; } match from.animate(to, Procedure::Interpolate { progress: segment_progress }) { Ok(value) => value, _ => if segment_progress < 0.5 { from.clone() } else { to.clone() }, } } #[no_mangle] pub extern "C" fn Servo_ComposeAnimationSegment( segment: RawGeckoAnimationPropertySegmentBorrowed, underlying_value: RawServoAnimationValueBorrowedOrNull, last_value: RawServoAnimationValueBorrowedOrNull, iteration_composite: IterationCompositeOperation, progress: f64, current_iteration: u64 ) -> RawServoAnimationValueStrong { let underlying_value = AnimationValue::arc_from_borrowed(&underlying_value).map(|v| &**v); let last_value = AnimationValue::arc_from_borrowed(&last_value).map(|v| &**v); let result = compose_animation_segment(segment, underlying_value, last_value, iteration_composite, current_iteration, progress, progress); Arc::new(result).into_strong() } #[no_mangle] pub extern "C" fn Servo_AnimationCompose(raw_value_map: RawServoAnimationValueMapBorrowedMut, base_values: RawServoAnimationValueTableBorrowed, css_property: nsCSSPropertyID, segment: RawGeckoAnimationPropertySegmentBorrowed, last_segment: RawGeckoAnimationPropertySegmentBorrowed, computed_timing: RawGeckoComputedTimingBorrowed, iteration_composite: IterationCompositeOperation) { use style::gecko_bindings::bindings::Gecko_AnimationGetBaseStyle; use style::gecko_bindings::bindings::Gecko_GetPositionInSegment; use style::gecko_bindings::bindings::Gecko_GetProgressFromComputedTiming; use style::properties::animated_properties::AnimationValueMap; let property = match LonghandId::from_nscsspropertyid(css_property) { Ok(longhand) if longhand.is_animatable() => longhand, _ => return, }; let value_map = AnimationValueMap::from_ffi_mut(raw_value_map); // We will need an underlying value if either of the endpoints is null... let need_underlying_value = segment.mFromValue.mServo.mRawPtr.is_null() || segment.mToValue.mServo.mRawPtr.is_null() || // ... or if they have a non-replace composite mode ... segment.mFromComposite != CompositeOperation::Replace || segment.mToComposite != CompositeOperation::Replace || // ... or if we accumulate onto the last value and it is null. (iteration_composite == IterationCompositeOperation::Accumulate && computed_timing.mCurrentIteration > 0 && last_segment.mToValue.mServo.mRawPtr.is_null()); // If either of the segment endpoints are null, get the underlying value to // use from the current value in the values map (set by a lower-priority // effect), or, if there is no current value, look up the cached base value // for this property. let underlying_value = if need_underlying_value { let previous_composed_value = value_map.get(&property).cloned(); previous_composed_value.or_else(|| { let raw_base_style = unsafe { Gecko_AnimationGetBaseStyle(base_values, css_property) }; AnimationValue::arc_from_borrowed(&raw_base_style).map(|v| &**v).cloned() }) } else { None }; if need_underlying_value && underlying_value.is_none() { warn!("Underlying value should be valid when we expect to use it"); return; } let raw_last_value; let last_value = if !last_segment.mToValue.mServo.mRawPtr.is_null() { raw_last_value = unsafe { &*last_segment.mToValue.mServo.mRawPtr }; Some(&**AnimationValue::as_arc(&raw_last_value)) } else { None }; let progress = unsafe { Gecko_GetProgressFromComputedTiming(computed_timing) }; let position = if segment.mToKey == segment.mFromKey { // Note: compose_animation_segment doesn't use this value // if segment.mFromKey == segment.mToKey, so assigning |progress| directly is fine. progress } else { unsafe { Gecko_GetPositionInSegment(segment, progress, computed_timing.mBeforeFlag) } }; let result = compose_animation_segment(segment, underlying_value.as_ref(), last_value, iteration_composite, computed_timing.mCurrentIteration, progress, position); value_map.insert(property, result); } macro_rules! get_property_id_from_nscsspropertyid { ($property_id: ident, $ret: expr) => {{ match PropertyId::from_nscsspropertyid($property_id) { Ok(property_id) => property_id, Err(()) => { return $ret; } } }} } #[no_mangle] pub extern "C" fn Servo_AnimationValue_Serialize(value: RawServoAnimationValueBorrowed, property: nsCSSPropertyID, buffer: *mut nsAString) { let uncomputed_value = AnimationValue::as_arc(&value).uncompute(); let mut string = String::new(); let rv = PropertyDeclarationBlock::with_one(uncomputed_value, Importance::Normal) .single_value_to_css(&get_property_id_from_nscsspropertyid!(property, ()), &mut string, None, None /* No extra custom properties */); debug_assert!(rv.is_ok()); let buffer = unsafe { buffer.as_mut().unwrap() }; buffer.assign_utf8(&string); } #[no_mangle] pub extern "C" fn Servo_Shorthand_AnimationValues_Serialize(shorthand_property: nsCSSPropertyID, values: RawGeckoServoAnimationValueListBorrowed, buffer: *mut nsAString) { let property_id = get_property_id_from_nscsspropertyid!(shorthand_property, ()); let shorthand = match property_id.as_shorthand() { Ok(shorthand) => shorthand, _ => return, }; // Convert RawServoAnimationValue(s) into a vector of PropertyDeclaration // so that we can use reference of the PropertyDeclaration without worrying // about its lifetime. (longhands_to_css() expects &PropertyDeclaration // iterator.) let declarations: Vec<PropertyDeclaration> = values.iter().map(|v| AnimationValue::as_arc(unsafe { &&*v.mRawPtr }).uncompute()).collect(); let mut string = String::new(); let rv = shorthand.longhands_to_css(declarations.iter(), &mut string); if rv.is_ok() { let buffer = unsafe { buffer.as_mut().unwrap() }; buffer.assign_utf8(&string); } } #[no_mangle] pub extern "C" fn Servo_AnimationValue_GetOpacity( value: RawServoAnimationValueBorrowed ) -> f32 { let value = AnimationValue::as_arc(&value); if let AnimationValue::Opacity(opacity) = **value { opacity } else { panic!("The AnimationValue should be Opacity"); } } #[no_mangle] pub extern "C" fn Servo_AnimationValue_Opacity( opacity: f32 ) -> RawServoAnimationValueStrong { Arc::new(AnimationValue::Opacity(opacity)).into_strong() } #[no_mangle] pub extern "C" fn Servo_AnimationValue_GetTransform( value: RawServoAnimationValueBorrowed, list: *mut structs::RefPtr<nsCSSValueSharedList> ) { let value = AnimationValue::as_arc(&value); if let AnimationValue::Transform(ref servo_list) = **value { let list = unsafe { &mut *list }; if servo_list.0.is_empty() { unsafe { list.set_move(RefPtr::from_addrefed(Gecko_NewNoneTransform())); } } else { gecko_properties::convert_transform(&servo_list.0, list); } } else { panic!("The AnimationValue should be transform"); } } #[no_mangle] pub extern "C" fn Servo_AnimationValue_Transform( list: *const nsCSSValueSharedList ) -> RawServoAnimationValueStrong { let list = unsafe { (&*list).mHead.as_ref() }; let transform = gecko_properties::clone_transform_from_list(list); Arc::new(AnimationValue::Transform(transform)).into_strong() } #[no_mangle] pub extern "C" fn Servo_AnimationValue_DeepEqual(this: RawServoAnimationValueBorrowed, other: RawServoAnimationValueBorrowed) -> bool { let this_value = AnimationValue::as_arc(&this); let other_value = AnimationValue::as_arc(&other); this_value == other_value } #[no_mangle] pub extern "C" fn Servo_AnimationValue_Uncompute( value: RawServoAnimationValueBorrowed, ) -> RawServoDeclarationBlockStrong { let value = AnimationValue::as_arc(&value); let global_style_data = &*GLOBAL_STYLE_DATA; Arc::new(global_style_data.shared_lock.wrap( PropertyDeclarationBlock::with_one(value.uncompute(), Importance::Normal))).into_strong() } // Return the ComputedValues by a base ComputedValues and the rules. fn resolve_rules_for_element_with_context<'a>( element: GeckoElement<'a>, mut context: StyleContext<GeckoElement<'a>>, rules: StrongRuleNode ) -> Arc<ComputedValues> { use style::style_resolver::{PseudoElementResolution, StyleResolverForElement}; // This currently ignores visited styles, which seems acceptable, as // existing browsers don't appear to animate visited styles. let inputs = CascadeInputs { rules: Some(rules), visited_rules: None, }; // Actually `PseudoElementResolution` doesn't matter. StyleResolverForElement::new(element, &mut context, RuleInclusion::All, PseudoElementResolution::IfApplicable) .cascade_style_and_visited_with_default_parents(inputs).0 } #[no_mangle] pub extern "C" fn Servo_StyleSet_GetBaseComputedValuesForElement( raw_style_set: RawServoStyleSetBorrowed, element: RawGeckoElementBorrowed, computed_values: ServoStyleContextBorrowed, snapshots: *const ServoElementSnapshotTable, pseudo_type: CSSPseudoElementType ) -> ServoStyleContextStrong { debug_assert!(!snapshots.is_null()); let computed_values = unsafe { ArcBorrow::from_ref(computed_values) }; let rules = match computed_values.rules { None => return computed_values.clone_arc().into(), Some(ref rules) => rules, }; let doc_data = PerDocumentStyleData::from_ffi(raw_style_set).borrow(); let without_animations_rules = doc_data.stylist.rule_tree().remove_animation_rules(rules); if without_animations_rules == *rules { return computed_values.clone_arc().into(); } let element = GeckoElement(element); let element_data = match element.borrow_data() { Some(data) => data, None => return computed_values.clone_arc().into(), }; if let Some(pseudo) = PseudoElement::from_pseudo_type(pseudo_type) { let styles = &element_data.styles; // This style already doesn't have animations. return styles .pseudos .get(&pseudo) .expect("GetBaseComputedValuesForElement for an unexisting pseudo?") .clone().into(); } let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let shared = create_shared_context(&global_style_data, &guard, &doc_data, TraversalFlags::empty(), unsafe { &*snapshots }); let mut tlc = ThreadLocalStyleContext::new(&shared); let context = StyleContext { shared: &shared, thread_local: &mut tlc, }; resolve_rules_for_element_with_context(element, context, without_animations_rules).into() } #[no_mangle] pub extern "C" fn Servo_StyleSet_GetComputedValuesByAddingAnimation( raw_style_set: RawServoStyleSetBorrowed, element: RawGeckoElementBorrowed, computed_values: ServoStyleContextBorrowed, snapshots: *const ServoElementSnapshotTable, animation_value: RawServoAnimationValueBorrowed, ) -> ServoStyleContextStrong { debug_assert!(!snapshots.is_null()); let computed_values = unsafe { ArcBorrow::from_ref(computed_values) }; let rules = match computed_values.rules { None => return ServoStyleContextStrong::null(), Some(ref rules) => rules, }; let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let uncomputed_value = AnimationValue::as_arc(&animation_value).uncompute(); let doc_data = PerDocumentStyleData::from_ffi(raw_style_set).borrow(); let with_animations_rules = { let guards = StylesheetGuards::same(&guard); let declarations = Arc::new(global_style_data.shared_lock.wrap( PropertyDeclarationBlock::with_one(uncomputed_value, Importance::Normal))); doc_data.stylist .rule_tree() .add_animation_rules_at_transition_level(rules, declarations, &guards) }; let element = GeckoElement(element); if element.borrow_data().is_none() { return ServoStyleContextStrong::null(); } let shared = create_shared_context(&global_style_data, &guard, &doc_data, TraversalFlags::empty(), unsafe { &*snapshots }); let mut tlc: ThreadLocalStyleContext<GeckoElement> = ThreadLocalStyleContext::new(&shared); let context = StyleContext { shared: &shared, thread_local: &mut tlc, }; resolve_rules_for_element_with_context(element, context, with_animations_rules).into() } #[no_mangle] pub extern "C" fn Servo_ComputedValues_ExtractAnimationValue( computed_values: ServoStyleContextBorrowed, property_id: nsCSSPropertyID, ) -> RawServoAnimationValueStrong { let property = match LonghandId::from_nscsspropertyid(property_id) { Ok(longhand) => longhand, Err(()) => return Strong::null(), }; match AnimationValue::from_computed_values(&property, &computed_values) { Some(v) => Arc::new(v).into_strong(), None => Strong::null(), } } #[no_mangle] pub extern "C" fn Servo_Property_IsAnimatable(property: nsCSSPropertyID) -> bool { use style::properties::animated_properties; animated_properties::nscsspropertyid_is_animatable(property) } #[no_mangle] pub extern "C" fn Servo_Property_IsTransitionable(property: nsCSSPropertyID) -> bool { use style::properties::animated_properties; animated_properties::nscsspropertyid_is_transitionable(property) } #[no_mangle] pub extern "C" fn Servo_Property_IsDiscreteAnimatable(property: nsCSSPropertyID) -> bool { match LonghandId::from_nscsspropertyid(property) { Ok(longhand) => longhand.is_discrete_animatable(), Err(()) => return false, } } #[no_mangle] pub extern "C" fn Servo_StyleWorkerThreadCount() -> u32 { STYLE_THREAD_POOL.num_threads as u32 } #[no_mangle] pub extern "C" fn Servo_Element_ClearData(element: RawGeckoElementBorrowed) { unsafe { GeckoElement(element).clear_data() }; } #[no_mangle] pub extern "C" fn Servo_Element_SizeOfExcludingThisAndCVs(malloc_size_of: GeckoMallocSizeOf, malloc_enclosing_size_of: GeckoMallocSizeOf, seen_ptrs: *mut SeenPtrs, element: RawGeckoElementBorrowed) -> usize { let element = GeckoElement(element); let borrow = element.borrow_data(); if let Some(data) = borrow { let have_seen_ptr = move |ptr| { unsafe { Gecko_HaveSeenPtr(seen_ptrs, ptr) } }; let mut ops = MallocSizeOfOps::new(malloc_size_of.unwrap(), Some(malloc_enclosing_size_of.unwrap()), Some(Box::new(have_seen_ptr))); (*data).size_of_excluding_cvs(&mut ops) } else { 0 } } #[no_mangle] pub extern "C" fn Servo_Element_HasPrimaryComputedValues(element: RawGeckoElementBorrowed) -> bool { let element = GeckoElement(element); let data = element.borrow_data().expect("Looking for CVs on unstyled element"); data.has_styles() } #[no_mangle] pub extern "C" fn Servo_Element_GetPrimaryComputedValues(element: RawGeckoElementBorrowed) -> ServoStyleContextStrong { let element = GeckoElement(element); let data = element.borrow_data().expect("Getting CVs on unstyled element"); data.styles.primary().clone().into() } #[no_mangle] pub extern "C" fn Servo_Element_HasPseudoComputedValues(element: RawGeckoElementBorrowed, index: usize) -> bool { let element = GeckoElement(element); let data = element.borrow_data().expect("Looking for CVs on unstyled element"); data.styles.pseudos.as_array()[index].is_some() } #[no_mangle] pub extern "C" fn Servo_Element_GetPseudoComputedValues(element: RawGeckoElementBorrowed, index: usize) -> ServoStyleContextStrong { let element = GeckoElement(element); let data = element.borrow_data().expect("Getting CVs that aren't present"); data.styles.pseudos.as_array()[index].as_ref().expect("Getting CVs that aren't present") .clone().into() } #[no_mangle] pub extern "C" fn Servo_Element_IsDisplayNone(element: RawGeckoElementBorrowed) -> bool { let element = GeckoElement(element); let data = element.borrow_data().expect("Invoking Servo_Element_IsDisplayNone on unstyled element"); data.styles.is_display_none() } #[no_mangle] pub extern "C" fn Servo_Element_IsPrimaryStyleReusedViaRuleNode(element: RawGeckoElementBorrowed) -> bool { let element = GeckoElement(element); let data = element.borrow_data() .expect("Invoking Servo_Element_IsPrimaryStyleReusedViaRuleNode on unstyled element"); data.flags.contains(data::ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE) } #[no_mangle] pub extern "C" fn Servo_StyleSheet_Empty(mode: SheetParsingMode) -> RawServoStyleSheetContentsStrong { let global_style_data = &*GLOBAL_STYLE_DATA; let origin = match mode { SheetParsingMode::eAuthorSheetFeatures => Origin::Author, SheetParsingMode::eUserSheetFeatures => Origin::User, SheetParsingMode::eAgentSheetFeatures => Origin::UserAgent, SheetParsingMode::eSafeAgentSheetFeatures => Origin::UserAgent, }; let shared_lock = &global_style_data.shared_lock; Arc::new( StylesheetContents::from_str( "", unsafe { dummy_url_data() }.clone(), origin, shared_lock, /* loader = */ None, &NullReporter, QuirksMode::NoQuirks, 0 ) ).into_strong() } #[no_mangle] pub extern "C" fn Servo_StyleSheet_FromUTF8Bytes( loader: *mut Loader, stylesheet: *mut ServoStyleSheet, data: *const u8, data_len: usize, mode: SheetParsingMode, extra_data: *mut URLExtraData, line_number_offset: u32, quirks_mode: nsCompatibility, reusable_sheets: *mut LoaderReusableStyleSheets ) -> RawServoStyleSheetContentsStrong { let global_style_data = &*GLOBAL_STYLE_DATA; let input = unsafe { ::std::str::from_utf8_unchecked(::std::slice::from_raw_parts(data, data_len)) }; let origin = match mode { SheetParsingMode::eAuthorSheetFeatures => Origin::Author, SheetParsingMode::eUserSheetFeatures => Origin::User, SheetParsingMode::eAgentSheetFeatures => Origin::UserAgent, SheetParsingMode::eSafeAgentSheetFeatures => Origin::UserAgent, }; let reporter = ErrorReporter::new(stylesheet, loader, extra_data); let url_data = unsafe { RefPtr::from_ptr_ref(&extra_data) }; let loader = if loader.is_null() { None } else { Some(StylesheetLoader::new(loader, stylesheet, reusable_sheets)) }; // FIXME(emilio): loader.as_ref() doesn't typecheck for some reason? let loader: Option<&StyleStylesheetLoader> = match loader { None => None, Some(ref s) => Some(s), }; Arc::new(StylesheetContents::from_str( input, url_data.clone(), origin, &global_style_data.shared_lock, loader, &reporter, quirks_mode.into(), line_number_offset) ).into_strong() } #[no_mangle] pub extern "C" fn Servo_StyleSet_AppendStyleSheet( raw_data: RawServoStyleSetBorrowed, sheet: *const ServoStyleSheet, ) { let global_style_data = &*GLOBAL_STYLE_DATA; let mut data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); let data = &mut *data; let guard = global_style_data.shared_lock.read(); let sheet = unsafe { GeckoStyleSheet::new(sheet) }; data.stylist.append_stylesheet(sheet, &guard); } #[no_mangle] pub extern "C" fn Servo_StyleSet_MediumFeaturesChanged( raw_data: RawServoStyleSetBorrowed, viewport_units_used: *mut bool, ) -> u8 { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); // NOTE(emilio): We don't actually need to flush the stylist here and ensure // it's up to date. // // In case it isn't we would trigger a rebuild + restyle as needed too. // // We need to ensure the default computed values are up to date though, // because those can influence the result of media query evaluation. // // FIXME(emilio, bug 1369984): do the computation conditionally, to do it // less often. let mut data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); unsafe { *viewport_units_used = data.stylist.device().used_viewport_size(); } data.stylist.device_mut().reset_computed_values(); let guards = StylesheetGuards::same(&guard); let origins_in_which_rules_changed = data.stylist.media_features_change_changed_style(&guards); // We'd like to return `OriginFlags` here, but bindgen bitfield enums don't // work as return values with the Linux 32-bit ABI at the moment because // they wrap the value in a struct, so for now just unwrap it. OriginFlags::from(origins_in_which_rules_changed).0 } #[no_mangle] pub extern "C" fn Servo_StyleSet_SetDevice( raw_data: RawServoStyleSetBorrowed, pres_context: RawGeckoPresContextOwned ) -> u8 { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let mut data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); let device = Device::new(pres_context); let guards = StylesheetGuards::same(&guard); let origins_in_which_rules_changed = data.stylist.set_device(device, &guards); // We'd like to return `OriginFlags` here, but bindgen bitfield enums don't // work as return values with the Linux 32-bit ABI at the moment because // they wrap the value in a struct, so for now just unwrap it. OriginFlags::from(origins_in_which_rules_changed).0 } #[no_mangle] pub extern "C" fn Servo_StyleSet_PrependStyleSheet( raw_data: RawServoStyleSetBorrowed, sheet: *const ServoStyleSheet, ) { let global_style_data = &*GLOBAL_STYLE_DATA; let mut data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); let data = &mut *data; let guard = global_style_data.shared_lock.read(); let sheet = unsafe { GeckoStyleSheet::new(sheet) }; data.stylist.prepend_stylesheet(sheet, &guard); } #[no_mangle] pub extern "C" fn Servo_StyleSet_InsertStyleSheetBefore( raw_data: RawServoStyleSetBorrowed, sheet: *const ServoStyleSheet, before_sheet: *const ServoStyleSheet ) { let global_style_data = &*GLOBAL_STYLE_DATA; let mut data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); let data = &mut *data; let guard = global_style_data.shared_lock.read(); let sheet = unsafe { GeckoStyleSheet::new(sheet) }; data.stylist.insert_stylesheet_before( sheet, unsafe { GeckoStyleSheet::new(before_sheet) }, &guard, ); } #[no_mangle] pub extern "C" fn Servo_StyleSet_RemoveStyleSheet( raw_data: RawServoStyleSetBorrowed, sheet: *const ServoStyleSheet ) { let global_style_data = &*GLOBAL_STYLE_DATA; let mut data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); let data = &mut *data; let guard = global_style_data.shared_lock.read(); let sheet = unsafe { GeckoStyleSheet::new(sheet) }; data.stylist.remove_stylesheet(sheet, &guard); } #[no_mangle] pub extern "C" fn Servo_StyleSet_FlushStyleSheets( raw_data: RawServoStyleSetBorrowed, doc_element: RawGeckoElementBorrowedOrNull, ) { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let mut data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); let doc_element = doc_element.map(GeckoElement); let have_invalidations = data.flush_stylesheets(&guard, doc_element); if have_invalidations && doc_element.is_some() { // The invalidation machinery propagates the bits up, but we still // need to tell the gecko restyle root machinery about it. unsafe { bindings::Gecko_NoteDirtySubtreeForInvalidation(doc_element.unwrap().0); } } } #[no_mangle] pub extern "C" fn Servo_StyleSet_NoteStyleSheetsChanged( raw_data: RawServoStyleSetBorrowed, author_style_disabled: bool, changed_origins: OriginFlags, ) { let mut data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); data.stylist.force_stylesheet_origins_dirty(OriginSet::from(changed_origins)); data.stylist.set_author_style_disabled(author_style_disabled); } #[no_mangle] pub extern "C" fn Servo_StyleSheet_HasRules( raw_contents: RawServoStyleSheetContentsBorrowed ) -> bool { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); !StylesheetContents::as_arc(&raw_contents) .rules.read_with(&guard).0.is_empty() } #[no_mangle] pub extern "C" fn Servo_StyleSheet_GetRules( sheet: RawServoStyleSheetContentsBorrowed ) -> ServoCssRulesStrong { StylesheetContents::as_arc(&sheet).rules.clone().into_strong() } #[no_mangle] pub extern "C" fn Servo_StyleSheet_Clone( raw_sheet: RawServoStyleSheetContentsBorrowed, reference_sheet: *const ServoStyleSheet, ) -> RawServoStyleSheetContentsStrong { use style::shared_lock::{DeepCloneParams, DeepCloneWithLock}; let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let contents = StylesheetContents::as_arc(&raw_sheet); let params = DeepCloneParams { reference_sheet }; Arc::new(contents.deep_clone_with_lock( &global_style_data.shared_lock, &guard, &params, )).into_strong() } #[no_mangle] pub extern "C" fn Servo_StyleSheet_SizeOfIncludingThis( malloc_size_of: GeckoMallocSizeOf, malloc_enclosing_size_of: GeckoMallocSizeOf, sheet: RawServoStyleSheetContentsBorrowed ) -> usize { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let mut ops = MallocSizeOfOps::new(malloc_size_of.unwrap(), Some(malloc_enclosing_size_of.unwrap()), None); StylesheetContents::as_arc(&sheet).size_of(&guard, &mut ops) } #[no_mangle] pub extern "C" fn Servo_StyleSheet_GetOrigin( sheet: RawServoStyleSheetContentsBorrowed ) -> u8 { let origin = match StylesheetContents::as_arc(&sheet).origin { Origin::UserAgent => OriginFlags_UserAgent, Origin::User => OriginFlags_User, Origin::Author => OriginFlags_Author, }; // We'd like to return `OriginFlags` here, but bindgen bitfield enums don't // work as return values with the Linux 32-bit ABI at the moment because // they wrap the value in a struct, so for now just unwrap it. origin.0 } #[no_mangle] pub extern "C" fn Servo_StyleSheet_GetSourceMapURL( sheet: RawServoStyleSheetContentsBorrowed, result: *mut nsAString ) { let contents = StylesheetContents::as_arc(&sheet); let url_opt = contents.source_map_url.read(); if let Some(ref url) = *url_opt { write!(unsafe { &mut *result }, "{}", url).unwrap(); } } #[no_mangle] pub extern "C" fn Servo_StyleSheet_GetSourceURL( sheet: RawServoStyleSheetContentsBorrowed, result: *mut nsAString ) { let contents = StylesheetContents::as_arc(&sheet); let url_opt = contents.source_url.read(); if let Some(ref url) = *url_opt { write!(unsafe { &mut *result }, "{}", url).unwrap(); } } fn read_locked_arc<T, R, F>(raw: &<Locked<T> as HasFFI>::FFIType, func: F) -> R where Locked<T>: HasArcFFI, F: FnOnce(&T) -> R { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); func(Locked::<T>::as_arc(&raw).read_with(&guard)) } #[cfg(debug_assertions)] unsafe fn read_locked_arc_unchecked<T, R, F>(raw: &<Locked<T> as HasFFI>::FFIType, func: F) -> R where Locked<T>: HasArcFFI, F: FnOnce(&T) -> R { read_locked_arc(raw, func) } #[cfg(not(debug_assertions))] unsafe fn read_locked_arc_unchecked<T, R, F>(raw: &<Locked<T> as HasFFI>::FFIType, func: F) -> R where Locked<T>: HasArcFFI, F: FnOnce(&T) -> R { func(Locked::<T>::as_arc(&raw).read_unchecked()) } fn write_locked_arc<T, R, F>(raw: &<Locked<T> as HasFFI>::FFIType, func: F) -> R where Locked<T>: HasArcFFI, F: FnOnce(&mut T) -> R { let global_style_data = &*GLOBAL_STYLE_DATA; let mut guard = global_style_data.shared_lock.write(); func(Locked::<T>::as_arc(&raw).write_with(&mut guard)) } #[no_mangle] pub extern "C" fn Servo_CssRules_ListTypes(rules: ServoCssRulesBorrowed, result: nsTArrayBorrowed_uintptr_t) { read_locked_arc(rules, |rules: &CssRules| { let iter = rules.0.iter().map(|rule| rule.rule_type() as usize); let (size, upper) = iter.size_hint(); debug_assert_eq!(size, upper.unwrap()); unsafe { result.set_len(size as u32) }; result.iter_mut().zip(iter).fold((), |_, (r, v)| *r = v); }) } #[no_mangle] pub extern "C" fn Servo_CssRules_InsertRule( rules: ServoCssRulesBorrowed, contents: RawServoStyleSheetContentsBorrowed, rule: *const nsACString, index: u32, nested: bool, loader: *mut Loader, gecko_stylesheet: *mut ServoStyleSheet, rule_type: *mut u16, ) -> nsresult { let loader = if loader.is_null() { None } else { Some(StylesheetLoader::new(loader, gecko_stylesheet, ptr::null_mut())) }; let loader = loader.as_ref().map(|loader| loader as &StyleStylesheetLoader); let rule = unsafe { rule.as_ref().unwrap().as_str_unchecked() }; let global_style_data = &*GLOBAL_STYLE_DATA; let contents = StylesheetContents::as_arc(&contents); let result = Locked::<CssRules>::as_arc(&rules).insert_rule( &global_style_data.shared_lock, rule, contents, index as usize, nested, loader ); match result { Ok(new_rule) => { *unsafe { rule_type.as_mut().unwrap() } = new_rule.rule_type() as u16; nsresult::NS_OK } Err(err) => err.into(), } } #[no_mangle] pub extern "C" fn Servo_CssRules_DeleteRule( rules: ServoCssRulesBorrowed, index: u32 ) -> nsresult { write_locked_arc(rules, |rules: &mut CssRules| { match rules.remove_rule(index as usize) { Ok(_) => nsresult::NS_OK, Err(err) => err.into() } }) } macro_rules! impl_basic_rule_funcs_without_getter { { ($rule_type:ty, $raw_type:ty), debug: $debug:ident, to_css: $to_css:ident, } => { #[no_mangle] pub extern "C" fn $debug(rule: &$raw_type, result: *mut nsACString) { read_locked_arc(rule, |rule: &$rule_type| { write!(unsafe { result.as_mut().unwrap() }, "{:?}", *rule).unwrap(); }) } #[no_mangle] pub extern "C" fn $to_css(rule: &$raw_type, result: *mut nsAString) { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let rule = Locked::<$rule_type>::as_arc(&rule); rule.read_with(&guard).to_css(&guard, unsafe { result.as_mut().unwrap() }).unwrap(); } } } macro_rules! impl_basic_rule_funcs { { ($name:ident, $rule_type:ty, $raw_type:ty), getter: $getter:ident, debug: $debug:ident, to_css: $to_css:ident, } => { #[no_mangle] pub extern "C" fn $getter(rules: ServoCssRulesBorrowed, index: u32, line: *mut u32, column: *mut u32) -> Strong<$raw_type> { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let rules = Locked::<CssRules>::as_arc(&rules).read_with(&guard); let index = index as usize; if index >= rules.0.len() { return Strong::null(); } match rules.0[index] { CssRule::$name(ref rule) => { let location = rule.read_with(&guard).source_location; *unsafe { line.as_mut().unwrap() } = location.line as u32; *unsafe { column.as_mut().unwrap() } = location.column as u32; rule.clone().into_strong() }, _ => { Strong::null() } } } impl_basic_rule_funcs_without_getter! { ($rule_type, $raw_type), debug: $debug, to_css: $to_css, } } } macro_rules! impl_group_rule_funcs { { ($name:ident, $rule_type:ty, $raw_type:ty), get_rules: $get_rules:ident, $($basic:tt)+ } => { impl_basic_rule_funcs! { ($name, $rule_type, $raw_type), $($basic)+ } #[no_mangle] pub extern "C" fn $get_rules(rule: &$raw_type) -> ServoCssRulesStrong { read_locked_arc(rule, |rule: &$rule_type| { rule.rules.clone().into_strong() }) } } } impl_basic_rule_funcs! { (Style, StyleRule, RawServoStyleRule), getter: Servo_CssRules_GetStyleRuleAt, debug: Servo_StyleRule_Debug, to_css: Servo_StyleRule_GetCssText, } impl_basic_rule_funcs! { (Import, ImportRule, RawServoImportRule), getter: Servo_CssRules_GetImportRuleAt, debug: Servo_ImportRule_Debug, to_css: Servo_ImportRule_GetCssText, } impl_basic_rule_funcs_without_getter! { (Keyframe, RawServoKeyframe), debug: Servo_Keyframe_Debug, to_css: Servo_Keyframe_GetCssText, } impl_basic_rule_funcs! { (Keyframes, KeyframesRule, RawServoKeyframesRule), getter: Servo_CssRules_GetKeyframesRuleAt, debug: Servo_KeyframesRule_Debug, to_css: Servo_KeyframesRule_GetCssText, } impl_group_rule_funcs! { (Media, MediaRule, RawServoMediaRule), get_rules: Servo_MediaRule_GetRules, getter: Servo_CssRules_GetMediaRuleAt, debug: Servo_MediaRule_Debug, to_css: Servo_MediaRule_GetCssText, } impl_basic_rule_funcs! { (Namespace, NamespaceRule, RawServoNamespaceRule), getter: Servo_CssRules_GetNamespaceRuleAt, debug: Servo_NamespaceRule_Debug, to_css: Servo_NamespaceRule_GetCssText, } impl_basic_rule_funcs! { (Page, PageRule, RawServoPageRule), getter: Servo_CssRules_GetPageRuleAt, debug: Servo_PageRule_Debug, to_css: Servo_PageRule_GetCssText, } impl_group_rule_funcs! { (Supports, SupportsRule, RawServoSupportsRule), get_rules: Servo_SupportsRule_GetRules, getter: Servo_CssRules_GetSupportsRuleAt, debug: Servo_SupportsRule_Debug, to_css: Servo_SupportsRule_GetCssText, } impl_group_rule_funcs! { (Document, DocumentRule, RawServoDocumentRule), get_rules: Servo_DocumentRule_GetRules, getter: Servo_CssRules_GetDocumentRuleAt, debug: Servo_DocumentRule_Debug, to_css: Servo_DocumentRule_GetCssText, } impl_basic_rule_funcs! { (FontFeatureValues, FontFeatureValuesRule, RawServoFontFeatureValuesRule), getter: Servo_CssRules_GetFontFeatureValuesRuleAt, debug: Servo_FontFeatureValuesRule_Debug, to_css: Servo_FontFeatureValuesRule_GetCssText, } macro_rules! impl_getter_for_embedded_rule { ($getter:ident: $name:ident -> $ty:ty) => { #[no_mangle] pub extern "C" fn $getter(rules: ServoCssRulesBorrowed, index: u32) -> *mut $ty { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let rules = Locked::<CssRules>::as_arc(&rules).read_with(&guard); match rules.0[index as usize] { CssRule::$name(ref rule) => rule.read_with(&guard).get(), _ => unreachable!(concat!(stringify!($getter), " should only be called on a ", stringify!($name), " rule")), } } } } impl_getter_for_embedded_rule!(Servo_CssRules_GetFontFaceRuleAt: FontFace -> nsCSSFontFaceRule); impl_getter_for_embedded_rule!(Servo_CssRules_GetCounterStyleRuleAt: CounterStyle -> nsCSSCounterStyleRule); #[no_mangle] pub extern "C" fn Servo_StyleRule_GetStyle(rule: RawServoStyleRuleBorrowed) -> RawServoDeclarationBlockStrong { read_locked_arc(rule, |rule: &StyleRule| { rule.block.clone().into_strong() }) } #[no_mangle] pub extern "C" fn Servo_StyleRule_SetStyle(rule: RawServoStyleRuleBorrowed, declarations: RawServoDeclarationBlockBorrowed) { let declarations = Locked::<PropertyDeclarationBlock>::as_arc(&declarations); write_locked_arc(rule, |rule: &mut StyleRule| { rule.block = declarations.clone_arc(); }) } #[no_mangle] pub extern "C" fn Servo_StyleRule_GetSelectorText(rule: RawServoStyleRuleBorrowed, result: *mut nsAString) { read_locked_arc(rule, |rule: &StyleRule| { rule.selectors.to_css(unsafe { result.as_mut().unwrap() }).unwrap(); }) } #[no_mangle] pub extern "C" fn Servo_StyleRule_GetSelectorTextAtIndex(rule: RawServoStyleRuleBorrowed, index: u32, result: *mut nsAString) { read_locked_arc(rule, |rule: &StyleRule| { let index = index as usize; if index >= rule.selectors.0.len() { return; } rule.selectors.0[index].to_css(unsafe { result.as_mut().unwrap() }).unwrap(); }) } #[no_mangle] pub extern "C" fn Servo_StyleRule_GetSelectorCount(rule: RawServoStyleRuleBorrowed, count: *mut u32) { read_locked_arc(rule, |rule: &StyleRule| { *unsafe { count.as_mut().unwrap() } = rule.selectors.0.len() as u32; }) } #[no_mangle] pub extern "C" fn Servo_StyleRule_GetSpecificityAtIndex( rule: RawServoStyleRuleBorrowed, index: u32, specificity: *mut u64 ) { read_locked_arc(rule, |rule: &StyleRule| { let specificity = unsafe { specificity.as_mut().unwrap() }; let index = index as usize; if index >= rule.selectors.0.len() { *specificity = 0; return; } *specificity = rule.selectors.0[index].specificity() as u64; }) } #[no_mangle] pub extern "C" fn Servo_StyleRule_SelectorMatchesElement(rule: RawServoStyleRuleBorrowed, element: RawGeckoElementBorrowed, index: u32, pseudo_type: CSSPseudoElementType) -> bool { read_locked_arc(rule, |rule: &StyleRule| { let index = index as usize; if index >= rule.selectors.0.len() { return false; } let selector = &rule.selectors.0[index]; let mut matching_mode = MatchingMode::Normal; match PseudoElement::from_pseudo_type(pseudo_type) { Some(pseudo) => { // We need to make sure that the requested pseudo element type // matches the selector pseudo element type before proceeding. match selector.pseudo_element() { Some(selector_pseudo) if *selector_pseudo == pseudo => { matching_mode = MatchingMode::ForStatelessPseudoElement }, _ => return false, }; }, None => { // Do not attempt to match if a pseudo element is requested and // this is not a pseudo element selector, or vice versa. if selector.has_pseudo_element() { return false; } }, }; let element = GeckoElement(element); let quirks_mode = element.as_node().owner_doc().quirks_mode(); let mut ctx = MatchingContext::new(matching_mode, None, None, quirks_mode); matches_selector(selector, 0, None, &element, &mut ctx, &mut |_, _| {}) }) } #[no_mangle] pub unsafe extern "C" fn Servo_SelectorList_Closest( element: RawGeckoElementBorrowed, selectors: RawServoSelectorListBorrowed, ) -> *const structs::RawGeckoElement { use std::borrow::Borrow; use style::dom_apis; let element = GeckoElement(element); let quirks_mode = element.as_node().owner_doc().quirks_mode(); let selectors = ::selectors::SelectorList::from_ffi(selectors).borrow(); dom_apis::element_closest(element, &selectors, quirks_mode) .map_or(ptr::null(), |e| e.0) } #[no_mangle] pub unsafe extern "C" fn Servo_SelectorList_Matches( element: RawGeckoElementBorrowed, selectors: RawServoSelectorListBorrowed, ) -> bool { use std::borrow::Borrow; use style::dom_apis; let element = GeckoElement(element); let quirks_mode = element.as_node().owner_doc().quirks_mode(); let selectors = ::selectors::SelectorList::from_ffi(selectors).borrow(); dom_apis::element_matches( &element, &selectors, quirks_mode, ) } #[no_mangle] pub unsafe extern "C" fn Servo_SelectorList_QueryFirst( node: RawGeckoNodeBorrowed, selectors: RawServoSelectorListBorrowed, may_use_invalidation: bool, ) -> *const structs::RawGeckoElement { use std::borrow::Borrow; use style::dom_apis::{self, MayUseInvalidation, QueryFirst}; let node = GeckoNode(node); let selectors = ::selectors::SelectorList::from_ffi(selectors).borrow(); let mut result = None; let may_use_invalidation = if may_use_invalidation { MayUseInvalidation::Yes } else { MayUseInvalidation::No }; dom_apis::query_selector::<GeckoElement, QueryFirst>( node, &selectors, &mut result, may_use_invalidation, ); result.map_or(ptr::null(), |e| e.0) } #[no_mangle] pub unsafe extern "C" fn Servo_SelectorList_QueryAll( node: RawGeckoNodeBorrowed, selectors: RawServoSelectorListBorrowed, content_list: *mut structs::nsSimpleContentList, may_use_invalidation: bool, ) { use smallvec::SmallVec; use std::borrow::Borrow; use style::dom_apis::{self, MayUseInvalidation, QueryAll}; let node = GeckoNode(node); let selectors = ::selectors::SelectorList::from_ffi(selectors).borrow(); let mut result = SmallVec::new(); let may_use_invalidation = if may_use_invalidation { MayUseInvalidation::Yes } else { MayUseInvalidation::No }; dom_apis::query_selector::<GeckoElement, QueryAll>( node, &selectors, &mut result, may_use_invalidation, ); if !result.is_empty() { // NOTE(emilio): This relies on a slice of GeckoElement having the same // memory representation than a slice of element pointers. bindings::Gecko_ContentList_AppendAll( content_list, result.as_ptr() as *mut *const _, result.len(), ) } } #[no_mangle] pub extern "C" fn Servo_ImportRule_GetHref(rule: RawServoImportRuleBorrowed, result: *mut nsAString) { read_locked_arc(rule, |rule: &ImportRule| { write!(unsafe { &mut *result }, "{}", rule.url.as_str()).unwrap(); }) } #[no_mangle] pub extern "C" fn Servo_ImportRule_GetSheet( rule: RawServoImportRuleBorrowed ) -> *const ServoStyleSheet { read_locked_arc(rule, |rule: &ImportRule| { rule.stylesheet.0.raw() as *const ServoStyleSheet }) } #[no_mangle] pub extern "C" fn Servo_Keyframe_GetKeyText( keyframe: RawServoKeyframeBorrowed, result: *mut nsAString ) { read_locked_arc(keyframe, |keyframe: &Keyframe| { keyframe.selector.to_css(unsafe { result.as_mut().unwrap() }).unwrap() }) } #[no_mangle] pub extern "C" fn Servo_Keyframe_SetKeyText(keyframe: RawServoKeyframeBorrowed, text: *const nsACString) -> bool { let text = unsafe { text.as_ref().unwrap().as_str_unchecked() }; let mut input = ParserInput::new(&text); if let Ok(selector) = Parser::new(&mut input).parse_entirely(KeyframeSelector::parse) { write_locked_arc(keyframe, |keyframe: &mut Keyframe| { keyframe.selector = selector; }); true } else { false } } #[no_mangle] pub extern "C" fn Servo_Keyframe_GetStyle(keyframe: RawServoKeyframeBorrowed) -> RawServoDeclarationBlockStrong { read_locked_arc(keyframe, |keyframe: &Keyframe| keyframe.block.clone().into_strong()) } #[no_mangle] pub extern "C" fn Servo_Keyframe_SetStyle(keyframe: RawServoKeyframeBorrowed, declarations: RawServoDeclarationBlockBorrowed) { let declarations = Locked::<PropertyDeclarationBlock>::as_arc(&declarations); write_locked_arc(keyframe, |keyframe: &mut Keyframe| { keyframe.block = declarations.clone_arc(); }) } #[no_mangle] pub extern "C" fn Servo_KeyframesRule_GetName(rule: RawServoKeyframesRuleBorrowed) -> *mut nsAtom { read_locked_arc(rule, |rule: &KeyframesRule| rule.name.as_atom().as_ptr()) } #[no_mangle] pub extern "C" fn Servo_KeyframesRule_SetName(rule: RawServoKeyframesRuleBorrowed, name: *mut nsAtom) { write_locked_arc(rule, |rule: &mut KeyframesRule| { rule.name = KeyframesName::Ident(CustomIdent(unsafe { Atom::from_addrefed(name) })); }) } #[no_mangle] pub extern "C" fn Servo_KeyframesRule_GetCount(rule: RawServoKeyframesRuleBorrowed) -> u32 { read_locked_arc(rule, |rule: &KeyframesRule| rule.keyframes.len() as u32) } #[no_mangle] pub extern "C" fn Servo_KeyframesRule_GetKeyframeAt(rule: RawServoKeyframesRuleBorrowed, index: u32, line: *mut u32, column: *mut u32) -> RawServoKeyframeStrong { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let key = Locked::<KeyframesRule>::as_arc(&rule).read_with(&guard) .keyframes[index as usize].clone(); let location = key.read_with(&guard).source_location; *unsafe { line.as_mut().unwrap() } = location.line as u32; *unsafe { column.as_mut().unwrap() } = location.column as u32; key.into_strong() } #[no_mangle] pub extern "C" fn Servo_KeyframesRule_FindRule(rule: RawServoKeyframesRuleBorrowed, key: *const nsACString) -> u32 { let key = unsafe { key.as_ref().unwrap().as_str_unchecked() }; let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); Locked::<KeyframesRule>::as_arc(&rule).read_with(&guard) .find_rule(&guard, key).map(|index| index as u32) .unwrap_or(u32::max_value()) } #[no_mangle] pub extern "C" fn Servo_KeyframesRule_AppendRule( rule: RawServoKeyframesRuleBorrowed, contents: RawServoStyleSheetContentsBorrowed, css: *const nsACString ) -> bool { let css = unsafe { css.as_ref().unwrap().as_str_unchecked() }; let contents = StylesheetContents::as_arc(&contents); let global_style_data = &*GLOBAL_STYLE_DATA; match Keyframe::parse(css, &contents, &global_style_data.shared_lock) { Ok(keyframe) => { write_locked_arc(rule, |rule: &mut KeyframesRule| { rule.keyframes.push(keyframe); }); true } Err(..) => false, } } #[no_mangle] pub extern "C" fn Servo_KeyframesRule_DeleteRule(rule: RawServoKeyframesRuleBorrowed, index: u32) { write_locked_arc(rule, |rule: &mut KeyframesRule| { rule.keyframes.remove(index as usize); }) } #[no_mangle] pub extern "C" fn Servo_MediaRule_GetMedia(rule: RawServoMediaRuleBorrowed) -> RawServoMediaListStrong { read_locked_arc(rule, |rule: &MediaRule| { rule.media_queries.clone().into_strong() }) } #[no_mangle] pub extern "C" fn Servo_NamespaceRule_GetPrefix(rule: RawServoNamespaceRuleBorrowed) -> *mut nsAtom { read_locked_arc(rule, |rule: &NamespaceRule| { rule.prefix.as_ref().unwrap_or(&atom!("")).as_ptr() }) } #[no_mangle] pub extern "C" fn Servo_NamespaceRule_GetURI(rule: RawServoNamespaceRuleBorrowed) -> *mut nsAtom { read_locked_arc(rule, |rule: &NamespaceRule| rule.url.0.as_ptr()) } #[no_mangle] pub extern "C" fn Servo_PageRule_GetStyle(rule: RawServoPageRuleBorrowed) -> RawServoDeclarationBlockStrong { read_locked_arc(rule, |rule: &PageRule| { rule.block.clone().into_strong() }) } #[no_mangle] pub extern "C" fn Servo_PageRule_SetStyle(rule: RawServoPageRuleBorrowed, declarations: RawServoDeclarationBlockBorrowed) { let declarations = Locked::<PropertyDeclarationBlock>::as_arc(&declarations); write_locked_arc(rule, |rule: &mut PageRule| { rule.block = declarations.clone_arc(); }) } #[no_mangle] pub extern "C" fn Servo_SupportsRule_GetConditionText(rule: RawServoSupportsRuleBorrowed, result: *mut nsAString) { read_locked_arc(rule, |rule: &SupportsRule| { rule.condition.to_css(unsafe { result.as_mut().unwrap() }).unwrap(); }) } #[no_mangle] pub extern "C" fn Servo_DocumentRule_GetConditionText(rule: RawServoDocumentRuleBorrowed, result: *mut nsAString) { read_locked_arc(rule, |rule: &DocumentRule| { rule.condition.to_css(unsafe { result.as_mut().unwrap() }).unwrap(); }) } #[no_mangle] pub extern "C" fn Servo_FontFeatureValuesRule_GetFontFamily(rule: RawServoFontFeatureValuesRuleBorrowed, result: *mut nsAString) { read_locked_arc(rule, |rule: &FontFeatureValuesRule| { rule.font_family_to_css(unsafe { result.as_mut().unwrap() }).unwrap(); }) } #[no_mangle] pub extern "C" fn Servo_FontFeatureValuesRule_GetValueText(rule: RawServoFontFeatureValuesRuleBorrowed, result: *mut nsAString) { read_locked_arc(rule, |rule: &FontFeatureValuesRule| { rule.value_to_css(unsafe { result.as_mut().unwrap() }).unwrap(); }) } #[no_mangle] pub extern "C" fn Servo_ComputedValues_GetForAnonymousBox(parent_style_or_null: ServoStyleContextBorrowedOrNull, pseudo_tag: *mut nsAtom, raw_data: RawServoStyleSetBorrowed) -> ServoStyleContextStrong { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let guards = StylesheetGuards::same(&guard); let data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); let atom = Atom::from(pseudo_tag); let pseudo = PseudoElement::from_anon_box_atom(&atom) .expect("Not an anon box pseudo?"); let mut cascade_flags = CascadeFlags::SKIP_ROOT_AND_ITEM_BASED_DISPLAY_FIXUP; if pseudo.is_fieldset_content() { cascade_flags.insert(CascadeFlags::IS_FIELDSET_CONTENT); } let metrics = get_metrics_provider_for_product(); // If the pseudo element is PageContent, we should append the precomputed // pseudo element declerations with specified page rules. let page_decls = match pseudo { PseudoElement::PageContent => { let mut declarations = vec![]; let iter = data.stylist.iter_extra_data_origins_rev(); for (data, origin) in iter { let level = match origin { Origin::UserAgent => CascadeLevel::UANormal, Origin::User => CascadeLevel::UserNormal, Origin::Author => CascadeLevel::AuthorNormal, }; for rule in data.pages.iter() { declarations.push(ApplicableDeclarationBlock::from_declarations( rule.read_with(level.guard(&guards)).block.clone(), level )); } } Some(declarations) }, _ => None, }; let rule_node = data.stylist.rule_node_for_precomputed_pseudo( &guards, &pseudo, page_decls, ); data.stylist.precomputed_values_for_pseudo_with_rule_node( &guards, &pseudo, parent_style_or_null.map(|x| &*x), cascade_flags, &metrics, &rule_node ).into() } #[no_mangle] pub extern "C" fn Servo_ResolvePseudoStyle(element: RawGeckoElementBorrowed, pseudo_type: CSSPseudoElementType, is_probe: bool, inherited_style: ServoStyleContextBorrowedOrNull, raw_data: RawServoStyleSetBorrowed) -> ServoStyleContextStrong { let element = GeckoElement(element); let doc_data = PerDocumentStyleData::from_ffi(raw_data).borrow(); debug!("Servo_ResolvePseudoStyle: {:?} {:?}, is_probe: {}", element, PseudoElement::from_pseudo_type(pseudo_type), is_probe); let data = element.borrow_data(); let data = match data.as_ref() { Some(data) if data.has_styles() => data, _ => { // FIXME(bholley, emilio): Assert against this. // // Known offender is nsMathMLmoFrame::MarkIntrinsicISizesDirty, // which goes and does a bunch of work involving style resolution. // // Bug 1403865 tracks fixing it, and potentially adding an assert // here instead. warn!("Calling Servo_ResolvePseudoStyle on unstyled element"); return if is_probe { Strong::null() } else { doc_data.default_computed_values().clone().into() }; } }; let pseudo = PseudoElement::from_pseudo_type(pseudo_type) .expect("ResolvePseudoStyle with a non-pseudo?"); let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let style = get_pseudo_style( &guard, element, &pseudo, RuleInclusion::All, &data.styles, inherited_style, &*doc_data, is_probe, /* matching_func = */ None, ); match style { Some(s) => s.into(), None => { debug_assert!(is_probe); Strong::null() } } } fn debug_atom_array(atoms: &AtomArray) -> String { let mut result = String::from("["); for atom in atoms.iter() { if atom.mRawPtr.is_null() { result += "(null), "; } else { let atom = unsafe { WeakAtom::new(atom.mRawPtr) }; write!(result, "{}, ", atom).unwrap(); } } result.push(']'); result } #[no_mangle] pub extern "C" fn Servo_ComputedValues_ResolveXULTreePseudoStyle( element: RawGeckoElementBorrowed, pseudo_tag: *mut nsAtom, inherited_style: ServoStyleContextBorrowed, input_word: *const AtomArray, raw_data: RawServoStyleSetBorrowed ) -> ServoStyleContextStrong { let element = GeckoElement(element); let data = element.borrow_data() .expect("Calling ResolveXULTreePseudoStyle on unstyled element?"); let pseudo = unsafe { Atom::with(pseudo_tag, |atom| { PseudoElement::from_tree_pseudo_atom(atom, Box::new([])) }).expect("ResolveXULTreePseudoStyle with a non-tree pseudo?") }; let input_word = unsafe { input_word.as_ref().unwrap() }; let doc_data = PerDocumentStyleData::from_ffi(raw_data).borrow(); debug!("ResolveXULTreePseudoStyle: {:?} {:?} {}", element, pseudo, debug_atom_array(input_word)); let matching_fn = |pseudo: &PseudoElement| { let args = pseudo.tree_pseudo_args().expect("Not a tree pseudo-element?"); args.iter().all(|atom| { input_word.iter().any(|item| atom.as_ptr() == item.mRawPtr) }) }; let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); get_pseudo_style( &guard, element, &pseudo, RuleInclusion::All, &data.styles, Some(inherited_style), &*doc_data, /* is_probe = */ false, Some(&matching_fn), ).unwrap().into() } #[no_mangle] pub extern "C" fn Servo_SetExplicitStyle(element: RawGeckoElementBorrowed, style: ServoStyleContextBorrowed) { let element = GeckoElement(element); debug!("Servo_SetExplicitStyle: {:?}", element); // We only support this API for initial styling. There's no reason it couldn't // work for other things, we just haven't had a reason to do so. debug_assert!(element.get_data().is_none()); let mut data = unsafe { element.ensure_data() }; data.styles.primary = Some(unsafe { ArcBorrow::from_ref(style) }.clone_arc()); } #[no_mangle] pub extern "C" fn Servo_HasAuthorSpecifiedRules(style: ServoStyleContextBorrowed, element: RawGeckoElementBorrowed, pseudo_type: CSSPseudoElementType, rule_type_mask: u32, author_colors_allowed: bool) -> bool { let element = GeckoElement(element); let pseudo = PseudoElement::from_pseudo_type(pseudo_type); let guard = (*GLOBAL_STYLE_DATA).shared_lock.read(); let guards = StylesheetGuards::same(&guard); style.rules().has_author_specified_rules(element, pseudo, &guards, rule_type_mask, author_colors_allowed) } fn get_pseudo_style( guard: &SharedRwLockReadGuard, element: GeckoElement, pseudo: &PseudoElement, rule_inclusion: RuleInclusion, styles: &ElementStyles, inherited_styles: Option<&ComputedValues>, doc_data: &PerDocumentStyleDataImpl, is_probe: bool, matching_func: Option<&Fn(&PseudoElement) -> bool>, ) -> Option<Arc<ComputedValues>> { let style = match pseudo.cascade_type() { PseudoElementCascadeType::Eager => { match *pseudo { PseudoElement::FirstLetter => { styles.pseudos.get(&pseudo).and_then(|pseudo_styles| { // inherited_styles can be None when doing lazy resolution // (e.g. for computed style) or when probing. In that case // we just inherit from our element, which is what Gecko // does in that situation. What should actually happen in // the computed style case is a bit unclear. let inherited_styles = inherited_styles.unwrap_or(styles.primary()); let guards = StylesheetGuards::same(guard); let metrics = get_metrics_provider_for_product(); let inputs = CascadeInputs::new_from_style(pseudo_styles); doc_data.stylist .compute_pseudo_element_style_with_inputs( &inputs, pseudo, &guards, inherited_styles, &metrics ) }) }, _ => { // Unfortunately, we can't assert that inherited_styles, if // present, is pointer-equal to styles.primary(), or even // equal in any meaningful way. The way it can fail is as // follows. Say we append an element with a ::before, // ::after, or ::first-line to a parent with a ::first-line, // such that the element ends up on the first line of the // parent (e.g. it's an inline-block in the case it has a // ::first-line, or any container in the ::before/::after // cases). Then gecko will update its frame's style to // inherit from the parent's ::first-line. The next time we // try to get the ::before/::after/::first-line style for // the kid, we'll likely pass in the frame's style as // inherited_styles, but that's not pointer-identical to // styles.primary(), because it got reparented. // // Now in practice this turns out to be OK, because all the // cases in which there's a mismatch go ahead and reparent // styles again as needed to make sure the ::first-line // affects all the things it should affect. But it makes it // impossible to assert anything about the two styles // matching here, unfortunately. styles.pseudos.get(&pseudo).cloned() }, } } PseudoElementCascadeType::Precomputed => unreachable!("No anonymous boxes"), PseudoElementCascadeType::Lazy => { debug_assert!(inherited_styles.is_none() || ptr::eq(inherited_styles.unwrap(), &**styles.primary())); let base = if pseudo.inherits_from_default_values() { doc_data.default_computed_values() } else { styles.primary() }; let guards = StylesheetGuards::same(guard); let metrics = get_metrics_provider_for_product(); doc_data.stylist .lazily_compute_pseudo_element_style( &guards, &element, &pseudo, rule_inclusion, base, is_probe, &metrics, matching_func, ) }, }; if is_probe { return style; } Some(style.unwrap_or_else(|| { StyleBuilder::for_inheritance( doc_data.stylist.device(), styles.primary(), Some(pseudo), ).build() })) } #[no_mangle] pub extern "C" fn Servo_ComputedValues_Inherit( raw_data: RawServoStyleSetBorrowed, pseudo_tag: *mut nsAtom, parent_style_context: ServoStyleContextBorrowedOrNull, target: structs::InheritTarget ) -> ServoStyleContextStrong { let data = PerDocumentStyleData::from_ffi(raw_data).borrow(); let for_text = target == structs::InheritTarget::Text; let atom = Atom::from(pseudo_tag); let pseudo = PseudoElement::from_anon_box_atom(&atom) .expect("Not an anon-box? Gah!"); let style = if let Some(reference) = parent_style_context { let mut style = StyleBuilder::for_inheritance( data.stylist.device(), reference, Some(&pseudo) ); if for_text { StyleAdjuster::new(&mut style) .adjust_for_text(); } style.build() } else { debug_assert!(!for_text); StyleBuilder::for_derived_style( data.stylist.device(), data.default_computed_values(), /* parent_style = */ None, Some(&pseudo), ).build() }; style.into() } #[no_mangle] pub extern "C" fn Servo_ComputedValues_GetStyleBits(values: ServoStyleContextBorrowed) -> u64 { use style::properties::computed_value_flags::ComputedValueFlags; // FIXME(emilio): We could do this more efficiently I'm quite sure. let flags = values.flags; let mut result = 0; if flags.contains(ComputedValueFlags::IS_RELEVANT_LINK_VISITED) { result |= structs::NS_STYLE_RELEVANT_LINK_VISITED as u64; } if flags.contains(ComputedValueFlags::HAS_TEXT_DECORATION_LINES) { result |= structs::NS_STYLE_HAS_TEXT_DECORATION_LINES as u64; } if flags.contains(ComputedValueFlags::SHOULD_SUPPRESS_LINEBREAK) { result |= structs::NS_STYLE_SUPPRESS_LINEBREAK as u64; } if flags.contains(ComputedValueFlags::IS_TEXT_COMBINED) { result |= structs::NS_STYLE_IS_TEXT_COMBINED as u64; } if flags.contains(ComputedValueFlags::IS_IN_PSEUDO_ELEMENT_SUBTREE) { result |= structs::NS_STYLE_HAS_PSEUDO_ELEMENT_DATA as u64; } if flags.contains(ComputedValueFlags::IS_IN_DISPLAY_NONE_SUBTREE) { result |= structs::NS_STYLE_IN_DISPLAY_NONE_SUBTREE as u64; } result } #[no_mangle] pub extern "C" fn Servo_ComputedValues_SpecifiesAnimationsOrTransitions(values: ServoStyleContextBorrowed) -> bool { let b = values.get_box(); b.specifies_animations() || b.specifies_transitions() } #[no_mangle] pub extern "C" fn Servo_ComputedValues_EqualCustomProperties( first: ServoComputedDataBorrowed, second: ServoComputedDataBorrowed ) -> bool { first.custom_properties == second.custom_properties } #[no_mangle] pub extern "C" fn Servo_ComputedValues_GetStyleRuleList(values: ServoStyleContextBorrowed, rules: RawGeckoServoStyleRuleListBorrowedMut) { use smallvec::SmallVec; let rule_node = match values.rules { Some(ref r) => r, None => return, }; let mut result = SmallVec::<[_; 10]>::new(); for node in rule_node.self_and_ancestors() { let style_rule = match *node.style_source() { StyleSource::Style(ref rule) => rule, _ => continue, }; // For the rules with any important declaration, we insert them into // rule tree twice, one for normal level and another for important // level. So, we skip the important one to keep the specificity order of // rules. if node.importance().important() { continue; } result.push(style_rule); } unsafe { rules.set_len(result.len() as u32) }; for (ref src, ref mut dest) in result.into_iter().zip(rules.iter_mut()) { src.with_raw_offset_arc(|arc| { **dest = *Locked::<StyleRule>::arc_as_borrowed(arc); }) } } /// See the comment in `Device` to see why it's ok to pass an owned reference to /// the pres context (hint: the context outlives the StyleSet, that holds the /// device alive). #[no_mangle] pub extern "C" fn Servo_StyleSet_Init(pres_context: RawGeckoPresContextOwned) -> *mut RawServoStyleSet { let data = Box::new(PerDocumentStyleData::new(pres_context)); Box::into_raw(data) as *mut RawServoStyleSet } #[no_mangle] pub extern "C" fn Servo_StyleSet_RebuildCachedData(raw_data: RawServoStyleSetBorrowed) { let mut data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); data.stylist.device_mut().rebuild_cached_data(); } #[no_mangle] pub extern "C" fn Servo_StyleSet_Drop(data: RawServoStyleSetOwned) { let _ = data.into_box::<PerDocumentStyleData>(); } /// Updating the stylesheets and redoing selector matching is always happens /// before the document element is inserted. Therefore we don't need to call /// `force_dirty` here. #[no_mangle] pub extern "C" fn Servo_StyleSet_CompatModeChanged(raw_data: RawServoStyleSetBorrowed) { let mut data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); let quirks_mode = unsafe { (*data.stylist.device().pres_context().mDocument.raw::<nsIDocument>()) .mCompatMode }; data.stylist.set_quirks_mode(quirks_mode.into()); } fn parse_property_into<R>( declarations: &mut SourcePropertyDeclaration, property_id: PropertyId, value: *const nsACString, data: *mut URLExtraData, parsing_mode: structs::ParsingMode, quirks_mode: QuirksMode, reporter: &R ) -> Result<(), ()> where R: ParseErrorReporter { use style_traits::ParsingMode; let value = unsafe { value.as_ref().unwrap().as_str_unchecked() }; let url_data = unsafe { RefPtr::from_ptr_ref(&data) }; let parsing_mode = ParsingMode::from_bits_truncate(parsing_mode); parse_one_declaration_into( declarations, property_id, value, url_data, reporter, parsing_mode, quirks_mode) } #[no_mangle] pub extern "C" fn Servo_ParseProperty( property: nsCSSPropertyID, value: *const nsACString, data: *mut URLExtraData, parsing_mode: structs::ParsingMode, quirks_mode: nsCompatibility, loader: *mut Loader, ) -> RawServoDeclarationBlockStrong { let id = get_property_id_from_nscsspropertyid!(property, RawServoDeclarationBlockStrong::null()); let mut declarations = SourcePropertyDeclaration::new(); let reporter = ErrorReporter::new(ptr::null_mut(), loader, data); match parse_property_into(&mut declarations, id, value, data, parsing_mode, quirks_mode.into(), &reporter) { Ok(()) => { let global_style_data = &*GLOBAL_STYLE_DATA; let mut block = PropertyDeclarationBlock::new(); block.extend( declarations.drain(), Importance::Normal, DeclarationSource::CssOm, ); Arc::new(global_style_data.shared_lock.wrap(block)).into_strong() } Err(_) => RawServoDeclarationBlockStrong::null() } } #[no_mangle] pub extern "C" fn Servo_ParseEasing( easing: *const nsAString, data: *mut URLExtraData, output: nsTimingFunctionBorrowedMut ) -> bool { use style::properties::longhands::transition_timing_function; // FIXME Dummy URL data would work fine here. let url_data = unsafe { RefPtr::from_ptr_ref(&data) }; let context = ParserContext::new(Origin::Author, url_data, Some(CssRuleType::Style), ParsingMode::DEFAULT, QuirksMode::NoQuirks); let easing = unsafe { (*easing).to_string() }; let mut input = ParserInput::new(&easing); let mut parser = Parser::new(&mut input); let result = parser.parse_entirely(|p| transition_timing_function::single_value::parse(&context, p)); match result { Ok(parsed_easing) => { *output = parsed_easing.into(); true }, Err(_) => false } } #[no_mangle] pub extern "C" fn Servo_GetProperties_Overriding_Animation(element: RawGeckoElementBorrowed, list: RawGeckoCSSPropertyIDListBorrowed, set: nsCSSPropertyIDSetBorrowedMut) { let element = GeckoElement(element); let element_data = match element.borrow_data() { Some(data) => data, None => return }; let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let guards = StylesheetGuards::same(&guard); let (overridden, custom) = element_data.styles.primary().rules().get_properties_overriding_animations(&guards); for p in list.iter() { match PropertyId::from_nscsspropertyid(*p) { Ok(property) => { if let PropertyId::Longhand(id) = property { if overridden.contains(id) { unsafe { Gecko_AddPropertyToSet(set, *p) }; } } }, Err(_) => { if *p == nsCSSPropertyID::eCSSPropertyExtra_variable && custom { unsafe { Gecko_AddPropertyToSet(set, *p) }; } } } } } #[no_mangle] pub extern "C" fn Servo_MatrixTransform_Operate(matrix_operator: MatrixTransformOperator, from: *const RawGeckoGfxMatrix4x4, to: *const RawGeckoGfxMatrix4x4, progress: f64, output: *mut RawGeckoGfxMatrix4x4) { use self::MatrixTransformOperator::{Accumulate, Interpolate}; use style::values::computed::transform::Matrix3D; let from = Matrix3D::from(unsafe { from.as_ref() }.expect("not a valid 'from' matrix")); let to = Matrix3D::from(unsafe { to.as_ref() }.expect("not a valid 'to' matrix")); let result = match matrix_operator { Interpolate => from.animate(&to, Procedure::Interpolate { progress }), Accumulate => from.animate(&to, Procedure::Accumulate { count: progress as u64 }), }; let output = unsafe { output.as_mut() }.expect("not a valid 'output' matrix"); if let Ok(result) = result { *output = result.into(); } else if progress < 0.5 { *output = from.clone().into(); } else { *output = to.clone().into(); } } #[no_mangle]<|fim▁hole|> quirks_mode: nsCompatibility, loader: *mut Loader, ) -> RawServoDeclarationBlockStrong { let global_style_data = &*GLOBAL_STYLE_DATA; let value = unsafe { data.as_ref().unwrap().as_str_unchecked() }; let reporter = ErrorReporter::new(ptr::null_mut(), loader, raw_extra_data); let url_data = unsafe { RefPtr::from_ptr_ref(&raw_extra_data) }; Arc::new(global_style_data.shared_lock.wrap( GeckoElement::parse_style_attribute(value, url_data, quirks_mode.into(), &reporter))) .into_strong() } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_CreateEmpty() -> RawServoDeclarationBlockStrong { let global_style_data = &*GLOBAL_STYLE_DATA; Arc::new(global_style_data.shared_lock.wrap(PropertyDeclarationBlock::new())).into_strong() } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_Clone(declarations: RawServoDeclarationBlockBorrowed) -> RawServoDeclarationBlockStrong { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let declarations = Locked::<PropertyDeclarationBlock>::as_arc(&declarations); Arc::new(global_style_data.shared_lock.wrap( declarations.read_with(&guard).clone() )).into_strong() } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_Equals( a: RawServoDeclarationBlockBorrowed, b: RawServoDeclarationBlockBorrowed, ) -> bool { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); *Locked::<PropertyDeclarationBlock>::as_arc(&a).read_with(&guard).declarations() == *Locked::<PropertyDeclarationBlock>::as_arc(&b).read_with(&guard).declarations() } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_GetCssText(declarations: RawServoDeclarationBlockBorrowed, result: *mut nsAString) { read_locked_arc(declarations, |decls: &PropertyDeclarationBlock| { decls.to_css(unsafe { result.as_mut().unwrap() }).unwrap(); }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SerializeOneValue( declarations: RawServoDeclarationBlockBorrowed, property_id: nsCSSPropertyID, buffer: *mut nsAString, computed_values: ServoStyleContextBorrowedOrNull, custom_properties: RawServoDeclarationBlockBorrowedOrNull, ) { let property_id = get_property_id_from_nscsspropertyid!(property_id, ()); let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let decls = Locked::<PropertyDeclarationBlock>::as_arc(&declarations).read_with(&guard); let mut string = String::new(); let custom_properties = Locked::<PropertyDeclarationBlock>::arc_from_borrowed(&custom_properties); let custom_properties = custom_properties.map(|block| block.read_with(&guard)); let rv = decls.single_value_to_css( &property_id, &mut string, computed_values, custom_properties); debug_assert!(rv.is_ok()); let buffer = unsafe { buffer.as_mut().unwrap() }; buffer.assign_utf8(&string); } #[no_mangle] pub extern "C" fn Servo_SerializeFontValueForCanvas( declarations: RawServoDeclarationBlockBorrowed, buffer: *mut nsAString, ) { use style::properties::shorthands::font; read_locked_arc(declarations, |decls: &PropertyDeclarationBlock| { let longhands = match font::LonghandsToSerialize::from_iter(decls.declarations().iter()) { Ok(l) => l, Err(()) => { warn!("Unexpected property!"); return; } }; let mut string = String::new(); let rv = longhands.to_css_for_canvas(&mut string); debug_assert!(rv.is_ok()); let buffer = unsafe { buffer.as_mut().unwrap() }; buffer.assign_utf8(&string); }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_Count(declarations: RawServoDeclarationBlockBorrowed) -> u32 { read_locked_arc(declarations, |decls: &PropertyDeclarationBlock| { decls.declarations().len() as u32 }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_GetNthProperty( declarations: RawServoDeclarationBlockBorrowed, index: u32, result: *mut nsAString, ) -> bool { read_locked_arc(declarations, |decls: &PropertyDeclarationBlock| { if let Some(decl) = decls.declarations().get(index as usize) { let result = unsafe { result.as_mut().unwrap() }; result.assign_utf8(&decl.id().name()); true } else { false } }) } macro_rules! get_property_id_from_property { ($property: ident, $ret: expr) => {{ let property = $property.as_ref().unwrap().as_str_unchecked(); match PropertyId::parse(property.into(), None) { Ok(property_id) => property_id, Err(_) => { return $ret; } } }} } unsafe fn get_property_value( declarations: RawServoDeclarationBlockBorrowed, property_id: PropertyId, value: *mut nsAString, ) { // This callsite is hot enough that the lock acquisition shows up in profiles. // Using an unchecked read here improves our performance by ~10% on the // microbenchmark in bug 1355599. read_locked_arc_unchecked(declarations, |decls: &PropertyDeclarationBlock| { decls.property_value_to_css(&property_id, value.as_mut().unwrap()).unwrap(); }) } #[no_mangle] pub unsafe extern "C" fn Servo_DeclarationBlock_GetPropertyValue( declarations: RawServoDeclarationBlockBorrowed, property: *const nsACString, value: *mut nsAString, ) { get_property_value( declarations, get_property_id_from_property!(property, ()), value, ) } #[no_mangle] pub unsafe extern "C" fn Servo_DeclarationBlock_GetPropertyValueById( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, value: *mut nsAString, ) { get_property_value(declarations, get_property_id_from_nscsspropertyid!(property, ()), value) } #[no_mangle] pub unsafe extern "C" fn Servo_DeclarationBlock_GetPropertyIsImportant( declarations: RawServoDeclarationBlockBorrowed, property: *const nsACString, ) -> bool { let property_id = get_property_id_from_property!(property, false); read_locked_arc(declarations, |decls: &PropertyDeclarationBlock| { decls.property_priority(&property_id).important() }) } fn set_property( declarations: RawServoDeclarationBlockBorrowed, property_id: PropertyId, value: *const nsACString, is_important: bool, data: *mut URLExtraData, parsing_mode: structs::ParsingMode, quirks_mode: QuirksMode, loader: *mut Loader ) -> bool { let mut source_declarations = SourcePropertyDeclaration::new(); let reporter = ErrorReporter::new(ptr::null_mut(), loader, data); match parse_property_into(&mut source_declarations, property_id, value, data, parsing_mode, quirks_mode, &reporter) { Ok(()) => { let importance = if is_important { Importance::Important } else { Importance::Normal }; write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.extend( source_declarations.drain(), importance, DeclarationSource::CssOm ) }) }, Err(_) => false, } } #[no_mangle] pub unsafe extern "C" fn Servo_DeclarationBlock_SetProperty( declarations: RawServoDeclarationBlockBorrowed, property: *const nsACString, value: *const nsACString, is_important: bool, data: *mut URLExtraData, parsing_mode: structs::ParsingMode, quirks_mode: nsCompatibility, loader: *mut Loader, ) -> bool { set_property( declarations, get_property_id_from_property!(property, false), value, is_important, data, parsing_mode, quirks_mode.into(), loader, ) } #[no_mangle] pub unsafe extern "C" fn Servo_DeclarationBlock_SetPropertyById( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, value: *const nsACString, is_important: bool, data: *mut URLExtraData, parsing_mode: structs::ParsingMode, quirks_mode: nsCompatibility, loader: *mut Loader, ) -> bool { set_property( declarations, get_property_id_from_nscsspropertyid!(property, false), value, is_important, data, parsing_mode, quirks_mode.into(), loader, ) } fn remove_property( declarations: RawServoDeclarationBlockBorrowed, property_id: PropertyId ) -> bool { write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.remove_property(&property_id) }) } #[no_mangle] pub unsafe extern "C" fn Servo_DeclarationBlock_RemoveProperty( declarations: RawServoDeclarationBlockBorrowed, property: *const nsACString, ) { remove_property(declarations, get_property_id_from_property!(property, ())); } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_RemovePropertyById( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID ) -> bool { remove_property(declarations, get_property_id_from_nscsspropertyid!(property, false)) } #[no_mangle] pub extern "C" fn Servo_MediaList_Create() -> RawServoMediaListStrong { let global_style_data = &*GLOBAL_STYLE_DATA; Arc::new(global_style_data.shared_lock.wrap(MediaList::empty())).into_strong() } #[no_mangle] pub extern "C" fn Servo_MediaList_DeepClone(list: RawServoMediaListBorrowed) -> RawServoMediaListStrong { let global_style_data = &*GLOBAL_STYLE_DATA; read_locked_arc(list, |list: &MediaList| { Arc::new(global_style_data.shared_lock.wrap(list.clone())) .into_strong() }) } #[no_mangle] pub extern "C" fn Servo_MediaList_Matches( list: RawServoMediaListBorrowed, raw_data: RawServoStyleSetBorrowed, ) -> bool { let per_doc_data = PerDocumentStyleData::from_ffi(raw_data).borrow(); read_locked_arc(list, |list: &MediaList| { list.evaluate(per_doc_data.stylist.device(), per_doc_data.stylist.quirks_mode()) }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_HasCSSWideKeyword( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, ) -> bool { let property_id = get_property_id_from_nscsspropertyid!(property, false); read_locked_arc(declarations, |decls: &PropertyDeclarationBlock| { decls.has_css_wide_keyword(&property_id) }) } #[no_mangle] pub extern "C" fn Servo_MediaList_GetText(list: RawServoMediaListBorrowed, result: *mut nsAString) { read_locked_arc(list, |list: &MediaList| { list.to_css(unsafe { result.as_mut().unwrap() }).unwrap(); }) } #[no_mangle] pub unsafe extern "C" fn Servo_MediaList_SetText( list: RawServoMediaListBorrowed, text: *const nsACString, caller_type: CallerType, ) { let text = (*text).as_str_unchecked(); let mut input = ParserInput::new(&text); let mut parser = Parser::new(&mut input); let url_data = dummy_url_data(); // TODO(emilio): If the need for `CallerType` appears in more places, // consider adding an explicit member in `ParserContext` instead of doing // this (or adding a dummy "chrome://" url data). // // For media query parsing it's effectively the same, so for now... let origin = match caller_type { CallerType::System => Origin::UserAgent, CallerType::NonSystem => Origin::Author, }; let context = ParserContext::new( origin, url_data, Some(CssRuleType::Media), ParsingMode::DEFAULT, QuirksMode::NoQuirks, ); write_locked_arc(list, |list: &mut MediaList| { *list = parse_media_query_list( &context, &mut parser, &NullReporter, ); }) } #[no_mangle] pub extern "C" fn Servo_MediaList_GetLength(list: RawServoMediaListBorrowed) -> u32 { read_locked_arc(list, |list: &MediaList| list.media_queries.len() as u32) } #[no_mangle] pub extern "C" fn Servo_MediaList_GetMediumAt( list: RawServoMediaListBorrowed, index: u32, result: *mut nsAString, ) -> bool { read_locked_arc(list, |list: &MediaList| { if let Some(media_query) = list.media_queries.get(index as usize) { media_query.to_css(unsafe { result.as_mut().unwrap() }).unwrap(); true } else { false } }) } #[no_mangle] pub extern "C" fn Servo_MediaList_AppendMedium( list: RawServoMediaListBorrowed, new_medium: *const nsACString, ) { let new_medium = unsafe { new_medium.as_ref().unwrap().as_str_unchecked() }; let url_data = unsafe { dummy_url_data() }; let context = ParserContext::new_for_cssom(url_data, Some(CssRuleType::Media), ParsingMode::DEFAULT, QuirksMode::NoQuirks); write_locked_arc(list, |list: &mut MediaList| { list.append_medium(&context, new_medium); }) } #[no_mangle] pub extern "C" fn Servo_MediaList_DeleteMedium( list: RawServoMediaListBorrowed, old_medium: *const nsACString, ) -> bool { let old_medium = unsafe { old_medium.as_ref().unwrap().as_str_unchecked() }; let url_data = unsafe { dummy_url_data() }; let context = ParserContext::new_for_cssom(url_data, Some(CssRuleType::Media), ParsingMode::DEFAULT, QuirksMode::NoQuirks); write_locked_arc(list, |list: &mut MediaList| list.delete_medium(&context, old_medium)) } macro_rules! get_longhand_from_id { ($id:expr) => { match PropertyId::from_nscsspropertyid($id) { Ok(PropertyId::Longhand(long)) => long, _ => { panic!("stylo: unknown presentation property with id {:?}", $id); } } }; } macro_rules! match_wrap_declared { ($longhand:ident, $($property:ident => $inner:expr,)*) => ( match $longhand { $( LonghandId::$property => PropertyDeclaration::$property($inner), )* _ => { panic!("stylo: Don't know how to handle presentation property {:?}", $longhand); } } ) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_PropertyIsSet(declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID) -> bool { read_locked_arc(declarations, |decls: &PropertyDeclarationBlock| { decls.contains(get_longhand_from_id!(property)) }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SetIdentStringValue( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, value: *mut nsAtom, ) { use style::properties::{PropertyDeclaration, LonghandId}; use style::properties::longhands::_x_lang::computed_value::T as Lang; let long = get_longhand_from_id!(property); let prop = match_wrap_declared! { long, XLang => Lang(Atom::from(value)), }; write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(prop, Importance::Normal, DeclarationSource::CssOm); }) } #[no_mangle] #[allow(unreachable_code)] pub extern "C" fn Servo_DeclarationBlock_SetKeywordValue( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, value: i32 ) { use style::properties::{PropertyDeclaration, LonghandId}; use style::properties::longhands; use style::values::specified::BorderStyle; let long = get_longhand_from_id!(property); let value = value as u32; let prop = match_wrap_declared! { long, MozUserModify => longhands::_moz_user_modify::SpecifiedValue::from_gecko_keyword(value), // TextEmphasisPosition => FIXME implement text-emphasis-position Direction => longhands::direction::SpecifiedValue::from_gecko_keyword(value), Display => longhands::display::SpecifiedValue::from_gecko_keyword(value), Float => longhands::float::SpecifiedValue::from_gecko_keyword(value), VerticalAlign => longhands::vertical_align::SpecifiedValue::from_gecko_keyword(value), TextAlign => longhands::text_align::SpecifiedValue::from_gecko_keyword(value), TextEmphasisPosition => longhands::text_emphasis_position::SpecifiedValue::from_gecko_keyword(value), Clear => longhands::clear::SpecifiedValue::from_gecko_keyword(value), FontSize => { // We rely on Gecko passing in font-size values (0...7) here. longhands::font_size::SpecifiedValue::from_html_size(value as u8) }, FontStyle => { ToComputedValue::from_computed_value(&longhands::font_style::computed_value::T::from_gecko_keyword(value)) }, FontWeight => longhands::font_weight::SpecifiedValue::from_gecko_keyword(value), ListStyleType => Box::new(longhands::list_style_type::SpecifiedValue::from_gecko_keyword(value)), MozMathVariant => longhands::_moz_math_variant::SpecifiedValue::from_gecko_keyword(value), WhiteSpace => longhands::white_space::SpecifiedValue::from_gecko_keyword(value), CaptionSide => longhands::caption_side::SpecifiedValue::from_gecko_keyword(value), BorderTopStyle => BorderStyle::from_gecko_keyword(value), BorderRightStyle => BorderStyle::from_gecko_keyword(value), BorderBottomStyle => BorderStyle::from_gecko_keyword(value), BorderLeftStyle => BorderStyle::from_gecko_keyword(value), }; write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(prop, Importance::Normal, DeclarationSource::CssOm); }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SetIntValue( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, value: i32 ) { use style::properties::{PropertyDeclaration, LonghandId}; use style::properties::longhands::_moz_script_level::SpecifiedValue as MozScriptLevel; use style::properties::longhands::_x_span::computed_value::T as Span; let long = get_longhand_from_id!(property); let prop = match_wrap_declared! { long, XSpan => Span(value), // Gecko uses Integer values to signal that it is relative MozScriptLevel => MozScriptLevel::Relative(value), }; write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(prop, Importance::Normal, DeclarationSource::CssOm); }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SetPixelValue( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, value: f32 ) { use style::properties::{PropertyDeclaration, LonghandId}; use style::properties::longhands::border_spacing::SpecifiedValue as BorderSpacing; use style::properties::longhands::height::SpecifiedValue as Height; use style::properties::longhands::width::SpecifiedValue as Width; use style::values::specified::{BorderSideWidth, MozLength, BorderCornerRadius}; use style::values::specified::length::{NoCalcLength, NonNegativeLength, LengthOrPercentage}; let long = get_longhand_from_id!(property); let nocalc = NoCalcLength::from_px(value); let prop = match_wrap_declared! { long, Height => Height(MozLength::LengthOrPercentageOrAuto(nocalc.into())), Width => Width(MozLength::LengthOrPercentageOrAuto(nocalc.into())), BorderTopWidth => BorderSideWidth::Length(nocalc.into()), BorderRightWidth => BorderSideWidth::Length(nocalc.into()), BorderBottomWidth => BorderSideWidth::Length(nocalc.into()), BorderLeftWidth => BorderSideWidth::Length(nocalc.into()), MarginTop => nocalc.into(), MarginRight => nocalc.into(), MarginBottom => nocalc.into(), MarginLeft => nocalc.into(), PaddingTop => nocalc.into(), PaddingRight => nocalc.into(), PaddingBottom => nocalc.into(), PaddingLeft => nocalc.into(), BorderSpacing => { let v = NonNegativeLength::from(nocalc); Box::new(BorderSpacing::new(v.clone(), v)) }, BorderTopLeftRadius => { let length = LengthOrPercentage::from(nocalc); Box::new(BorderCornerRadius::new(length.clone(), length)) }, BorderTopRightRadius => { let length = LengthOrPercentage::from(nocalc); Box::new(BorderCornerRadius::new(length.clone(), length)) }, BorderBottomLeftRadius => { let length = LengthOrPercentage::from(nocalc); Box::new(BorderCornerRadius::new(length.clone(), length)) }, BorderBottomRightRadius => { let length = LengthOrPercentage::from(nocalc); Box::new(BorderCornerRadius::new(length.clone(), length)) }, }; write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(prop, Importance::Normal, DeclarationSource::CssOm); }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SetLengthValue( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, value: f32, unit: structs::nsCSSUnit, ) { use style::properties::{PropertyDeclaration, LonghandId}; use style::properties::longhands::_moz_script_min_size::SpecifiedValue as MozScriptMinSize; use style::properties::longhands::width::SpecifiedValue as Width; use style::values::specified::MozLength; use style::values::specified::length::{AbsoluteLength, FontRelativeLength}; use style::values::specified::length::{LengthOrPercentage, NoCalcLength}; let long = get_longhand_from_id!(property); let nocalc = match unit { structs::nsCSSUnit::eCSSUnit_EM => NoCalcLength::FontRelative(FontRelativeLength::Em(value)), structs::nsCSSUnit::eCSSUnit_XHeight => NoCalcLength::FontRelative(FontRelativeLength::Ex(value)), structs::nsCSSUnit::eCSSUnit_Pixel => NoCalcLength::Absolute(AbsoluteLength::Px(value)), structs::nsCSSUnit::eCSSUnit_Inch => NoCalcLength::Absolute(AbsoluteLength::In(value)), structs::nsCSSUnit::eCSSUnit_Centimeter => NoCalcLength::Absolute(AbsoluteLength::Cm(value)), structs::nsCSSUnit::eCSSUnit_Millimeter => NoCalcLength::Absolute(AbsoluteLength::Mm(value)), structs::nsCSSUnit::eCSSUnit_Point => NoCalcLength::Absolute(AbsoluteLength::Pt(value)), structs::nsCSSUnit::eCSSUnit_Pica => NoCalcLength::Absolute(AbsoluteLength::Pc(value)), structs::nsCSSUnit::eCSSUnit_Quarter => NoCalcLength::Absolute(AbsoluteLength::Q(value)), _ => unreachable!("Unknown unit {:?} passed to SetLengthValue", unit) }; let prop = match_wrap_declared! { long, Width => Width(MozLength::LengthOrPercentageOrAuto(nocalc.into())), FontSize => LengthOrPercentage::from(nocalc).into(), MozScriptMinSize => MozScriptMinSize(nocalc), }; write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(prop, Importance::Normal, DeclarationSource::CssOm); }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SetNumberValue( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, value: f32, ) { use style::properties::{PropertyDeclaration, LonghandId}; use style::properties::longhands::_moz_script_level::SpecifiedValue as MozScriptLevel; let long = get_longhand_from_id!(property); let prop = match_wrap_declared! { long, MozScriptSizeMultiplier => value, // Gecko uses Number values to signal that it is absolute MozScriptLevel => MozScriptLevel::MozAbsolute(value as i32), }; write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(prop, Importance::Normal, DeclarationSource::CssOm); }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SetPercentValue( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, value: f32, ) { use style::properties::{PropertyDeclaration, LonghandId}; use style::properties::longhands::height::SpecifiedValue as Height; use style::properties::longhands::width::SpecifiedValue as Width; use style::values::computed::Percentage; use style::values::specified::MozLength; use style::values::specified::length::LengthOrPercentage; let long = get_longhand_from_id!(property); let pc = Percentage(value); let prop = match_wrap_declared! { long, Height => Height(MozLength::LengthOrPercentageOrAuto(pc.into())), Width => Width(MozLength::LengthOrPercentageOrAuto(pc.into())), MarginTop => pc.into(), MarginRight => pc.into(), MarginBottom => pc.into(), MarginLeft => pc.into(), FontSize => LengthOrPercentage::from(pc).into(), }; write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(prop, Importance::Normal, DeclarationSource::CssOm); }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SetAutoValue( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, ) { use style::properties::{PropertyDeclaration, LonghandId}; use style::properties::longhands::height::SpecifiedValue as Height; use style::properties::longhands::width::SpecifiedValue as Width; use style::values::specified::LengthOrPercentageOrAuto; let long = get_longhand_from_id!(property); let auto = LengthOrPercentageOrAuto::Auto; let prop = match_wrap_declared! { long, Height => Height::auto(), Width => Width::auto(), MarginTop => auto, MarginRight => auto, MarginBottom => auto, MarginLeft => auto, }; write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(prop, Importance::Normal, DeclarationSource::CssOm); }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SetCurrentColor( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, ) { use style::properties::{PropertyDeclaration, LonghandId}; use style::values::specified::Color; let long = get_longhand_from_id!(property); let cc = Color::currentcolor(); let prop = match_wrap_declared! { long, BorderTopColor => cc, BorderRightColor => cc, BorderBottomColor => cc, BorderLeftColor => cc, }; write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(prop, Importance::Normal, DeclarationSource::CssOm); }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SetColorValue( declarations: RawServoDeclarationBlockBorrowed, property: nsCSSPropertyID, value: structs::nscolor, ) { use style::gecko::values::convert_nscolor_to_rgba; use style::properties::{PropertyDeclaration, LonghandId}; use style::properties::longhands; use style::values::specified::Color; let long = get_longhand_from_id!(property); let rgba = convert_nscolor_to_rgba(value); let color = Color::rgba(rgba); let prop = match_wrap_declared! { long, BorderTopColor => color, BorderRightColor => color, BorderBottomColor => color, BorderLeftColor => color, Color => longhands::color::SpecifiedValue(color), BackgroundColor => color, }; write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(prop, Importance::Normal, DeclarationSource::CssOm); }) } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SetFontFamily( declarations: RawServoDeclarationBlockBorrowed, value: *const nsAString, ) { use cssparser::{Parser, ParserInput}; use style::properties::PropertyDeclaration; use style::properties::longhands::font_family::SpecifiedValue as FontFamily; let string = unsafe { (*value).to_string() }; let mut input = ParserInput::new(&string); let mut parser = Parser::new(&mut input); let result = FontFamily::parse(&mut parser); if let Ok(family) = result { if parser.is_exhausted() { let decl = PropertyDeclaration::FontFamily(family); write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(decl, Importance::Normal, DeclarationSource::CssOm); }) } } } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SetBackgroundImage( declarations: RawServoDeclarationBlockBorrowed, value: *const nsAString, raw_extra_data: *mut URLExtraData, ) { use style::properties::PropertyDeclaration; use style::properties::longhands::background_image::SpecifiedValue as BackgroundImage; use style::values::Either; use style::values::generics::image::Image; use style::values::specified::url::SpecifiedUrl; let url_data = unsafe { RefPtr::from_ptr_ref(&raw_extra_data) }; let string = unsafe { (*value).to_string() }; let context = ParserContext::new(Origin::Author, url_data, Some(CssRuleType::Style), ParsingMode::DEFAULT, QuirksMode::NoQuirks); if let Ok(mut url) = SpecifiedUrl::parse_from_string(string.into(), &context) { url.build_image_value(); let decl = PropertyDeclaration::BackgroundImage(BackgroundImage( vec![Either::Second(Image::Url(url))] )); write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(decl, Importance::Normal, DeclarationSource::CssOm); }) } } #[no_mangle] pub extern "C" fn Servo_DeclarationBlock_SetTextDecorationColorOverride( declarations: RawServoDeclarationBlockBorrowed, ) { use style::properties::PropertyDeclaration; use style::values::specified::text::TextDecorationLine; let mut decoration = TextDecorationLine::none(); decoration |= TextDecorationLine::COLOR_OVERRIDE; let decl = PropertyDeclaration::TextDecorationLine(decoration); write_locked_arc(declarations, |decls: &mut PropertyDeclarationBlock| { decls.push(decl, Importance::Normal, DeclarationSource::CssOm); }) } #[no_mangle] pub unsafe extern "C" fn Servo_CSSSupports2( property: *const nsACString, value: *const nsACString, ) -> bool { let id = get_property_id_from_property!(property, false); let mut declarations = SourcePropertyDeclaration::new(); parse_property_into( &mut declarations, id, value, DUMMY_URL_DATA, structs::ParsingMode_Default, QuirksMode::NoQuirks, &NullReporter, ).is_ok() } #[no_mangle] pub extern "C" fn Servo_CSSSupports(cond: *const nsACString) -> bool { let condition = unsafe { cond.as_ref().unwrap().as_str_unchecked() }; let mut input = ParserInput::new(&condition); let mut input = Parser::new(&mut input); let cond = input.parse_entirely(|i| parse_condition_or_declaration(i)); if let Ok(cond) = cond { let url_data = unsafe { dummy_url_data() }; // NOTE(emilio): The supports API is not associated to any stylesheet, // so the fact that there are no namespace map here is fine. let context = ParserContext::new_for_cssom( url_data, Some(CssRuleType::Style), ParsingMode::DEFAULT, QuirksMode::NoQuirks, ); cond.eval(&context) } else { false } } #[no_mangle] pub extern "C" fn Servo_NoteExplicitHints( element: RawGeckoElementBorrowed, restyle_hint: nsRestyleHint, change_hint: nsChangeHint, ) { GeckoElement(element).note_explicit_hints(restyle_hint, change_hint); } #[no_mangle] pub extern "C" fn Servo_TakeChangeHint( element: RawGeckoElementBorrowed, was_restyled: *mut bool ) -> u32 { let was_restyled = unsafe { was_restyled.as_mut().unwrap() }; let element = GeckoElement(element); let damage = match element.mutate_data() { Some(mut data) => { *was_restyled = data.is_restyle(); let damage = data.damage; data.clear_restyle_state(); damage } None => { warn!("Trying to get change hint from unstyled element"); *was_restyled = false; GeckoRestyleDamage::empty() } }; debug!("Servo_TakeChangeHint: {:?}, damage={:?}", element, damage); // We'd like to return `nsChangeHint` here, but bindgen bitfield enums don't // work as return values with the Linux 32-bit ABI at the moment because // they wrap the value in a struct, so for now just unwrap it. damage.as_change_hint().0 } #[no_mangle] pub extern "C" fn Servo_ResolveStyle( element: RawGeckoElementBorrowed, _raw_data: RawServoStyleSetBorrowed, ) -> ServoStyleContextStrong { let element = GeckoElement(element); debug!("Servo_ResolveStyle: {:?}", element); let data = element.borrow_data().expect("Resolving style on unstyled element"); debug_assert!(element.has_current_styles(&*data), "Resolving style on {:?} without current styles: {:?}", element, data); data.styles.primary().clone().into() } #[no_mangle] pub extern "C" fn Servo_ResolveStyleLazily( element: RawGeckoElementBorrowed, pseudo_type: CSSPseudoElementType, rule_inclusion: StyleRuleInclusion, snapshots: *const ServoElementSnapshotTable, raw_data: RawServoStyleSetBorrowed, ignore_existing_styles: bool ) -> ServoStyleContextStrong { debug_assert!(!snapshots.is_null()); let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let element = GeckoElement(element); let doc_data = PerDocumentStyleData::from_ffi(raw_data); let data = doc_data.borrow(); let rule_inclusion = RuleInclusion::from(rule_inclusion); let pseudo = PseudoElement::from_pseudo_type(pseudo_type); let finish = |styles: &ElementStyles, is_probe: bool| -> Option<Arc<ComputedValues>> { match pseudo { Some(ref pseudo) => { get_pseudo_style( &guard, element, pseudo, rule_inclusion, styles, /* inherited_styles = */ None, &*data, is_probe, /* matching_func = */ None, ) } None => Some(styles.primary().clone()), } }; let is_before_or_after = pseudo.as_ref().map_or(false, |p| p.is_before_or_after()); // In the common case we already have the style. Check that before setting // up all the computation machinery. (Don't use it when we're getting // default styles or in a bfcached document (as indicated by // ignore_existing_styles), though.) // // Also, only probe in the ::before or ::after case, since their styles may // not be in the `ElementData`, given they may exist but not be applicable // to generate an actual pseudo-element (like, having a `content: none`). if rule_inclusion == RuleInclusion::All && !ignore_existing_styles { let styles = element.mutate_data().and_then(|d| { if d.has_styles() { finish(&d.styles, is_before_or_after) } else { None } }); if let Some(result) = styles { return result.into(); } } // We don't have the style ready. Go ahead and compute it as necessary. let shared = create_shared_context(&global_style_data, &guard, &data, TraversalFlags::empty(), unsafe { &*snapshots }); let mut tlc = ThreadLocalStyleContext::new(&shared); let mut context = StyleContext { shared: &shared, thread_local: &mut tlc, }; let styles = resolve_style( &mut context, element, rule_inclusion, ignore_existing_styles, pseudo.as_ref() ); finish(&styles, /* is_probe = */ false) .expect("We're not probing, so we should always get a style back") .into() } #[no_mangle] pub extern "C" fn Servo_ReparentStyle( style_to_reparent: ServoStyleContextBorrowed, parent_style: ServoStyleContextBorrowed, parent_style_ignoring_first_line: ServoStyleContextBorrowed, layout_parent_style: ServoStyleContextBorrowed, element: RawGeckoElementBorrowedOrNull, raw_data: RawServoStyleSetBorrowed, ) -> ServoStyleContextStrong { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let doc_data = PerDocumentStyleData::from_ffi(raw_data).borrow(); let inputs = CascadeInputs::new_from_style(style_to_reparent); let metrics = get_metrics_provider_for_product(); let pseudo = style_to_reparent.pseudo(); let element = element.map(GeckoElement); let mut cascade_flags = CascadeFlags::empty(); if style_to_reparent.is_anon_box() { cascade_flags.insert(CascadeFlags::SKIP_ROOT_AND_ITEM_BASED_DISPLAY_FIXUP); } if let Some(element) = element { if element.is_link() { cascade_flags.insert(CascadeFlags::IS_LINK); if element.is_visited_link() && doc_data.visited_styles_enabled() { cascade_flags.insert(CascadeFlags::IS_VISITED_LINK); } }; if element.is_native_anonymous() { cascade_flags.insert(CascadeFlags::PROHIBIT_DISPLAY_CONTENTS); } } if let Some(pseudo) = pseudo.as_ref() { cascade_flags.insert(CascadeFlags::PROHIBIT_DISPLAY_CONTENTS); if pseudo.is_fieldset_content() { cascade_flags.insert(CascadeFlags::IS_FIELDSET_CONTENT); } } doc_data.stylist .compute_style_with_inputs(&inputs, pseudo.as_ref(), &StylesheetGuards::same(&guard), parent_style, parent_style_ignoring_first_line, layout_parent_style, &metrics, cascade_flags) .into() } #[cfg(feature = "gecko_debug")] fn simulate_compute_values_failure(property: &PropertyValuePair) -> bool { let p = property.mProperty; let id = get_property_id_from_nscsspropertyid!(p, false); id.as_shorthand().is_ok() && property.mSimulateComputeValuesFailure } #[cfg(not(feature = "gecko_debug"))] fn simulate_compute_values_failure(_: &PropertyValuePair) -> bool { false } fn create_context<'a>( per_doc_data: &'a PerDocumentStyleDataImpl, font_metrics_provider: &'a FontMetricsProvider, style: &'a ComputedValues, parent_style: Option<&'a ComputedValues>, pseudo: Option<&'a PseudoElement>, for_smil_animation: bool, rule_cache_conditions: &'a mut RuleCacheConditions, ) -> Context<'a> { Context { is_root_element: false, builder: StyleBuilder::for_derived_style( per_doc_data.stylist.device(), style, parent_style, pseudo, ), font_metrics_provider: font_metrics_provider, cached_system_font: None, in_media_query: false, quirks_mode: per_doc_data.stylist.quirks_mode(), for_smil_animation, for_non_inherited_property: None, rule_cache_conditions: RefCell::new(rule_cache_conditions), } } struct PropertyAndIndex { property: PropertyId, index: usize, } struct PrioritizedPropertyIter<'a> { properties: &'a nsTArray<PropertyValuePair>, sorted_property_indices: Vec<PropertyAndIndex>, curr: usize, } impl<'a> PrioritizedPropertyIter<'a> { pub fn new(properties: &'a nsTArray<PropertyValuePair>) -> PrioritizedPropertyIter { // If we fail to convert a nsCSSPropertyID into a PropertyId we shouldn't fail outright // but instead by treating that property as the 'all' property we make it sort last. let all = PropertyId::Shorthand(ShorthandId::All); let mut sorted_property_indices: Vec<PropertyAndIndex> = properties.iter().enumerate().map(|(index, pair)| { PropertyAndIndex { property: PropertyId::from_nscsspropertyid(pair.mProperty) .unwrap_or(all.clone()), index, } }).collect(); sorted_property_indices.sort_by(|a, b| compare_property_priority(&a.property, &b.property)); PrioritizedPropertyIter { properties, sorted_property_indices, curr: 0, } } } impl<'a> Iterator for PrioritizedPropertyIter<'a> { type Item = &'a PropertyValuePair; fn next(&mut self) -> Option<&'a PropertyValuePair> { if self.curr >= self.sorted_property_indices.len() { return None } self.curr += 1; Some(&self.properties[self.sorted_property_indices[self.curr - 1].index]) } } #[no_mangle] pub extern "C" fn Servo_GetComputedKeyframeValues( keyframes: RawGeckoKeyframeListBorrowed, element: RawGeckoElementBorrowed, style: ServoStyleContextBorrowed, raw_data: RawServoStyleSetBorrowed, computed_keyframes: RawGeckoComputedKeyframeValuesListBorrowedMut ) { use std::mem; use style::properties::LonghandIdSet; let data = PerDocumentStyleData::from_ffi(raw_data).borrow(); let metrics = get_metrics_provider_for_product(); let element = GeckoElement(element); let parent_element = element.inheritance_parent(); let parent_data = parent_element.as_ref().and_then(|e| e.borrow_data()); let parent_style = parent_data.as_ref().map(|d| d.styles.primary()).map(|x| &**x); let pseudo = style.pseudo(); let mut conditions = Default::default(); let mut context = create_context( &data, &metrics, &style, parent_style, pseudo.as_ref(), /* for_smil_animation = */ false, &mut conditions, ); let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let default_values = data.default_computed_values(); let mut raw_custom_properties_block; // To make the raw block alive in the scope. for (index, keyframe) in keyframes.iter().enumerate() { let mut custom_properties = None; for property in keyframe.mPropertyValues.iter() { // Find the block for custom properties first. if property.mProperty == nsCSSPropertyID::eCSSPropertyExtra_variable { raw_custom_properties_block = unsafe { &*property.mServoDeclarationBlock.mRawPtr.clone() }; let guard = Locked::<PropertyDeclarationBlock>::as_arc( &raw_custom_properties_block).read_with(&guard); custom_properties = guard.cascade_custom_properties_with_context(&context); // There should be one PropertyDeclarationBlock for custom properties. break; } } let ref mut animation_values = computed_keyframes[index]; let mut seen = LonghandIdSet::new(); let mut property_index = 0; for property in PrioritizedPropertyIter::new(&keyframe.mPropertyValues) { if simulate_compute_values_failure(property) { continue; } let mut maybe_append_animation_value = |property: LonghandId, value: Option<AnimationValue>| { if seen.contains(property) { return; } seen.insert(property); // This is safe since we immediately write to the uninitialized values. unsafe { animation_values.set_len((property_index + 1) as u32) }; animation_values[property_index].mProperty = property.to_nscsspropertyid(); // We only make sure we have enough space for this variable, // but didn't construct a default value for StyleAnimationValue, // so we should zero it to avoid getting undefined behaviors. animation_values[property_index].mValue.mGecko = unsafe { mem::zeroed() }; match value { Some(v) => { animation_values[property_index].mValue.mServo.set_arc_leaky(Arc::new(v)); }, None => { animation_values[property_index].mValue.mServo.mRawPtr = ptr::null_mut(); }, } property_index += 1; }; if property.mServoDeclarationBlock.mRawPtr.is_null() { let property = LonghandId::from_nscsspropertyid(property.mProperty); if let Ok(prop) = property { maybe_append_animation_value(prop, None); } continue; } let declarations = unsafe { &*property.mServoDeclarationBlock.mRawPtr.clone() }; let declarations = Locked::<PropertyDeclarationBlock>::as_arc(&declarations); let guard = declarations.read_with(&guard); let iter = guard.to_animation_value_iter( &mut context, &default_values, custom_properties.as_ref(), ); for value in iter { let id = value.id(); maybe_append_animation_value(id, Some(value)); } } } } #[no_mangle] pub extern "C" fn Servo_GetAnimationValues( declarations: RawServoDeclarationBlockBorrowed, element: RawGeckoElementBorrowed, style: ServoStyleContextBorrowed, raw_data: RawServoStyleSetBorrowed, animation_values: RawGeckoServoAnimationValueListBorrowedMut, ) { let data = PerDocumentStyleData::from_ffi(raw_data).borrow(); let metrics = get_metrics_provider_for_product(); let element = GeckoElement(element); let parent_element = element.inheritance_parent(); let parent_data = parent_element.as_ref().and_then(|e| e.borrow_data()); let parent_style = parent_data.as_ref().map(|d| d.styles.primary()).map(|x| &**x); let pseudo = style.pseudo(); let mut conditions = Default::default(); let mut context = create_context( &data, &metrics, &style, parent_style, pseudo.as_ref(), /* for_smil_animation = */ true, &mut conditions, ); let default_values = data.default_computed_values(); let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let declarations = Locked::<PropertyDeclarationBlock>::as_arc(&declarations); let guard = declarations.read_with(&guard); let iter = guard.to_animation_value_iter( &mut context, &default_values, None, // SMIL has no extra custom properties. ); for (index, anim) in iter.enumerate() { unsafe { animation_values.set_len((index + 1) as u32) }; animation_values[index].set_arc_leaky(Arc::new(anim)); } } #[no_mangle] pub extern "C" fn Servo_AnimationValue_Compute( element: RawGeckoElementBorrowed, declarations: RawServoDeclarationBlockBorrowed, style: ServoStyleContextBorrowed, raw_data: RawServoStyleSetBorrowed, ) -> RawServoAnimationValueStrong { let data = PerDocumentStyleData::from_ffi(raw_data).borrow(); let metrics = get_metrics_provider_for_product(); let element = GeckoElement(element); let parent_element = element.inheritance_parent(); let parent_data = parent_element.as_ref().and_then(|e| e.borrow_data()); let parent_style = parent_data.as_ref().map(|d| d.styles.primary()).map(|x| &**x); let pseudo = style.pseudo(); let mut conditions = Default::default(); let mut context = create_context( &data, &metrics, style, parent_style, pseudo.as_ref(), /* for_smil_animation = */ false, &mut conditions, ); let default_values = data.default_computed_values(); let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let declarations = Locked::<PropertyDeclarationBlock>::as_arc(&declarations); // We only compute the first element in declarations. match declarations.read_with(&guard).declaration_importance_iter().next() { Some((decl, imp)) if imp == Importance::Normal => { let animation = AnimationValue::from_declaration( decl, &mut context, None, // No extra custom properties for devtools. default_values, ); animation.map_or(RawServoAnimationValueStrong::null(), |value| { Arc::new(value).into_strong() }) }, _ => RawServoAnimationValueStrong::null() } } #[no_mangle] pub extern "C" fn Servo_AssertTreeIsClean(root: RawGeckoElementBorrowed) { if !cfg!(feature = "gecko_debug") { panic!("Calling Servo_AssertTreeIsClean in release build"); } let root = GeckoElement(root); debug!("Servo_AssertTreeIsClean: "); debug!("{:?}", ShowSubtreeData(root.as_node())); fn assert_subtree_is_clean<'le>(el: GeckoElement<'le>) { debug_assert!(!el.has_dirty_descendants() && !el.has_animation_only_dirty_descendants(), "{:?} has still dirty bit {:?} or animation-only dirty bit {:?}", el, el.has_dirty_descendants(), el.has_animation_only_dirty_descendants()); for child in el.traversal_children() { if let Some(child) = child.as_element() { assert_subtree_is_clean(child); } } } assert_subtree_is_clean(root); } #[no_mangle] pub extern "C" fn Servo_IsWorkerThread() -> bool { thread_state::get().is_worker() } enum Offset { Zero, One } fn fill_in_missing_keyframe_values( all_properties: &LonghandIdSet, timing_function: nsTimingFunctionBorrowed, longhands_at_offset: &LonghandIdSet, offset: Offset, keyframes: RawGeckoKeyframeListBorrowedMut, ) { // Return early if all animated properties are already set. if longhands_at_offset.contains_all(all_properties) { return; } let keyframe = match offset { Offset::Zero => unsafe { Gecko_GetOrCreateInitialKeyframe(keyframes, timing_function) }, Offset::One => unsafe { Gecko_GetOrCreateFinalKeyframe(keyframes, timing_function) }, }; // Append properties that have not been set at this offset. for property in all_properties.iter() { if !longhands_at_offset.contains(property) { unsafe { Gecko_AppendPropertyValuePair( &mut (*keyframe).mPropertyValues, property.to_nscsspropertyid() ); } } } } #[no_mangle] pub extern "C" fn Servo_StyleSet_GetKeyframesForName( raw_data: RawServoStyleSetBorrowed, name: *mut nsAtom, inherited_timing_function: nsTimingFunctionBorrowed, keyframes: RawGeckoKeyframeListBorrowedMut, ) -> bool { debug_assert!(keyframes.len() == 0, "keyframes should be initially empty"); let data = PerDocumentStyleData::from_ffi(raw_data).borrow(); let name = Atom::from(name); let animation = match data.stylist.get_animation(&name) { Some(animation) => animation, None => return false, }; let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let mut properties_set_at_current_offset = LonghandIdSet::new(); let mut properties_set_at_start = LonghandIdSet::new(); let mut properties_set_at_end = LonghandIdSet::new(); let mut has_complete_initial_keyframe = false; let mut has_complete_final_keyframe = false; let mut current_offset = -1.; // Iterate over the keyframe rules backwards so we can drop overridden // properties (since declarations in later rules override those in earlier // ones). for step in animation.steps.iter().rev() { if step.start_percentage.0 != current_offset { properties_set_at_current_offset.clear(); current_offset = step.start_percentage.0; } // Override timing_function if the keyframe has an animation-timing-function. let timing_function = match step.get_animation_timing_function(&guard) { Some(val) => val.into(), None => *inherited_timing_function, }; // Look for an existing keyframe with the same offset and timing // function or else add a new keyframe at the beginning of the keyframe // array. let keyframe = unsafe { Gecko_GetOrCreateKeyframeAtStart(keyframes, step.start_percentage.0 as f32, &timing_function) }; match step.value { KeyframesStepValue::ComputedValues => { // In KeyframesAnimation::from_keyframes if there is no 0% or // 100% keyframe at all, we will create a 'ComputedValues' step // to represent that all properties animated by the keyframes // animation should be set to the underlying computed value for // that keyframe. for property in animation.properties_changed.iter() { unsafe { Gecko_AppendPropertyValuePair( &mut (*keyframe).mPropertyValues, property.to_nscsspropertyid(), ); } } if current_offset == 0.0 { has_complete_initial_keyframe = true; } else if current_offset == 1.0 { has_complete_final_keyframe = true; } }, KeyframesStepValue::Declarations { ref block } => { let guard = block.read_with(&guard); let mut custom_properties = PropertyDeclarationBlock::new(); // Filter out non-animatable properties and properties with // !important. for declaration in guard.normal_declaration_iter() { let id = declaration.id(); let id = match id { PropertyDeclarationId::Longhand(id) => { // Skip the 'display' property because although it // is animatable from SMIL, it should not be // animatable from CSS Animations. if id == LonghandId::Display { continue; } if !id.is_animatable() { continue; } id } PropertyDeclarationId::Custom(..) => { custom_properties.push( declaration.clone(), Importance::Normal, DeclarationSource::CssOm, ); continue; } }; if properties_set_at_current_offset.contains(id) { continue; } let pair = unsafe { Gecko_AppendPropertyValuePair( &mut (*keyframe).mPropertyValues, id.to_nscsspropertyid(), ) }; unsafe { (*pair).mServoDeclarationBlock.set_arc_leaky( Arc::new(global_style_data.shared_lock.wrap( PropertyDeclarationBlock::with_one( declaration.clone(), Importance::Normal, ) )) ); } if current_offset == 0.0 { properties_set_at_start.insert(id); } else if current_offset == 1.0 { properties_set_at_end.insert(id); } properties_set_at_current_offset.insert(id); } if custom_properties.any_normal() { let pair = unsafe { Gecko_AppendPropertyValuePair( &mut (*keyframe).mPropertyValues, nsCSSPropertyID::eCSSPropertyExtra_variable, ) }; unsafe { (*pair).mServoDeclarationBlock.set_arc_leaky(Arc::new( global_style_data.shared_lock.wrap(custom_properties) )); } } }, } } // Append property values that are missing in the initial or the final keyframes. if !has_complete_initial_keyframe { fill_in_missing_keyframe_values( &animation.properties_changed, inherited_timing_function, &properties_set_at_start, Offset::Zero, keyframes, ); } if !has_complete_final_keyframe { fill_in_missing_keyframe_values( &animation.properties_changed, inherited_timing_function, &properties_set_at_end, Offset::One, keyframes, ); } true } #[no_mangle] pub extern "C" fn Servo_StyleSet_GetFontFaceRules( raw_data: RawServoStyleSetBorrowed, rules: RawGeckoFontFaceRuleListBorrowedMut, ) { let data = PerDocumentStyleData::from_ffi(raw_data).borrow(); debug_assert!(rules.len() == 0); let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let len: u32 = data .stylist .iter_extra_data_origins() .map(|(d, _)| d.font_faces.len() as u32) .sum(); // Reversed iterator because Gecko expects rules to appear sorted // UserAgent first, Author last. let font_face_iter = data .stylist .iter_extra_data_origins_rev() .flat_map(|(d, o)| d.font_faces.iter().zip(iter::repeat(o))); unsafe { rules.set_len(len) }; for (src, dest) in font_face_iter.zip(rules.iter_mut()) { dest.mRule = src.0.read_with(&guard).clone().forget(); dest.mSheetType = src.1.into(); } } #[no_mangle] pub extern "C" fn Servo_StyleSet_GetCounterStyleRule( raw_data: RawServoStyleSetBorrowed, name: *mut nsAtom, ) -> *mut nsCSSCounterStyleRule { let data = PerDocumentStyleData::from_ffi(raw_data).borrow(); unsafe { Atom::with(name, |name| { data.stylist .iter_extra_data_origins() .filter_map(|(d, _)| d.counter_styles.get(name)) .next() }) }.map(|rule| { let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); rule.read_with(&guard).get() }).unwrap_or(ptr::null_mut()) } #[no_mangle] pub extern "C" fn Servo_StyleSet_BuildFontFeatureValueSet( raw_data: RawServoStyleSetBorrowed, ) -> *mut gfxFontFeatureValueSet { let data = PerDocumentStyleData::from_ffi(raw_data).borrow(); let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let has_rule = data.stylist .iter_extra_data_origins() .any(|(d, _)| !d.font_feature_values.is_empty()); if !has_rule { return ptr::null_mut(); } let font_feature_values_iter = data.stylist .iter_extra_data_origins_rev() .flat_map(|(d, _)| d.font_feature_values.iter()); let set = unsafe { Gecko_ConstructFontFeatureValueSet() }; for src in font_feature_values_iter { let rule = src.read_with(&guard); rule.set_at_rules(set); } set } #[no_mangle] pub extern "C" fn Servo_StyleSet_ResolveForDeclarations( raw_data: RawServoStyleSetBorrowed, parent_style_context: ServoStyleContextBorrowedOrNull, declarations: RawServoDeclarationBlockBorrowed, ) -> ServoStyleContextStrong { let doc_data = PerDocumentStyleData::from_ffi(raw_data).borrow(); let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let guards = StylesheetGuards::same(&guard); let parent_style = match parent_style_context { Some(parent) => &*parent, None => doc_data.default_computed_values(), }; let declarations = Locked::<PropertyDeclarationBlock>::as_arc(&declarations); doc_data.stylist.compute_for_declarations( &guards, parent_style, declarations.clone_arc(), ).into() } #[no_mangle] pub extern "C" fn Servo_StyleSet_AddSizeOfExcludingThis( malloc_size_of: GeckoMallocSizeOf, malloc_enclosing_size_of: GeckoMallocSizeOf, sizes: *mut ServoStyleSetSizes, raw_data: RawServoStyleSetBorrowed ) { let data = PerDocumentStyleData::from_ffi(raw_data).borrow_mut(); let mut ops = MallocSizeOfOps::new(malloc_size_of.unwrap(), Some(malloc_enclosing_size_of.unwrap()), None); let sizes = unsafe { sizes.as_mut() }.unwrap(); data.add_size_of(&mut ops, sizes); } #[no_mangle] pub extern "C" fn Servo_UACache_AddSizeOf( malloc_size_of: GeckoMallocSizeOf, malloc_enclosing_size_of: GeckoMallocSizeOf, sizes: *mut ServoStyleSetSizes ) { let mut ops = MallocSizeOfOps::new(malloc_size_of.unwrap(), Some(malloc_enclosing_size_of.unwrap()), None); let sizes = unsafe { sizes.as_mut() }.unwrap(); add_size_of_ua_cache(&mut ops, sizes); } #[no_mangle] pub extern "C" fn Servo_StyleSet_MightHaveAttributeDependency( raw_data: RawServoStyleSetBorrowed, element: RawGeckoElementBorrowed, local_name: *mut nsAtom, ) -> bool { let data = PerDocumentStyleData::from_ffi(raw_data).borrow(); let element = GeckoElement(element); let mut has_dep = false; unsafe { Atom::with(local_name, |atom| { has_dep = data.stylist.might_have_attribute_dependency(atom); if !has_dep { // TODO(emilio): Consider optimizing this storing attribute // dependencies from UA sheets separately, so we could optimize // the above lookup if cut_off_inheritance is true. element.each_xbl_stylist(|stylist| { has_dep = has_dep || stylist.might_have_attribute_dependency(atom); }); } }) } has_dep } #[no_mangle] pub extern "C" fn Servo_StyleSet_HasStateDependency( raw_data: RawServoStyleSetBorrowed, element: RawGeckoElementBorrowed, state: u64, ) -> bool { let element = GeckoElement(element); let state = ElementState::from_bits_truncate(state); let data = PerDocumentStyleData::from_ffi(raw_data).borrow(); let mut has_dep = data.stylist.has_state_dependency(state); if !has_dep { // TODO(emilio): Consider optimizing this storing attribute // dependencies from UA sheets separately, so we could optimize // the above lookup if cut_off_inheritance is true. element.each_xbl_stylist(|stylist| { has_dep = has_dep || stylist.has_state_dependency(state); }); } has_dep } #[no_mangle] pub extern "C" fn Servo_StyleSet_HasDocumentStateDependency( raw_data: RawServoStyleSetBorrowed, state: u64, ) -> bool { let state = DocumentState::from_bits_truncate(state); let data = PerDocumentStyleData::from_ffi(raw_data).borrow(); data.stylist.has_document_state_dependency(state) } #[no_mangle] pub extern "C" fn Servo_GetCustomPropertyValue( computed_values: ServoStyleContextBorrowed, name: *const nsAString, value: *mut nsAString, ) -> bool { let custom_properties = match computed_values.custom_properties() { Some(p) => p, None => return false, }; let name = unsafe { Atom::from((&*name)) }; let computed_value = match custom_properties.get(&name) { Some(v) => v, None => return false, }; computed_value.to_css(unsafe { value.as_mut().unwrap() }).unwrap(); true } #[no_mangle] pub extern "C" fn Servo_GetCustomPropertiesCount(computed_values: ServoStyleContextBorrowed) -> u32 { match computed_values.custom_properties() { Some(p) => p.len() as u32, None => 0, } } #[no_mangle] pub extern "C" fn Servo_GetCustomPropertyNameAt( computed_values: ServoStyleContextBorrowed, index: u32, name: *mut nsAString, ) -> bool { let custom_properties = match computed_values.custom_properties() { Some(p) => p, None => return false, }; let property_name = match custom_properties.get_key_at(index) { Some(n) => n, None => return false, }; let name = unsafe { name.as_mut().unwrap() }; name.assign(&*property_name.as_slice()); true } #[no_mangle] pub unsafe extern "C" fn Servo_ReleaseArcStringData(string: *const RawOffsetArc<RustString>) { let string = string as *const RawOffsetArc<String>; // Cause RawOffsetArc::drop to run, releasing the strong reference to the string data. let _ = ptr::read(string); } #[no_mangle] pub unsafe extern "C" fn Servo_CloneArcStringData( string: *const RawOffsetArc<RustString>, ) -> RawOffsetArc<RustString> { let string = string as *const RawOffsetArc<String>; let cloned = (*string).clone(); mem::transmute::<_, RawOffsetArc<RustString>>(cloned) } #[no_mangle] pub unsafe extern "C" fn Servo_GetArcStringData( string: *const RustString, utf8_chars: *mut *const u8, utf8_len: *mut u32, ) { let string = &*(string as *const String); *utf8_len = string.len() as u32; *utf8_chars = string.as_ptr(); } #[no_mangle] pub extern "C" fn Servo_ProcessInvalidations( set: RawServoStyleSetBorrowed, element: RawGeckoElementBorrowed, snapshots: *const ServoElementSnapshotTable, ) { debug_assert!(!snapshots.is_null()); let element = GeckoElement(element); debug_assert!(element.has_snapshot()); debug_assert!(!element.handled_snapshot()); let mut data = element.mutate_data(); debug_assert!(data.is_some()); let global_style_data = &*GLOBAL_STYLE_DATA; let guard = global_style_data.shared_lock.read(); let per_doc_data = PerDocumentStyleData::from_ffi(set).borrow(); let shared_style_context = create_shared_context(&global_style_data, &guard, &per_doc_data, TraversalFlags::empty(), unsafe { &*snapshots }); let mut data = data.as_mut().map(|d| &mut **d); if let Some(ref mut data) = data { // FIXME(emilio): an nth-index cache could be worth here, even // if temporary? // // Also, ideally we could share them across all the elements? let result = data.invalidate_style_if_needed( element, &shared_style_context, None, None, ); if result.has_invalidated_siblings() { let parent = element.traversal_parent().expect("How could we invalidate siblings without a common parent?"); unsafe { parent.set_dirty_descendants(); bindings::Gecko_NoteDirtySubtreeForInvalidation(parent.0); } } else if result.has_invalidated_descendants() { unsafe { bindings::Gecko_NoteDirtySubtreeForInvalidation(element.0) }; } else if result.has_invalidated_self() { unsafe { bindings::Gecko_NoteDirtyElement(element.0) }; } } } #[no_mangle] pub extern "C" fn Servo_HasPendingRestyleAncestor(element: RawGeckoElementBorrowed) -> bool { let mut element = Some(GeckoElement(element)); while let Some(e) = element { if e.has_animations() { return true; } // If the element needs a frame, it means that we haven't styled it yet // after it got inserted in the document, and thus we may need to do // that for transitions and animations to trigger. if e.needs_frame() { return true; } if let Some(data) = e.borrow_data() { if !data.hint.is_empty() { return true; } } element = e.traversal_parent(); } false } #[no_mangle] pub unsafe extern "C" fn Servo_SelectorList_Parse( selector_list: *const nsACString, ) -> *mut RawServoSelectorList { use style::selector_parser::SelectorParser; debug_assert!(!selector_list.is_null()); let input = (*selector_list).as_str_unchecked(); let selector_list = match SelectorParser::parse_author_origin_no_namespace(&input) { Ok(selector_list) => selector_list, Err(..) => return ptr::null_mut(), }; Box::into_raw(Box::new(selector_list)) as *mut RawServoSelectorList } #[no_mangle] pub unsafe extern "C" fn Servo_SelectorList_Drop(list: RawServoSelectorListOwned) { let _ = list.into_box::<::selectors::SelectorList<SelectorImpl>>(); } fn parse_color(value: &str) -> Result<specified::Color, ()> { let mut input = ParserInput::new(value); let mut parser = Parser::new(&mut input); parser.parse_entirely(specified::Color::parse_color).map_err(|_| ()) } #[no_mangle] pub extern "C" fn Servo_IsValidCSSColor( value: *const nsAString, ) -> bool { let value = unsafe { (*value).to_string() }; parse_color(&value).is_ok() } #[no_mangle] pub extern "C" fn Servo_ComputeColor( raw_data: RawServoStyleSetBorrowedOrNull, current_color: structs::nscolor, value: *const nsAString, result_color: *mut structs::nscolor, ) -> bool { use style::gecko; let current_color = gecko::values::convert_nscolor_to_rgba(current_color); let value = unsafe { (*value).to_string() }; let result_color = unsafe { result_color.as_mut().unwrap() }; match parse_color(&value) { Ok(specified_color) => { let computed_color = match raw_data { Some(raw_data) => { let data = PerDocumentStyleData::from_ffi(raw_data).borrow(); let metrics = get_metrics_provider_for_product(); let mut conditions = Default::default(); let context = create_context( &data, &metrics, data.stylist.device().default_computed_values(), /* parent_style = */ None, /* pseudo = */ None, /* for_smil_animation = */ false, &mut conditions, ); specified_color.to_computed_color(Some(&context)) } None => { specified_color.to_computed_color(None) } }; match computed_color { Some(computed_color) => { let rgba = computed_color.to_rgba(current_color); *result_color = gecko::values::convert_rgba_to_nscolor(&rgba); true } None => false, } } Err(_) => false, } } #[no_mangle] pub extern "C" fn Servo_ParseIntersectionObserverRootMargin( value: *const nsAString, result: *mut structs::nsCSSRect, ) -> bool { let value = unsafe { value.as_ref().unwrap().to_string() }; let result = unsafe { result.as_mut().unwrap() }; let mut input = ParserInput::new(&value); let mut parser = Parser::new(&mut input); let url_data = unsafe { dummy_url_data() }; let context = ParserContext::new( Origin::Author, url_data, Some(CssRuleType::Style), ParsingMode::DEFAULT, QuirksMode::NoQuirks, ); let margin = parser.parse_entirely(|p| { IntersectionObserverRootMargin::parse(&context, p) }); match margin { Ok(margin) => { let rect = margin.0; result.mTop.set_from(rect.0); result.mRight.set_from(rect.1); result.mBottom.set_from(rect.2); result.mLeft.set_from(rect.3); true } Err(..) => false, } } #[no_mangle] pub unsafe extern "C" fn Servo_SourceSizeList_Parse( value: *const nsACString, ) -> *mut RawServoSourceSizeList { let value = (*value).as_str_unchecked(); let mut input = ParserInput::new(value); let mut parser = Parser::new(&mut input); let context = ParserContext::new( Origin::Author, dummy_url_data(), Some(CssRuleType::Style), ParsingMode::DEFAULT, QuirksMode::NoQuirks, ); // NB: Intentionally not calling parse_entirely. let list = SourceSizeList::parse(&context, &mut parser); Box::into_raw(Box::new(list)) as *mut _ } #[no_mangle] pub unsafe extern "C" fn Servo_SourceSizeList_Evaluate( raw_data: RawServoStyleSetBorrowed, list: RawServoSourceSizeListBorrowedOrNull, ) -> i32 { let doc_data = PerDocumentStyleData::from_ffi(raw_data).borrow(); let device = doc_data.stylist.device(); let quirks_mode = doc_data.stylist.quirks_mode(); let result = match list { Some(list) => { SourceSizeList::from_ffi(list).evaluate(device, quirks_mode) } None => { SourceSizeList::empty().evaluate(device, quirks_mode) } }; result.0 } #[no_mangle] pub unsafe extern "C" fn Servo_SourceSizeList_Drop(list: RawServoSourceSizeListOwned) { let _ = list.into_box::<SourceSizeList>(); }<|fim▁end|>
pub extern "C" fn Servo_ParseStyleAttribute( data: *const nsACString, raw_extra_data: *mut URLExtraData,
<|file_name|>main.cpp<|end_file_name|><|fim▁begin|>class NumMatrix { public: NumMatrix(vector<vector<int>> &matrix) { // error handle if (matrix.size() == 0 || matrix[0].size() == 0) { _m = 0; _n = 0; return; } _m = matrix.size(); _n = matrix[0].size(); _sum = vector<vector<long long>>(_m + 1, vector<long long>(_n + 1, 0)); for (int i = 0; i < _m; i++) { for (int j = 0; j < _n; j++) { _sum[i + 1][j + 1] = _sum[i][j + 1] + _sum[i + 1][j] - _sum[i][j] + matrix[i][j]; } } } int sumRegion(int row1, int col1, int row2, int col2) { if (row2 < row1 || col2 < col1) { return 0; } if (row2 >= _m || col2 >= _n || row2 < 0 || col2 < 0) { return 0; } if (row1 >= _m || col1 >= _n || row1 < 0 || col1 < 0) {<|fim▁hole|> return 0; } if (_m == 0 || _n == 0) { return 0; } //注意 边界条件 return _sum[row2 + 1][col2 + 1] - _sum[row2 + 1][col1] - _sum[row1][col2 + 1] + _sum[row1][col1]; } private: vector<vector<long long>> _sum; int _m; int _n; }; // Your NumMatrix object will be instantiated and called as such: // NumMatrix numMatrix(matrix); // numMatrix.sumRegion(0, 1, 2, 3); // numMatrix.sumRegion(1, 2, 3, 4);<|fim▁end|>
<|file_name|>a.py<|end_file_name|><|fim▁begin|><|fim▁hole|>print(s[:4],s[4:])<|fim▁end|>
s = input().rstrip()
<|file_name|>http_request.go<|end_file_name|><|fim▁begin|>package data_table import ( "bytes" "encoding/json" "fmt" "github.com/julienschmidt/httprouter" "net/http" "net/url" ) func DataStoreHandler(tableStore TableStore) func(http.ResponseWriter, *http.Request, httprouter.Params) { return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { request := newSearchRequest(r, ps) result := tableStore.QueryData(request) jsonBytes, _ := json.Marshal(result) fmt.Fprint(w, string(jsonBytes)) } } func TreePostFormValues(values url.Values) map[string]interface{} {<|fim▁hole|> res := make(map[string]interface{}) var currValue map[string]interface{} for rawKey, value := range values { if vs := value; len(vs) > 0 { currValue = res keyPath := ParseKey(rawKey) lastIndex := len(keyPath) - 1 for index, key := range keyPath { if index == lastIndex { currValue[key] = vs[0] } else { if _, ok := currValue[key]; !ok { currValue[key] = make(map[string]interface{}) } currValue = currValue[key].(map[string]interface{}) } } } } return res } func ParseKey(key string) []string { res := make([]string, 0) var currKey bytes.Buffer for _, char := range key { if char == '[' || char == ']' { if currKey.Len() > 0 { res = append(res, currKey.String()) currKey.Reset() } } else { currKey.WriteRune(char) } } if currKey.Len() > 0 { res = append(res, currKey.String()) } return res }<|fim▁end|>
<|file_name|>translation.py<|end_file_name|><|fim▁begin|>import json from pprint import pprint import requests from telegram import Update, Bot from telegram.ext import CommandHandler from tg_bot import dispatcher # Open API key API_KEY = "6ae0c3a0-afdc-4532-a810-82ded0054236" URL = "http://services.gingersoftware.com/Ginger/correct/json/GingerTheText" def translate(bot: Bot, update: Update): if update.effective_message.reply_to_message: msg = update.effective_message.reply_to_message params = dict( lang="US", clientVersion="2.0", apiKey=API_KEY, text=msg.text ) res = requests.get(URL, params=params) # print(res) # print(res.text) pprint(json.loads(res.text)) changes = json.loads(res.text).get('LightGingerTheTextResult') curr_string = ""<|fim▁hole|> for change in changes: start = change.get('From') end = change.get('To') + 1 suggestions = change.get('Suggestions') if suggestions: sugg_str = suggestions[0].get('Text') # should look at this list more curr_string += msg.text[prev_end:start] + sugg_str prev_end = end curr_string += msg.text[prev_end:] print(curr_string) update.effective_message.reply_text(curr_string) __help__ = """ - /t: while replying to a message, will reply with a grammar corrected version """ __mod_name__ = "Translator" TRANSLATE_HANDLER = CommandHandler('t', translate) dispatcher.add_handler(TRANSLATE_HANDLER)<|fim▁end|>
prev_end = 0
<|file_name|>CreateSessionTest.java<|end_file_name|><|fim▁begin|>// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.openqa.selenium.grid.node.local; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.junit.Test; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; import org.openqa.selenium.events.local.GuavaEventBus; import org.openqa.selenium.grid.data.CreateSessionRequest; import org.openqa.selenium.grid.data.CreateSessionResponse; import org.openqa.selenium.grid.data.Session; import org.openqa.selenium.grid.node.Node; import org.openqa.selenium.grid.testing.TestSessionFactory; import org.openqa.selenium.json.Json; import org.openqa.selenium.remote.ErrorCodes; import org.openqa.selenium.remote.http.HttpRequest; import org.openqa.selenium.remote.tracing.DefaultTestTracer; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.json.Json.MAP_TYPE; import static org.openqa.selenium.remote.Dialect.OSS; import static org.openqa.selenium.remote.Dialect.W3C; import static org.openqa.selenium.remote.http.Contents.utf8String; import static org.openqa.selenium.remote.http.HttpMethod.POST; public class CreateSessionTest { private final Json json = new Json(); private final Capabilities stereotype = new ImmutableCapabilities("cheese", "brie"); @Test public void shouldAcceptAW3CPayload() throws URISyntaxException { String payload = json.toJson(ImmutableMap.of( "capabilities", ImmutableMap.of( "alwaysMatch", ImmutableMap.of("cheese", "brie")))); HttpRequest request = new HttpRequest(POST, "/session"); request.setContent(utf8String(payload)); URI uri = new URI("http://example.com"); Node node = LocalNode.builder( DefaultTestTracer.createTracer(), new GuavaEventBus(), uri, uri, null) .add(stereotype, new TestSessionFactory((id, caps) -> new Session(id, uri, caps))) .build(); CreateSessionResponse sessionResponse = node.newSession( new CreateSessionRequest( ImmutableSet.of(W3C), stereotype, ImmutableMap.of())) .orElseThrow(() -> new AssertionError("Unable to create session")); Map<String, Object> all = json.toType( new String(sessionResponse.getDownstreamEncodedResponse(), UTF_8), MAP_TYPE); // Ensure that there's no status field (as this is used by the protocol handshake to determine // whether the session is using the JWP or the W3C dialect. assertThat(all.containsKey("status")).isFalse(); // Now check the fields required by the spec Map<?, ?> value = (Map<?, ?>) all.get("value"); assertThat(value.get("sessionId")).isInstanceOf(String.class); assertThat(value.get("capabilities")).isInstanceOf(Map.class); } @Test public void shouldOnlyAcceptAJWPPayloadIfConfiguredTo() { // TODO: implement shouldOnlyAcceptAJWPPayloadIfConfiguredTo test } @Test public void ifOnlyW3CPayloadSentAndRemoteEndIsJWPOnlyFailSessionCreationIfJWPNotConfigured() { // TODO: implement ifOnlyW3CPayloadSentAndRemoteEndIsJWPOnlyFailSessionCreationIfJWPNotConfigured test } @Test public void ifOnlyJWPPayloadSentResponseShouldBeJWPOnlyIfJWPConfigured() throws URISyntaxException { String payload = json.toJson(ImmutableMap.of( "desiredCapabilities", ImmutableMap.of("cheese", "brie"))); HttpRequest request = new HttpRequest(POST, "/session"); request.setContent(utf8String(payload)); URI uri = new URI("http://example.com"); Node node = LocalNode.builder( DefaultTestTracer.createTracer(), new GuavaEventBus(), uri, uri, null) .add(stereotype, new TestSessionFactory((id, caps) -> new Session(id, uri, caps))) .build(); CreateSessionResponse sessionResponse = node.newSession( new CreateSessionRequest( ImmutableSet.of(OSS), stereotype, ImmutableMap.of())) .orElseThrow(() -> new AssertionError("Unable to create session")); Map<String, Object> all = json.toType( new String(sessionResponse.getDownstreamEncodedResponse(), UTF_8), MAP_TYPE); <|fim▁hole|> // The session id is a top level field assertThat(all.get("sessionId")).isInstanceOf(String.class); // And the value should contain the capabilities. assertThat(all.get("value")).isInstanceOf(Map.class); } @Test public void shouldPreferUsingTheW3CProtocol() throws URISyntaxException { String payload = json.toJson(ImmutableMap.of( "desiredCapabilities", ImmutableMap.of( "cheese", "brie"), "capabilities", ImmutableMap.of( "alwaysMatch", ImmutableMap.of("cheese", "brie")))); HttpRequest request = new HttpRequest(POST, "/session"); request.setContent(utf8String(payload)); URI uri = new URI("http://example.com"); Node node = LocalNode.builder( DefaultTestTracer.createTracer(), new GuavaEventBus(), uri, uri, null) .add(stereotype, new TestSessionFactory((id, caps) -> new Session(id, uri, caps))) .build(); CreateSessionResponse sessionResponse = node.newSession( new CreateSessionRequest( ImmutableSet.of(W3C), stereotype, ImmutableMap.of())) .orElseThrow(() -> new AssertionError("Unable to create session")); Map<String, Object> all = json.toType( new String(sessionResponse.getDownstreamEncodedResponse(), UTF_8), MAP_TYPE); // Ensure that there's no status field (as this is used by the protocol handshake to determine // whether the session is using the JWP or the W3C dialect. assertThat(all.containsKey("status")).isFalse(); // Now check the fields required by the spec Map<?, ?> value = (Map<?, ?>) all.get("value"); assertThat(value.get("sessionId")).isInstanceOf(String.class); assertThat(value.get("capabilities")).isInstanceOf(Map.class); } @Test public void sessionDataShouldBeCorrectRegardlessOfPayloadProtocol() { // TODO: implement sessionDataShouldBeCorrectRegardlessOfPayloadProtocol test } @Test public void shouldSupportProtocolConversion() { // TODO: implement shouldSupportProtocolConversion test } }<|fim▁end|>
// The status field is used by local ends to determine whether or not the session is a JWP one. assertThat(all.get("status")).matches(obj -> ((Number) obj).intValue() == ErrorCodes.SUCCESS);
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//! A TIS-100 emulator. //! //! # Example //! //! ``` //! use tis_100::save::parse_save; //! use tis_100::machine::Sandbox; //! //! // This program reads the value from the console and simply passes it to the console output. //! let src = "@1\nMOV UP DOWN\n@5\nMOV UP DOWN\n@9\nMOV UP RIGHT\n@10\nMOV LEFT DOWN\n"; //! //! let save = parse_save(src).unwrap(); //! let mut sandbox = Sandbox::from_save(&save); //! //! sandbox.write_console(42); //! //! for _ in 0..5 { //! sandbox.step(); //! } //! //! assert_eq!(sandbox.read_console(), Some(42)); //! ``` <|fim▁hole|>pub mod lex; pub mod parse; pub mod io; pub mod node; pub mod image; pub mod save; pub mod spec; pub mod machine;<|fim▁end|>
extern crate hlua; extern crate vec_map; pub mod core;
<|file_name|>fragment.rs<|end_file_name|><|fim▁begin|>/* 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/. */ //! The `Fragment` type, which represents the leaves of the layout tree. #![deny(unsafe_code)] use canvas_traits::CanvasMsg; use context::LayoutContext; use floats::ClearType; use flow; use flow::Flow; use flow_ref::FlowRef; use incremental::{self, RestyleDamage}; use inline::{InlineFragmentContext, InlineFragmentNodeInfo, InlineMetrics}; use layout_debug; use model::{self, IntrinsicISizes, IntrinsicISizesContribution, MaybeAuto, specified}; use text; use wrapper::{PseudoElementType, ThreadSafeLayoutNode}; use euclid::{Point2D, Rect, Size2D}; use gfx::display_list::{BLUR_INFLATION_FACTOR, OpaqueNode}; use gfx::text::glyph::CharIndex; use gfx::text::text_run::{TextRun, TextRunSlice}; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::{ConstellationChan, Msg, PipelineId, SubpageId}; use net_traits::image::base::Image; use net_traits::image_cache_task::UsePlaceholder; use rustc_serialize::{Encodable, Encoder}; use std::borrow::ToOwned; use std::cmp::{max, min}; use std::collections::LinkedList; use std::fmt; use std::sync::{Arc, Mutex}; use string_cache::Atom; use style::computed_values::content::ContentItem; use style::computed_values::{border_collapse, clear, mix_blend_mode, overflow_wrap, position}; use style::computed_values::{text_align, text_decoration, white_space, word_break}; use style::computed_values::transform_style; use style::properties::{self, ComputedValues, cascade_anonymous}; use style::values::computed::{LengthOrPercentage, LengthOrPercentageOrAuto}; use style::values::computed::{LengthOrPercentageOrNone}; use text::TextRunScanner; use url::Url; use util::geometry::{Au, ZERO_POINT}; use util::logical_geometry::{LogicalRect, LogicalSize, LogicalMargin, WritingMode}; use util::range::*; use util::str::{is_whitespace, slice_chars}; use util; /// Fragments (`struct Fragment`) are the leaves of the layout tree. They cannot position /// themselves. In general, fragments do not have a simple correspondence with CSS fragments in the /// specification: /// /// * Several fragments may correspond to the same CSS box or DOM node. For example, a CSS text box /// broken across two lines is represented by two fragments. /// /// * Some CSS fragments are not created at all, such as some anonymous block fragments induced by /// inline fragments with block-level sibling fragments. In that case, Servo uses an `InlineFlow` /// with `BlockFlow` siblings; the `InlineFlow` is block-level, but not a block container. It is /// positioned as if it were a block fragment, but its children are positioned according to /// inline flow. /// /// A `SpecificFragmentInfo::Generic` is an empty fragment that contributes only borders, margins, /// padding, and backgrounds. It is analogous to a CSS nonreplaced content box. /// /// A fragment's type influences how its styles are interpreted during layout. For example, /// replaced content such as images are resized differently from tables, text, or other content. /// Different types of fragments may also contain custom data; for example, text fragments contain /// text. /// /// Do not add fields to this structure unless they're really really mega necessary! Fragments get /// moved around a lot and thus their size impacts performance of layout quite a bit. /// /// FIXME(#2260, pcwalton): This can be slimmed down some by (at least) moving `inline_context` /// to be on `InlineFlow` only. #[derive(Clone)] pub struct Fragment { /// An opaque reference to the DOM node that this `Fragment` originates from. pub node: OpaqueNode, /// The CSS style of this fragment. pub style: Arc<ComputedValues>, /// The position of this fragment relative to its owning flow. The size includes padding and /// border, but not margin. /// /// NB: This does not account for relative positioning. /// NB: Collapsed borders are not included in this. pub border_box: LogicalRect<Au>, /// The sum of border and padding; i.e. the distance from the edge of the border box to the /// content edge of the fragment. pub border_padding: LogicalMargin<Au>, /// The margin of the content box. pub margin: LogicalMargin<Au>, /// Info specific to the kind of fragment. Keep this enum small. pub specific: SpecificFragmentInfo, /// Holds the style context information for fragments that are part of an inline formatting /// context. pub inline_context: Option<InlineFragmentContext>, /// How damaged this fragment is since last reflow. pub restyle_damage: RestyleDamage, /// The pseudo-element that this fragment represents. pub pseudo: PseudoElementType<()>, /// A debug ID that is consistent for the life of this fragment (via transform etc). pub debug_id: u16, } impl Encodable for Fragment { fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_struct("fragment", 0, |e| { try!(e.emit_struct_field("id", 0, |e| self.debug_id().encode(e))); try!(e.emit_struct_field("border_box", 1, |e| self.border_box.encode(e))); e.emit_struct_field("margin", 2, |e| self.margin.encode(e)) }) } } /// Info specific to the kind of fragment. /// /// Keep this enum small. As in, no more than one word. Or pcwalton will yell at you. #[derive(Clone)] pub enum SpecificFragmentInfo { Generic, /// A piece of generated content that cannot be resolved into `ScannedText` until the generated /// content resolution phase (e.g. an ordered list item marker). GeneratedContent(Box<GeneratedContentInfo>), Iframe(Box<IframeFragmentInfo>), Image(Box<ImageFragmentInfo>), Canvas(Box<CanvasFragmentInfo>), /// A hypothetical box (see CSS 2.1 § 10.3.7) for an absolutely-positioned block that was /// declared with `display: inline;`. InlineAbsoluteHypothetical(InlineAbsoluteHypotheticalFragmentInfo), InlineBlock(InlineBlockFragmentInfo), /// An inline fragment that establishes an absolute containing block for its descendants (i.e. /// a positioned inline fragment). InlineAbsolute(InlineAbsoluteFragmentInfo), ScannedText(Box<ScannedTextFragmentInfo>), Table, TableCell, TableColumn(TableColumnFragmentInfo), TableRow, TableWrapper, UnscannedText(UnscannedTextFragmentInfo), } impl SpecificFragmentInfo { fn restyle_damage(&self) -> RestyleDamage { let flow = match *self { SpecificFragmentInfo::Canvas(_) | SpecificFragmentInfo::GeneratedContent(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::ScannedText(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableColumn(_) | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper | SpecificFragmentInfo::UnscannedText(_) | SpecificFragmentInfo::Generic => return RestyleDamage::empty(), SpecificFragmentInfo::InlineAbsoluteHypothetical(ref info) => &info.flow_ref, SpecificFragmentInfo::InlineAbsolute(ref info) => &info.flow_ref, SpecificFragmentInfo::InlineBlock(ref info) => &info.flow_ref, }; flow::base(&**flow).restyle_damage } pub fn get_type(&self) -> &'static str { match *self { SpecificFragmentInfo::Canvas(_) => "SpecificFragmentInfo::Canvas", SpecificFragmentInfo::Generic => "SpecificFragmentInfo::Generic", SpecificFragmentInfo::GeneratedContent(_) => "SpecificFragmentInfo::GeneratedContent", SpecificFragmentInfo::Iframe(_) => "SpecificFragmentInfo::Iframe", SpecificFragmentInfo::Image(_) => "SpecificFragmentInfo::Image", SpecificFragmentInfo::InlineAbsolute(_) => "SpecificFragmentInfo::InlineAbsolute", SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => "SpecificFragmentInfo::InlineAbsoluteHypothetical", SpecificFragmentInfo::InlineBlock(_) => "SpecificFragmentInfo::InlineBlock", SpecificFragmentInfo::ScannedText(_) => "SpecificFragmentInfo::ScannedText", SpecificFragmentInfo::Table => "SpecificFragmentInfo::Table", SpecificFragmentInfo::TableCell => "SpecificFragmentInfo::TableCell", SpecificFragmentInfo::TableColumn(_) => "SpecificFragmentInfo::TableColumn", SpecificFragmentInfo::TableRow => "SpecificFragmentInfo::TableRow", SpecificFragmentInfo::TableWrapper => "SpecificFragmentInfo::TableWrapper", SpecificFragmentInfo::UnscannedText(_) => "SpecificFragmentInfo::UnscannedText", } } } impl fmt::Debug for SpecificFragmentInfo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SpecificFragmentInfo::ScannedText(ref info) => { write!(f, " \"{}\"", slice_chars(&*info.run.text, info.range.begin().get() as usize, info.range.end().get() as usize)) } _ => Ok(()) } } } /// Clamp a value obtained from style_length, based on min / max lengths. fn clamp_size(size: Au, min_size: LengthOrPercentage, max_size: LengthOrPercentageOrNone, container_size: Au) -> Au { let min_size = model::specified(min_size, container_size); let max_size = model::specified_or_none(max_size, container_size); max(min_size, match max_size { None => size, Some(max_size) => min(size, max_size), }) } /// Information for generated content. #[derive(Clone)] pub enum GeneratedContentInfo { ListItem, ContentItem(ContentItem), } /// A hypothetical box (see CSS 2.1 § 10.3.7) for an absolutely-positioned block that was declared /// with `display: inline;`. /// /// FIXME(pcwalton): Stop leaking this `FlowRef` to layout; that is not memory safe because layout /// can clone it. #[derive(Clone)] pub struct InlineAbsoluteHypotheticalFragmentInfo { pub flow_ref: FlowRef, } impl InlineAbsoluteHypotheticalFragmentInfo { pub fn new(flow_ref: FlowRef) -> InlineAbsoluteHypotheticalFragmentInfo { InlineAbsoluteHypotheticalFragmentInfo { flow_ref: flow_ref, } } } /// A fragment that represents an inline-block element. /// /// FIXME(pcwalton): Stop leaking this `FlowRef` to layout; that is not memory safe because layout /// can clone it. #[derive(Clone)] pub struct InlineBlockFragmentInfo { pub flow_ref: FlowRef, } impl InlineBlockFragmentInfo { pub fn new(flow_ref: FlowRef) -> InlineBlockFragmentInfo { InlineBlockFragmentInfo { flow_ref: flow_ref, } } } /// An inline fragment that establishes an absolute containing block for its descendants (i.e. /// a positioned inline fragment). /// /// FIXME(pcwalton): Stop leaking this `FlowRef` to layout; that is not memory safe because layout /// can clone it. #[derive(Clone)] pub struct InlineAbsoluteFragmentInfo { pub flow_ref: FlowRef, } impl InlineAbsoluteFragmentInfo { pub fn new(flow_ref: FlowRef) -> InlineAbsoluteFragmentInfo { InlineAbsoluteFragmentInfo { flow_ref: flow_ref, } } } #[derive(Clone)] pub struct CanvasFragmentInfo { pub replaced_image_fragment_info: ReplacedImageFragmentInfo, pub renderer_id: Option<usize>, pub ipc_renderer: Option<Arc<Mutex<IpcSender<CanvasMsg>>>>, } impl CanvasFragmentInfo { pub fn new(node: &ThreadSafeLayoutNode) -> CanvasFragmentInfo { CanvasFragmentInfo { replaced_image_fragment_info: ReplacedImageFragmentInfo::new(node, Some(Au::from_px(node.canvas_width() as i32)), Some(Au::from_px(node.canvas_height() as i32))), renderer_id: node.canvas_renderer_id(), ipc_renderer: node.canvas_ipc_renderer() .map(|renderer| Arc::new(Mutex::new(renderer))), } } /// Returns the original inline-size of the canvas. pub fn canvas_inline_size(&self) -> Au { self.replaced_image_fragment_info.dom_inline_size.unwrap_or(Au(0)) } /// Returns the original block-size of the canvas. pub fn canvas_block_size(&self) -> Au { self.replaced_image_fragment_info.dom_block_size.unwrap_or(Au(0)) } } /// A fragment that represents a replaced content image and its accompanying borders, shadows, etc. #[derive(Clone)] pub struct ImageFragmentInfo { /// The image held within this fragment. pub replaced_image_fragment_info: ReplacedImageFragmentInfo, pub image: Option<Arc<Image>>, } impl ImageFragmentInfo { /// Creates a new image fragment from the given URL and local image cache. /// /// FIXME(pcwalton): The fact that image fragments store the cache in the fragment makes little /// sense to me. pub fn new(node: &ThreadSafeLayoutNode, url: Option<Url>, layout_context: &LayoutContext) -> ImageFragmentInfo { fn convert_length(node: &ThreadSafeLayoutNode, name: &Atom) -> Option<Au> { let element = node.as_element(); element.get_attr(&ns!(""), name) .and_then(|string| string.parse().ok()) .map(Au::from_px) } let image = url.and_then(|url| { layout_context.get_or_request_image(url, UsePlaceholder::Yes) }); ImageFragmentInfo { replaced_image_fragment_info: ReplacedImageFragmentInfo::new(node, convert_length(node, &atom!("width")), convert_length(node, &atom!("height"))), image: image, } } /// Returns the original inline-size of the image. pub fn image_inline_size(&mut self) -> Au { match self.image { Some(ref image) => { Au::from_px(if self.replaced_image_fragment_info.writing_mode_is_vertical { image.height } else { image.width } as i32) } None => Au(0) } } /// Returns the original block-size of the image. pub fn image_block_size(&mut self) -> Au { match self.image { Some(ref image) => { Au::from_px(if self.replaced_image_fragment_info.writing_mode_is_vertical { image.width } else { image.height } as i32) } None => Au(0) } } /// Tile an image pub fn tile_image(position: &mut Au, size: &mut Au, virtual_position: Au, image_size: u32) { let image_size = image_size as i32; let delta_pixels = (virtual_position - *position).to_px(); let tile_count = (delta_pixels + image_size - 1) / image_size; let offset = Au::from_px(image_size * tile_count); let new_position = virtual_position - offset; *size = *position - new_position + *size; *position = new_position; } } #[derive(Clone)] pub struct ReplacedImageFragmentInfo { pub computed_inline_size: Option<Au>, pub computed_block_size: Option<Au>, pub dom_inline_size: Option<Au>, pub dom_block_size: Option<Au>, pub writing_mode_is_vertical: bool, } impl ReplacedImageFragmentInfo { pub fn new(node: &ThreadSafeLayoutNode, dom_width: Option<Au>, dom_height: Option<Au>) -> ReplacedImageFragmentInfo { let is_vertical = node.style().writing_mode.is_vertical(); ReplacedImageFragmentInfo { computed_inline_size: None, computed_block_size: None, dom_inline_size: if is_vertical { dom_height } else { dom_width }, dom_block_size: if is_vertical { dom_width } else { dom_height }, writing_mode_is_vertical: is_vertical, } } /// Returns the calculated inline-size of the image, accounting for the inline-size attribute. pub fn computed_inline_size(&self) -> Au { self.computed_inline_size.expect("image inline_size is not computed yet!") } /// Returns the calculated block-size of the image, accounting for the block-size attribute. pub fn computed_block_size(&self) -> Au { self.computed_block_size.expect("image block_size is not computed yet!") } // Return used value for inline-size or block-size. // // `dom_length`: inline-size or block-size as specified in the `img` tag. // `style_length`: inline-size as given in the CSS pub fn style_length(style_length: LengthOrPercentageOrAuto, dom_length: Option<Au>, container_size: Option<Au>) -> MaybeAuto { match (style_length, dom_length, container_size) { (LengthOrPercentageOrAuto::Length(length), _, _) => MaybeAuto::Specified(length), (LengthOrPercentageOrAuto::Percentage(pc), _, Some(container_size)) => { MaybeAuto::Specified(container_size.scale_by(pc)) } (LengthOrPercentageOrAuto::Percentage(_), _, None) => MaybeAuto::Auto, (LengthOrPercentageOrAuto::Auto, Some(dom_length), _) => MaybeAuto::Specified(dom_length), (LengthOrPercentageOrAuto::Auto, None, _) => MaybeAuto::Auto, } } pub fn calculate_replaced_inline_size(&mut self, style: &ComputedValues, noncontent_inline_size: Au, container_inline_size: Au, fragment_inline_size: Au, fragment_block_size: Au) -> Au { let style_inline_size = style.content_inline_size(); let style_block_size = style.content_block_size(); let style_min_inline_size = style.min_inline_size(); let style_max_inline_size = style.max_inline_size(); let style_min_block_size = style.min_block_size(); let style_max_block_size = style.max_block_size(); // TODO(ksh8281): compute border,margin let inline_size = ReplacedImageFragmentInfo::style_length( style_inline_size, self.dom_inline_size, Some(container_inline_size)); let inline_size = match inline_size { MaybeAuto::Auto => { let intrinsic_width = fragment_inline_size; let intrinsic_height = fragment_block_size; if intrinsic_height == Au(0) { intrinsic_width } else { let ratio = intrinsic_width.to_f32_px() / intrinsic_height.to_f32_px(); let specified_height = ReplacedImageFragmentInfo::style_length( style_block_size, self.dom_block_size, None); let specified_height = match specified_height { MaybeAuto::Auto => intrinsic_height, MaybeAuto::Specified(h) => h, }; let specified_height = clamp_size(specified_height, style_min_block_size, style_max_block_size, Au(0)); Au::from_f32_px(specified_height.to_f32_px() * ratio) } }, MaybeAuto::Specified(w) => w, }; let inline_size = clamp_size(inline_size, style_min_inline_size, style_max_inline_size, container_inline_size); self.computed_inline_size = Some(inline_size); inline_size + noncontent_inline_size } pub fn calculate_replaced_block_size(&mut self, style: &ComputedValues, noncontent_block_size: Au, containing_block_block_size: Option<Au>, fragment_inline_size: Au, fragment_block_size: Au) -> Au { // TODO(ksh8281): compute border,margin,padding let style_block_size = style.content_block_size(); let style_min_block_size = style.min_block_size(); let style_max_block_size = style.max_block_size(); let inline_size = self.computed_inline_size(); let block_size = ReplacedImageFragmentInfo::style_length( style_block_size, self.dom_block_size, containing_block_block_size); let block_size = match block_size { MaybeAuto::Auto => { let intrinsic_width = fragment_inline_size; let intrinsic_height = fragment_block_size; let scale = intrinsic_width.to_f32_px() / inline_size.to_f32_px(); Au::from_f32_px(intrinsic_height.to_f32_px() / scale) }, MaybeAuto::Specified(h) => { h } }; let block_size = clamp_size(block_size, style_min_block_size, style_max_block_size, Au(0)); self.computed_block_size = Some(block_size); block_size + noncontent_block_size } } /// A fragment that represents an inline frame (iframe). This stores the pipeline ID so that the /// size of this iframe can be communicated via the constellation to the iframe's own layout task. #[derive(Clone)] pub struct IframeFragmentInfo { /// The pipeline ID of this iframe. pub pipeline_id: PipelineId, /// The subpage ID of this iframe. pub subpage_id: SubpageId, } impl IframeFragmentInfo { /// Creates the information specific to an iframe fragment. pub fn new(node: &ThreadSafeLayoutNode) -> IframeFragmentInfo { let (pipeline_id, subpage_id) = node.iframe_pipeline_and_subpage_ids(); IframeFragmentInfo { pipeline_id: pipeline_id, subpage_id: subpage_id, } } #[inline] pub fn calculate_replaced_inline_size(&self, style: &ComputedValues, containing_size: Au) -> Au { // Calculate the replaced inline size (or default) as per CSS 2.1 § 10.3.2 IframeFragmentInfo::calculate_replaced_size(style.content_inline_size(), style.min_inline_size(), style.max_inline_size(), Some(containing_size), Au::from_px(300)) } #[inline] pub fn calculate_replaced_block_size(&self, style: &ComputedValues, containing_size: Option<Au>) -> Au { // Calculate the replaced block size (or default) as per CSS 2.1 § 10.3.2 IframeFragmentInfo::calculate_replaced_size(style.content_block_size(), style.min_block_size(), style.max_block_size(), containing_size, Au::from_px(150)) } fn calculate_replaced_size(content_size: LengthOrPercentageOrAuto, style_min_size: LengthOrPercentage, style_max_size: LengthOrPercentageOrNone, containing_size: Option<Au>, default_size: Au) -> Au { let computed_size = match (content_size, containing_size) { (LengthOrPercentageOrAuto::Length(length), _) => length, (LengthOrPercentageOrAuto::Percentage(pc), Some(container_size)) => container_size.scale_by(pc), (LengthOrPercentageOrAuto::Percentage(_), None) => default_size, (LengthOrPercentageOrAuto::Auto, _) => default_size, }; let containing_size = containing_size.unwrap_or(Au(0)); let size = clamp_size(computed_size, style_min_size, style_max_size, containing_size); size } } /// A scanned text fragment represents a single run of text with a distinct style. A `TextFragment` /// may be split into two or more fragments across line breaks. Several `TextFragment`s may /// correspond to a single DOM text node. Split text fragments are implemented by referring to /// subsets of a single `TextRun` object. #[derive(Clone)] pub struct ScannedTextFragmentInfo { /// The text run that this represents. pub run: Arc<TextRun>, /// The intrinsic size of the text fragment. pub content_size: LogicalSize<Au>, /// The range within the above text run that this represents. pub range: Range<CharIndex>, /// The endpoint of the above range, including whitespace that was stripped out. This exists /// so that we can restore the range to its original value (before line breaking occurred) when /// performing incremental reflow. pub range_end_including_stripped_whitespace: CharIndex, /// Whether a line break is required after this fragment if wrapping on newlines (e.g. if /// `white-space: pre` is in effect). pub requires_line_break_afterward_if_wrapping_on_newlines: bool, } impl ScannedTextFragmentInfo { /// Creates the information specific to a scanned text fragment from a range and a text run. pub fn new(run: Arc<TextRun>, range: Range<CharIndex>, content_size: LogicalSize<Au>, requires_line_break_afterward_if_wrapping_on_newlines: bool) -> ScannedTextFragmentInfo { ScannedTextFragmentInfo { run: run, range: range, content_size: content_size, range_end_including_stripped_whitespace: range.end(), requires_line_break_afterward_if_wrapping_on_newlines: requires_line_break_afterward_if_wrapping_on_newlines, } } } /// Describes how to split a fragment. This is used during line breaking as part of the return /// value of `find_split_info_for_inline_size()`. #[derive(Debug, Clone)] pub struct SplitInfo { // TODO(bjz): this should only need to be a single character index, but both values are // currently needed for splitting in the `inline::try_append_*` functions. pub range: Range<CharIndex>, pub inline_size: Au, } impl SplitInfo { fn new(range: Range<CharIndex>, info: &ScannedTextFragmentInfo) -> SplitInfo { let inline_size = info.run.advance_for_range(&range); SplitInfo { range: range, inline_size: inline_size, } } } /// Describes how to split a fragment into two. This contains up to two `SplitInfo`s. pub struct SplitResult { /// The part of the fragment that goes on the first line. pub inline_start: Option<SplitInfo>, /// The part of the fragment that goes on the second line. pub inline_end: Option<SplitInfo>, /// The text run which is being split. pub text_run: Arc<TextRun>, } /// Describes how a fragment should be truncated. pub struct TruncationResult { /// The part of the fragment remaining after truncation. pub split: SplitInfo, /// The text run which is being truncated. pub text_run: Arc<TextRun>, } /// Data for an unscanned text fragment. Unscanned text fragments are the results of flow /// construction that have not yet had their inline-size determined. #[derive(Clone)] pub struct UnscannedTextFragmentInfo { /// The text inside the fragment. pub text: Box<str>, } impl UnscannedTextFragmentInfo { /// Creates a new instance of `UnscannedTextFragmentInfo` from the given text. #[inline] pub fn from_text(text: String) -> UnscannedTextFragmentInfo { UnscannedTextFragmentInfo { text: text.into_boxed_slice(), } } } /// A fragment that represents a table column. #[derive(Copy, Clone)] pub struct TableColumnFragmentInfo { /// the number of columns a <col> element should span pub span: u32, } impl TableColumnFragmentInfo { /// Create the information specific to an table column fragment. pub fn new(node: &ThreadSafeLayoutNode) -> TableColumnFragmentInfo { let element = node.as_element(); let span = element.get_attr(&ns!(""), &atom!("span")) .and_then(|string| string.parse().ok()) .unwrap_or(0); TableColumnFragmentInfo { span: span, } } } impl Fragment { /// Constructs a new `Fragment` instance. pub fn new(node: &ThreadSafeLayoutNode, specific: SpecificFragmentInfo) -> Fragment { let style = node.style().clone(); let writing_mode = style.writing_mode; Fragment { node: node.opaque(), style: style, restyle_damage: node.restyle_damage(), border_box: LogicalRect::zero(writing_mode), border_padding: LogicalMargin::zero(writing_mode), margin: LogicalMargin::zero(writing_mode), specific: specific, inline_context: None, pseudo: node.get_pseudo_element_type().strip(), debug_id: layout_debug::generate_unique_debug_id(), } } /// Constructs a new `Fragment` instance for an anonymous table object. pub fn new_anonymous_from_specific_info(node: &ThreadSafeLayoutNode, specific: SpecificFragmentInfo) -> Fragment { // CSS 2.1 § 17.2.1 This is for non-inherited properties on anonymous table fragments // example: // // <div style="display: table"> // Foo // </div> // // Anonymous table fragments, SpecificFragmentInfo::TableRow and // SpecificFragmentInfo::TableCell, are generated around `Foo`, but they shouldn't inherit // the border. let node_style = cascade_anonymous(&**node.style()); let writing_mode = node_style.writing_mode; Fragment {<|fim▁hole|> style: Arc::new(node_style), restyle_damage: node.restyle_damage(), border_box: LogicalRect::zero(writing_mode), border_padding: LogicalMargin::zero(writing_mode), margin: LogicalMargin::zero(writing_mode), specific: specific, inline_context: None, pseudo: node.get_pseudo_element_type().strip(), debug_id: layout_debug::generate_unique_debug_id(), } } /// Constructs a new `Fragment` instance from an opaque node. pub fn from_opaque_node_and_style(node: OpaqueNode, pseudo: PseudoElementType<()>, style: Arc<ComputedValues>, restyle_damage: RestyleDamage, specific: SpecificFragmentInfo) -> Fragment { let writing_mode = style.writing_mode; Fragment { node: node, style: style, restyle_damage: restyle_damage, border_box: LogicalRect::zero(writing_mode), border_padding: LogicalMargin::zero(writing_mode), margin: LogicalMargin::zero(writing_mode), specific: specific, inline_context: None, pseudo: pseudo, debug_id: layout_debug::generate_unique_debug_id(), } } pub fn reset_inline_sizes(&mut self) { self.border_padding = LogicalMargin::zero(self.style.writing_mode); self.margin = LogicalMargin::zero(self.style.writing_mode); } /// Returns a debug ID of this fragment. This ID should not be considered stable across /// multiple layouts or fragment manipulations. pub fn debug_id(&self) -> u16 { self.debug_id } /// Transforms this fragment into another fragment of the given type, with the given size, /// preserving all the other data. pub fn transform(&self, size: LogicalSize<Au>, info: SpecificFragmentInfo) -> Fragment { let new_border_box = LogicalRect::from_point_size(self.style.writing_mode, self.border_box.start, size); Fragment { node: self.node, style: self.style.clone(), restyle_damage: incremental::rebuild_and_reflow(), border_box: new_border_box, border_padding: self.border_padding, margin: self.margin, specific: info, inline_context: self.inline_context.clone(), pseudo: self.pseudo.clone(), debug_id: self.debug_id, } } /// Transforms this fragment using the given `SplitInfo`, preserving all the other data. pub fn transform_with_split_info(&self, split: &SplitInfo, text_run: Arc<TextRun>) -> Fragment { let size = LogicalSize::new(self.style.writing_mode, split.inline_size, self.border_box.size.block); let requires_line_break_afterward_if_wrapping_on_newlines = self.requires_line_break_afterward_if_wrapping_on_newlines(); let info = box ScannedTextFragmentInfo::new( text_run, split.range, size, requires_line_break_afterward_if_wrapping_on_newlines); self.transform(size, SpecificFragmentInfo::ScannedText(info)) } /// Transforms this fragment into an ellipsis fragment, preserving all the other data. pub fn transform_into_ellipsis(&self, layout_context: &LayoutContext) -> Fragment { let mut unscanned_ellipsis_fragments = LinkedList::new(); unscanned_ellipsis_fragments.push_back(self.transform( self.border_box.size, SpecificFragmentInfo::UnscannedText(UnscannedTextFragmentInfo::from_text( "…".to_owned())))); let ellipsis_fragments = TextRunScanner::new().scan_for_runs(&mut layout_context.font_context(), unscanned_ellipsis_fragments); debug_assert!(ellipsis_fragments.len() == 1); ellipsis_fragments.fragments.into_iter().next().unwrap() } pub fn restyle_damage(&self) -> RestyleDamage { self.restyle_damage | self.specific.restyle_damage() } pub fn contains_node(&self, node_address: OpaqueNode) -> bool { node_address == self.node || self.inline_context.as_ref().map_or(false, |ctx| { ctx.contains_node(node_address) }) } /// Adds a style to the inline context for this fragment. If the inline context doesn't exist /// yet, it will be created. pub fn add_inline_context_style(&mut self, mut node_info: InlineFragmentNodeInfo, first_frag: bool, last_frag: bool) { if self.inline_context.is_none() { self.inline_context = Some(InlineFragmentContext::new()); } if !first_frag || !last_frag { properties::modify_style_for_inline_sides(&mut node_info.style, first_frag, last_frag) }; self.inline_context.as_mut().unwrap().nodes.push(node_info); } /// Determines which quantities (border/padding/margin/specified) should be included in the /// intrinsic inline size of this fragment. fn quantities_included_in_intrinsic_inline_size(&self) -> QuantitiesIncludedInIntrinsicInlineSizes { match self.specific { SpecificFragmentInfo::Canvas(_) | SpecificFragmentInfo::Generic | SpecificFragmentInfo::GeneratedContent(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::InlineAbsolute(_) => { QuantitiesIncludedInIntrinsicInlineSizes::all() } SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell => { let base_quantities = INTRINSIC_INLINE_SIZE_INCLUDES_PADDING | INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED; if self.style.get_inheritedtable().border_collapse == border_collapse::T::separate { base_quantities | INTRINSIC_INLINE_SIZE_INCLUDES_BORDER } else { base_quantities } } SpecificFragmentInfo::TableWrapper => { let base_quantities = INTRINSIC_INLINE_SIZE_INCLUDES_MARGINS | INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED; if self.style.get_inheritedtable().border_collapse == border_collapse::T::separate { base_quantities | INTRINSIC_INLINE_SIZE_INCLUDES_BORDER } else { base_quantities } } SpecificFragmentInfo::TableRow => { let base_quantities = INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED; if self.style.get_inheritedtable().border_collapse == border_collapse::T::separate { base_quantities | INTRINSIC_INLINE_SIZE_INCLUDES_BORDER } else { base_quantities } } SpecificFragmentInfo::ScannedText(_) | SpecificFragmentInfo::TableColumn(_) | SpecificFragmentInfo::UnscannedText(_) | SpecificFragmentInfo::InlineAbsoluteHypothetical(_) | SpecificFragmentInfo::InlineBlock(_) => { QuantitiesIncludedInIntrinsicInlineSizes::empty() } } } /// Returns the portion of the intrinsic inline-size that consists of borders, padding, and/or /// margins. /// /// FIXME(#2261, pcwalton): This won't work well for inlines: is this OK? pub fn surrounding_intrinsic_inline_size(&self) -> Au { let flags = self.quantities_included_in_intrinsic_inline_size(); let style = self.style(); // FIXME(pcwalton): Percentages should be relative to any definite size per CSS-SIZING. // This will likely need to be done by pushing down definite sizes during selector // cascading. let margin = if flags.contains(INTRINSIC_INLINE_SIZE_INCLUDES_MARGINS) { let margin = style.logical_margin(); (MaybeAuto::from_style(margin.inline_start, Au(0)).specified_or_zero() + MaybeAuto::from_style(margin.inline_end, Au(0)).specified_or_zero()) } else { Au(0) }; // FIXME(pcwalton): Percentages should be relative to any definite size per CSS-SIZING. // This will likely need to be done by pushing down definite sizes during selector // cascading. let padding = if flags.contains(INTRINSIC_INLINE_SIZE_INCLUDES_PADDING) { let padding = style.logical_padding(); (model::specified(padding.inline_start, Au(0)) + model::specified(padding.inline_end, Au(0))) } else { Au(0) }; let border = if flags.contains(INTRINSIC_INLINE_SIZE_INCLUDES_BORDER) { self.border_width().inline_start_end() } else { Au(0) }; margin + padding + border } /// Uses the style only to estimate the intrinsic inline-sizes. These may be modified for text /// or replaced elements. fn style_specified_intrinsic_inline_size(&self) -> IntrinsicISizesContribution { let flags = self.quantities_included_in_intrinsic_inline_size(); let style = self.style(); let specified = if flags.contains(INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED) { max(model::specified(style.min_inline_size(), Au(0)), MaybeAuto::from_style(style.content_inline_size(), Au(0)).specified_or_zero()) } else { Au(0) }; // FIXME(#2261, pcwalton): This won't work well for inlines: is this OK? let surrounding_inline_size = self.surrounding_intrinsic_inline_size(); IntrinsicISizesContribution { content_intrinsic_sizes: IntrinsicISizes { minimum_inline_size: specified, preferred_inline_size: specified, }, surrounding_size: surrounding_inline_size, } } pub fn calculate_line_height(&self, layout_context: &LayoutContext) -> Au { let font_style = self.style.get_font_arc(); let font_metrics = text::font_metrics_for_style(&mut layout_context.font_context(), font_style); text::line_height_from_style(&*self.style, &font_metrics) } /// Returns the sum of the inline-sizes of all the borders of this fragment. Note that this /// can be expensive to compute, so if possible use the `border_padding` field instead. #[inline] fn border_width(&self) -> LogicalMargin<Au> { let style_border_width = match self.specific { SpecificFragmentInfo::ScannedText(_) => LogicalMargin::zero(self.style.writing_mode), _ => self.style().logical_border_width(), }; match self.inline_context { None => style_border_width, Some(ref inline_fragment_context) => { inline_fragment_context.nodes .iter() .fold(style_border_width, |acc, node| acc + node.style.logical_border_width()) } } } /// Computes the margins in the inline direction from the containing block inline-size and the /// style. After this call, the inline direction of the `margin` field will be correct. /// /// Do not use this method if the inline direction margins are to be computed some other way /// (for example, via constraint solving for blocks). pub fn compute_inline_direction_margins(&mut self, containing_block_inline_size: Au) { match self.specific { SpecificFragmentInfo::InlineBlock(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableColumn(_) => { self.margin.inline_start = Au(0); self.margin.inline_end = Au(0); return } _ => {} } let margin = self.style().logical_margin(); self.margin.inline_start = MaybeAuto::from_style(margin.inline_start, containing_block_inline_size).specified_or_zero(); self.margin.inline_end = MaybeAuto::from_style(margin.inline_end, containing_block_inline_size).specified_or_zero(); if let Some(ref inline_context) = self.inline_context { for node in inline_context.nodes.iter() { let margin = node.style.logical_margin(); self.margin.inline_start = self.margin.inline_start + MaybeAuto::from_style(margin.inline_start, containing_block_inline_size).specified_or_zero(); self.margin.inline_end = self.margin.inline_end + MaybeAuto::from_style(margin.inline_end, containing_block_inline_size).specified_or_zero(); } } } /// Computes the margins in the block direction from the containing block inline-size and the /// style. After this call, the block direction of the `margin` field will be correct. /// /// Do not use this method if the block direction margins are to be computed some other way /// (for example, via constraint solving for absolutely-positioned flows). pub fn compute_block_direction_margins(&mut self, containing_block_inline_size: Au) { match self.specific { SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableColumn(_) => { self.margin.block_start = Au(0); self.margin.block_end = Au(0) } _ => { // NB: Percentages are relative to containing block inline-size (not block-size) // per CSS 2.1. let margin = self.style().logical_margin(); self.margin.block_start = MaybeAuto::from_style(margin.block_start, containing_block_inline_size) .specified_or_zero(); self.margin.block_end = MaybeAuto::from_style(margin.block_end, containing_block_inline_size) .specified_or_zero(); } } } /// Computes the border and padding in both inline and block directions from the containing /// block inline-size and the style. After this call, the `border_padding` field will be /// correct. /// /// TODO(pcwalton): Remove `border_collapse`; we can figure it out from our style and specific /// fragment info. pub fn compute_border_and_padding(&mut self, containing_block_inline_size: Au, border_collapse: border_collapse::T) { // Compute border. let border = match border_collapse { border_collapse::T::separate => self.border_width(), border_collapse::T::collapse => LogicalMargin::zero(self.style.writing_mode), }; // Compute padding. let padding = match self.specific { SpecificFragmentInfo::TableColumn(_) | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper => LogicalMargin::zero(self.style.writing_mode), _ => { let style_padding = match self.specific { SpecificFragmentInfo::ScannedText(_) => { LogicalMargin::zero(self.style.writing_mode) } _ => model::padding_from_style(self.style(), containing_block_inline_size), }; match self.inline_context { None => style_padding, Some(ref inline_fragment_context) => { inline_fragment_context.nodes .iter() .fold(style_padding, |acc, node| { acc + model::padding_from_style(&*node.style, Au(0)) }) } } } }; self.border_padding = border + padding } // Return offset from original position because of `position: relative`. pub fn relative_position(&self, containing_block_size: &LogicalSize<Au>) -> LogicalSize<Au> { fn from_style(style: &ComputedValues, container_size: &LogicalSize<Au>) -> LogicalSize<Au> { let offsets = style.logical_position(); let offset_i = if offsets.inline_start != LengthOrPercentageOrAuto::Auto { MaybeAuto::from_style(offsets.inline_start, container_size.inline).specified_or_zero() } else { -MaybeAuto::from_style(offsets.inline_end, container_size.inline).specified_or_zero() }; let offset_b = if offsets.block_start != LengthOrPercentageOrAuto::Auto { MaybeAuto::from_style(offsets.block_start, container_size.inline).specified_or_zero() } else { -MaybeAuto::from_style(offsets.block_end, container_size.inline).specified_or_zero() }; LogicalSize::new(style.writing_mode, offset_i, offset_b) } // Go over the ancestor fragments and add all relative offsets (if any). let mut rel_pos = if self.style().get_box().position == position::T::relative { from_style(self.style(), containing_block_size) } else { LogicalSize::zero(self.style.writing_mode) }; if let Some(ref inline_fragment_context) = self.inline_context { for node in inline_fragment_context.nodes.iter() { if node.style.get_box().position == position::T::relative { rel_pos = rel_pos + from_style(&*node.style, containing_block_size); } } } rel_pos } /// Always inline for SCCP. /// /// FIXME(pcwalton): Just replace with the clear type from the style module for speed? #[inline(always)] pub fn clear(&self) -> Option<ClearType> { let style = self.style(); match style.get_box().clear { clear::T::none => None, clear::T::left => Some(ClearType::Left), clear::T::right => Some(ClearType::Right), clear::T::both => Some(ClearType::Both), } } #[inline(always)] pub fn style<'a>(&'a self) -> &'a ComputedValues { &*self.style } /// Returns the text alignment of the computed style of the nearest ancestor-or-self `Element` /// node. pub fn text_align(&self) -> text_align::T { self.style().get_inheritedtext().text_align } pub fn white_space(&self) -> white_space::T { self.style().get_inheritedtext().white_space } /// Returns the text decoration of this fragment, according to the style of the nearest ancestor /// element. /// /// NB: This may not be the actual text decoration, because of the override rules specified in /// CSS 2.1 § 16.3.1. Unfortunately, computing this properly doesn't really fit into Servo's /// model. Therefore, this is a best lower bound approximation, but the end result may actually /// have the various decoration flags turned on afterward. pub fn text_decoration(&self) -> text_decoration::T { self.style().get_text().text_decoration } /// Returns the inline-start offset from margin edge to content edge. /// /// FIXME(#2262, pcwalton): I think this method is pretty bogus, because it won't work for /// inlines. pub fn inline_start_offset(&self) -> Au { match self.specific { SpecificFragmentInfo::TableWrapper => self.margin.inline_start, SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableRow => self.border_padding.inline_start, SpecificFragmentInfo::TableColumn(_) => Au(0), _ => self.margin.inline_start + self.border_padding.inline_start, } } /// Returns true if this element can be split. This is true for text fragments, unless /// `white-space: pre` is set. pub fn can_split(&self) -> bool { self.is_scanned_text_fragment() && self.style.get_inheritedtext().white_space != white_space::T::pre } /// Returns true if and only if this fragment is a generated content fragment. pub fn is_generated_content(&self) -> bool { match self.specific { SpecificFragmentInfo::GeneratedContent(..) => true, _ => false, } } /// Returns true if and only if this is a scanned text fragment. pub fn is_scanned_text_fragment(&self) -> bool { match self.specific { SpecificFragmentInfo::ScannedText(..) => true, _ => false, } } /// Computes the intrinsic inline-sizes of this fragment. pub fn compute_intrinsic_inline_sizes(&mut self) -> IntrinsicISizesContribution { let mut result = self.style_specified_intrinsic_inline_size(); match self.specific { SpecificFragmentInfo::Generic | SpecificFragmentInfo::GeneratedContent(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableColumn(_) | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper | SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => {} SpecificFragmentInfo::InlineBlock(ref mut info) => { let block_flow = info.flow_ref.as_block(); result.union_block(&block_flow.base.intrinsic_inline_sizes) } SpecificFragmentInfo::InlineAbsolute(ref mut info) => { let block_flow = info.flow_ref.as_block(); result.union_block(&block_flow.base.intrinsic_inline_sizes) } SpecificFragmentInfo::Image(ref mut image_fragment_info) => { let image_inline_size = match image_fragment_info.replaced_image_fragment_info .dom_inline_size { None => image_fragment_info.image_inline_size(), Some(dom_inline_size) => dom_inline_size, }; result.union_block(&IntrinsicISizes { minimum_inline_size: image_inline_size, preferred_inline_size: image_inline_size, }); } SpecificFragmentInfo::Canvas(ref mut canvas_fragment_info) => { let canvas_inline_size = canvas_fragment_info.canvas_inline_size(); result.union_block(&IntrinsicISizes { minimum_inline_size: canvas_inline_size, preferred_inline_size: canvas_inline_size, }) } SpecificFragmentInfo::ScannedText(ref text_fragment_info) => { let range = &text_fragment_info.range; // See http://dev.w3.org/csswg/css-sizing/#max-content-inline-size. // TODO: Account for soft wrap opportunities. let max_line_inline_size = text_fragment_info.run .metrics_for_range(range) .advance_width; let min_line_inline_size = match self.style.get_inheritedtext().white_space { white_space::T::pre | white_space::T::nowrap => max_line_inline_size, white_space::T::normal => text_fragment_info.run.min_width_for_range(range), }; result.union_block(&IntrinsicISizes { minimum_inline_size: min_line_inline_size, preferred_inline_size: max_line_inline_size, }) } SpecificFragmentInfo::UnscannedText(..) => { panic!("Unscanned text fragments should have been scanned by now!") } }; // Take borders and padding for parent inline fragments into account, if necessary. if self.is_primary_fragment() { if let Some(ref context) = self.inline_context { for node in context.nodes.iter() { let border_width = node.style.logical_border_width().inline_start_end(); let padding_inline_size = model::padding_from_style(&*node.style, Au(0)).inline_start_end(); let margin_inline_size = model::specified_margin_from_style(&*node.style).inline_start_end(); result.surrounding_size = result.surrounding_size + border_width + padding_inline_size + margin_inline_size; } } } result } /// TODO: What exactly does this function return? Why is it Au(0) for /// `SpecificFragmentInfo::Generic`? pub fn content_inline_size(&self) -> Au { match self.specific { SpecificFragmentInfo::Generic | SpecificFragmentInfo::GeneratedContent(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper | SpecificFragmentInfo::InlineBlock(_) | SpecificFragmentInfo::InlineAbsoluteHypothetical(_) | SpecificFragmentInfo::InlineAbsolute(_) => Au(0), SpecificFragmentInfo::Canvas(ref canvas_fragment_info) => { canvas_fragment_info.replaced_image_fragment_info.computed_inline_size() } SpecificFragmentInfo::Image(ref image_fragment_info) => { image_fragment_info.replaced_image_fragment_info.computed_inline_size() } SpecificFragmentInfo::ScannedText(ref text_fragment_info) => { let (range, run) = (&text_fragment_info.range, &text_fragment_info.run); let text_bounds = run.metrics_for_range(range).bounding_box; text_bounds.size.width } SpecificFragmentInfo::TableColumn(_) => { panic!("Table column fragments do not have inline_size") } SpecificFragmentInfo::UnscannedText(_) => { panic!("Unscanned text fragments should have been scanned by now!") } } } /// Returns the dimensions of the content box. /// /// This is marked `#[inline]` because it is frequently called when only one or two of the /// values are needed and that will save computation. #[inline] pub fn content_box(&self) -> LogicalRect<Au> { self.border_box - self.border_padding } /// Attempts to find the split positions of a text fragment so that its inline-size is no more /// than `max_inline_size`. /// /// A return value of `None` indicates that the fragment could not be split. Otherwise the /// information pertaining to the split is returned. The inline-start and inline-end split /// information are both optional due to the possibility of them being whitespace. pub fn calculate_split_position(&self, max_inline_size: Au, starts_line: bool) -> Option<SplitResult> { let text_fragment_info = if let SpecificFragmentInfo::ScannedText(ref text_fragment_info) = self.specific { text_fragment_info } else { return None }; let mut flags = SplitOptions::empty(); if starts_line { flags.insert(STARTS_LINE); if self.style().get_inheritedtext().overflow_wrap == overflow_wrap::T::break_word { flags.insert(RETRY_AT_CHARACTER_BOUNDARIES) } } match self.style().get_inheritedtext().word_break { word_break::T::normal => { // Break at normal word boundaries. let natural_word_breaking_strategy = text_fragment_info.run.natural_word_slices_in_range(&text_fragment_info.range); self.calculate_split_position_using_breaking_strategy( natural_word_breaking_strategy, max_inline_size, flags) } word_break::T::break_all => { // Break at character boundaries. let character_breaking_strategy = text_fragment_info.run.character_slices_in_range(&text_fragment_info.range); flags.remove(RETRY_AT_CHARACTER_BOUNDARIES); return self.calculate_split_position_using_breaking_strategy( character_breaking_strategy, max_inline_size, flags) } } } /// Truncates this fragment to the given `max_inline_size`, using a character-based breaking /// strategy. If no characters could fit, returns `None`. pub fn truncate_to_inline_size(&self, max_inline_size: Au) -> Option<TruncationResult> { let text_fragment_info = if let SpecificFragmentInfo::ScannedText(ref text_fragment_info) = self.specific { text_fragment_info } else { return None }; let character_breaking_strategy = text_fragment_info.run.character_slices_in_range(&text_fragment_info.range); match self.calculate_split_position_using_breaking_strategy(character_breaking_strategy, max_inline_size, SplitOptions::empty()) { None => None, Some(split_info) => { match split_info.inline_start { None => None, Some(split) => { Some(TruncationResult { split: split, text_run: split_info.text_run.clone(), }) } } } } } /// A helper method that uses the breaking strategy described by `slice_iterator` (at present, /// either natural word breaking or character breaking) to split this fragment. fn calculate_split_position_using_breaking_strategy<'a,I>( &self, slice_iterator: I, max_inline_size: Au, flags: SplitOptions) -> Option<SplitResult> where I: Iterator<Item=TextRunSlice<'a>> { let text_fragment_info = if let SpecificFragmentInfo::ScannedText(ref text_fragment_info) = self.specific { text_fragment_info } else { return None }; let mut pieces_processed_count: u32 = 0; let mut remaining_inline_size = max_inline_size; let mut inline_start_range = Range::new(text_fragment_info.range.begin(), CharIndex(0)); let mut inline_end_range = None; let mut overflowing = false; debug!("calculate_split_position_using_breaking_strategy: splitting text fragment \ (strlen={}, range={:?}, max_inline_size={:?})", text_fragment_info.run.text.len(), text_fragment_info.range, max_inline_size); for slice in slice_iterator { debug!("calculate_split_position_using_breaking_strategy: considering slice \ (offset={:?}, slice range={:?}, remaining_inline_size={:?})", slice.offset, slice.range, remaining_inline_size); // Use the `remaining_inline_size` to find a split point if possible. If not, go around // the loop again with the next slice. let metrics = text_fragment_info.run.metrics_for_slice(slice.glyphs, &slice.range); let advance = metrics.advance_width; // Have we found the split point? if advance <= remaining_inline_size || slice.glyphs.is_whitespace() { // Keep going; we haven't found the split point yet. if flags.contains(STARTS_LINE) && pieces_processed_count == 0 && slice.glyphs.is_whitespace() { debug!("calculate_split_position_using_breaking_strategy: skipping \ leading trimmable whitespace"); inline_start_range.shift_by(slice.range.length()); } else { debug!("calculate_split_position_using_breaking_strategy: enlarging span"); remaining_inline_size = remaining_inline_size - advance; inline_start_range.extend_by(slice.range.length()); } pieces_processed_count += 1; continue } // The advance is more than the remaining inline-size, so split here. First, check to // see if we're going to overflow the line. If so, perform a best-effort split. let mut remaining_range = slice.text_run_range(); let split_is_empty = inline_start_range.is_empty() && !self.requires_line_break_afterward_if_wrapping_on_newlines(); if split_is_empty { // We're going to overflow the line. overflowing = true; inline_start_range = slice.text_run_range(); remaining_range = Range::new(slice.text_run_range().end(), CharIndex(0)); remaining_range.extend_to(text_fragment_info.range.end()); } // Check to see if we need to create an inline-end chunk. let slice_begin = remaining_range.begin(); if slice_begin < text_fragment_info.range.end() { // There still some things left over at the end of the line, so create the // inline-end chunk. let mut inline_end = remaining_range; inline_end.extend_to(text_fragment_info.range.end()); inline_end_range = Some(inline_end); debug!("calculate_split_position: splitting remainder with inline-end range={:?}", inline_end); } // If we failed to find a suitable split point, we're on the verge of overflowing the // line. if split_is_empty || overflowing { // If we've been instructed to retry at character boundaries (probably via // `overflow-wrap: break-word`), do so. if flags.contains(RETRY_AT_CHARACTER_BOUNDARIES) { let character_breaking_strategy = text_fragment_info.run .character_slices_in_range(&text_fragment_info.range); let mut flags = flags; flags.remove(RETRY_AT_CHARACTER_BOUNDARIES); return self.calculate_split_position_using_breaking_strategy( character_breaking_strategy, max_inline_size, flags) } // We aren't at the start of the line, so don't overflow. Let inline layout wrap to // the next line instead. if !flags.contains(STARTS_LINE) { return None } } break } let split_is_empty = inline_start_range.is_empty() && !self.requires_line_break_afterward_if_wrapping_on_newlines(); let inline_start = if !split_is_empty { Some(SplitInfo::new(inline_start_range, &**text_fragment_info)) } else { None }; let inline_end = inline_end_range.map(|inline_end_range| { SplitInfo::new(inline_end_range, &**text_fragment_info) }); Some(SplitResult { inline_start: inline_start, inline_end: inline_end, text_run: text_fragment_info.run.clone(), }) } /// The opposite of `calculate_split_position_using_breaking_strategy`: merges this fragment /// with the next one. pub fn merge_with(&mut self, next_fragment: Fragment) { match (&mut self.specific, &next_fragment.specific) { (&mut SpecificFragmentInfo::ScannedText(ref mut this_info), &SpecificFragmentInfo::ScannedText(ref other_info)) => { debug_assert!(util::arc_ptr_eq(&this_info.run, &other_info.run)); this_info.range.extend_to(other_info.range_end_including_stripped_whitespace); this_info.content_size.inline = this_info.run.metrics_for_range(&this_info.range).advance_width; this_info.requires_line_break_afterward_if_wrapping_on_newlines = this_info.requires_line_break_afterward_if_wrapping_on_newlines || other_info.requires_line_break_afterward_if_wrapping_on_newlines; self.border_box.size.inline = this_info.content_size.inline + self.border_padding.inline_start_end(); } _ => panic!("Can only merge two scanned-text fragments!"), } } /// Returns true if this fragment is an unscanned text fragment that consists entirely of /// whitespace that should be stripped. pub fn is_ignorable_whitespace(&self) -> bool { match self.white_space() { white_space::T::pre => return false, white_space::T::normal | white_space::T::nowrap => {} } match self.specific { SpecificFragmentInfo::UnscannedText(ref text_fragment_info) => { is_whitespace(&text_fragment_info.text) } _ => false, } } /// Assigns replaced inline-size, padding, and margins for this fragment only if it is replaced /// content per CSS 2.1 § 10.3.2. pub fn assign_replaced_inline_size_if_necessary<'a>(&'a mut self, container_inline_size: Au) { match self.specific { SpecificFragmentInfo::Generic | SpecificFragmentInfo::GeneratedContent(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper => return, SpecificFragmentInfo::TableColumn(_) => { panic!("Table column fragments do not have inline size") } SpecificFragmentInfo::UnscannedText(_) => { panic!("Unscanned text fragments should have been scanned by now!") } SpecificFragmentInfo::Canvas(_) | SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::InlineBlock(_) | SpecificFragmentInfo::InlineAbsoluteHypothetical(_) | SpecificFragmentInfo::InlineAbsolute(_) | SpecificFragmentInfo::ScannedText(_) => {} }; let style = &*self.style; let noncontent_inline_size = self.border_padding.inline_start_end(); match self.specific { SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut info) => { let block_flow = info.flow_ref.as_block(); block_flow.base.position.size.inline = block_flow.base.intrinsic_inline_sizes.preferred_inline_size; // This is a hypothetical box, so it takes up no space. self.border_box.size.inline = Au(0); } SpecificFragmentInfo::InlineBlock(ref mut info) => { let block_flow = info.flow_ref.as_block(); self.border_box.size.inline = max(block_flow.base.intrinsic_inline_sizes.minimum_inline_size, block_flow.base.intrinsic_inline_sizes.preferred_inline_size); block_flow.base.block_container_inline_size = self.border_box.size.inline; block_flow.base.block_container_writing_mode = self.style.writing_mode; } SpecificFragmentInfo::InlineAbsolute(ref mut info) => { let block_flow = info.flow_ref.as_block(); self.border_box.size.inline = max(block_flow.base.intrinsic_inline_sizes.minimum_inline_size, block_flow.base.intrinsic_inline_sizes.preferred_inline_size); block_flow.base.block_container_inline_size = self.border_box.size.inline; block_flow.base.block_container_writing_mode = self.style.writing_mode; } SpecificFragmentInfo::ScannedText(ref info) => { // Scanned text fragments will have already had their content inline-sizes assigned // by this point. self.border_box.size.inline = info.content_size.inline + noncontent_inline_size } SpecificFragmentInfo::Image(ref mut image_fragment_info) => { let fragment_inline_size = image_fragment_info.image_inline_size(); let fragment_block_size = image_fragment_info.image_block_size(); self.border_box.size.inline = image_fragment_info.replaced_image_fragment_info .calculate_replaced_inline_size(style, noncontent_inline_size, container_inline_size, fragment_inline_size, fragment_block_size); } SpecificFragmentInfo::Canvas(ref mut canvas_fragment_info) => { let fragment_inline_size = canvas_fragment_info.canvas_inline_size(); let fragment_block_size = canvas_fragment_info.canvas_block_size(); self.border_box.size.inline = canvas_fragment_info.replaced_image_fragment_info .calculate_replaced_inline_size(style, noncontent_inline_size, container_inline_size, fragment_inline_size, fragment_block_size); } SpecificFragmentInfo::Iframe(ref iframe_fragment_info) => { self.border_box.size.inline = iframe_fragment_info.calculate_replaced_inline_size(style, container_inline_size) + noncontent_inline_size; } _ => panic!("this case should have been handled above"), } } /// Assign block-size for this fragment if it is replaced content. The inline-size must have /// been assigned first. /// /// Ideally, this should follow CSS 2.1 § 10.6.2. pub fn assign_replaced_block_size_if_necessary(&mut self, containing_block_block_size: Option<Au>) { match self.specific { SpecificFragmentInfo::Generic | SpecificFragmentInfo::GeneratedContent(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::TableWrapper => return, SpecificFragmentInfo::TableColumn(_) => { panic!("Table column fragments do not have block size") } SpecificFragmentInfo::UnscannedText(_) => { panic!("Unscanned text fragments should have been scanned by now!") } SpecificFragmentInfo::Canvas(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::InlineBlock(_) | SpecificFragmentInfo::InlineAbsoluteHypothetical(_) | SpecificFragmentInfo::InlineAbsolute(_) | SpecificFragmentInfo::ScannedText(_) => {} } let style = &*self.style; let noncontent_block_size = self.border_padding.block_start_end(); match self.specific { SpecificFragmentInfo::Image(ref mut image_fragment_info) => { let fragment_inline_size = image_fragment_info.image_inline_size(); let fragment_block_size = image_fragment_info.image_block_size(); self.border_box.size.block = image_fragment_info.replaced_image_fragment_info .calculate_replaced_block_size(style, noncontent_block_size, containing_block_block_size, fragment_inline_size, fragment_block_size); } SpecificFragmentInfo::Canvas(ref mut canvas_fragment_info) => { let fragment_inline_size = canvas_fragment_info.canvas_inline_size(); let fragment_block_size = canvas_fragment_info.canvas_block_size(); self.border_box.size.block = canvas_fragment_info.replaced_image_fragment_info .calculate_replaced_block_size(style, noncontent_block_size, containing_block_block_size, fragment_inline_size, fragment_block_size); } SpecificFragmentInfo::ScannedText(ref info) => { // Scanned text fragments' content block-sizes are calculated by the text run // scanner during flow construction. self.border_box.size.block = info.content_size.block + noncontent_block_size } SpecificFragmentInfo::InlineBlock(ref mut info) => { // Not the primary fragment, so we do not take the noncontent size into account. let block_flow = info.flow_ref.as_block(); self.border_box.size.block = block_flow.base.position.size.block + block_flow.fragment.margin.block_start_end() } SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut info) => { // Not the primary fragment, so we do not take the noncontent size into account. let block_flow = info.flow_ref.as_block(); self.border_box.size.block = block_flow.base.position.size.block; } SpecificFragmentInfo::InlineAbsolute(ref mut info) => { // Not the primary fragment, so we do not take the noncontent size into account. let block_flow = info.flow_ref.as_block(); self.border_box.size.block = block_flow.base.position.size.block + block_flow.fragment.margin.block_start_end() } SpecificFragmentInfo::Iframe(ref info) => { self.border_box.size.block = info.calculate_replaced_block_size(style, containing_block_block_size) + noncontent_block_size; } _ => panic!("should have been handled above"), } } /// Calculates block-size above baseline, depth below baseline, and ascent for this fragment /// when used in an inline formatting context. See CSS 2.1 § 10.8.1. pub fn inline_metrics(&self, layout_context: &LayoutContext) -> InlineMetrics { match self.specific { SpecificFragmentInfo::Image(ref image_fragment_info) => { let computed_block_size = image_fragment_info.replaced_image_fragment_info .computed_block_size(); InlineMetrics { block_size_above_baseline: computed_block_size + self.border_padding.block_start, depth_below_baseline: self.border_padding.block_end, ascent: computed_block_size + self.border_padding.block_start, } } SpecificFragmentInfo::ScannedText(ref text_fragment) => { // See CSS 2.1 § 10.8.1. let line_height = self.calculate_line_height(layout_context); let font_derived_metrics = InlineMetrics::from_font_metrics(&text_fragment.run.font_metrics, line_height); InlineMetrics { block_size_above_baseline: font_derived_metrics.block_size_above_baseline + self.border_padding.block_start, depth_below_baseline: font_derived_metrics.depth_below_baseline + self.border_padding.block_end, ascent: font_derived_metrics.ascent + self.border_padding.block_start, } } SpecificFragmentInfo::InlineBlock(ref info) => { // See CSS 2.1 § 10.8.1. let block_flow = info.flow_ref.as_immutable_block(); let font_style = self.style.get_font_arc(); let font_metrics = text::font_metrics_for_style(&mut layout_context.font_context(), font_style); InlineMetrics::from_block_height(&font_metrics, block_flow.base.position.size.block, block_flow.fragment.margin.block_start, block_flow.fragment.margin.block_end) } SpecificFragmentInfo::InlineAbsoluteHypothetical(_) | SpecificFragmentInfo::InlineAbsolute(_) => { // Hypothetical boxes take up no space. InlineMetrics { block_size_above_baseline: Au(0), depth_below_baseline: Au(0), ascent: Au(0), } } _ => { InlineMetrics { block_size_above_baseline: self.border_box.size.block, depth_below_baseline: Au(0), ascent: self.border_box.size.block, } } } } /// Returns true if this fragment is a hypothetical box. See CSS 2.1 § 10.3.7. pub fn is_hypothetical(&self) -> bool { match self.specific { SpecificFragmentInfo::InlineAbsoluteHypothetical(_) => true, _ => false, } } /// Returns true if this fragment can merge with another adjacent fragment or false otherwise. pub fn can_merge_with_fragment(&self, other: &Fragment) -> bool { match (&self.specific, &other.specific) { (&SpecificFragmentInfo::UnscannedText(ref first_unscanned_text), &SpecificFragmentInfo::UnscannedText(_)) => { // FIXME: Should probably use a whitelist of styles that can safely differ (#3165) let length = first_unscanned_text.text.len(); self.style().get_font() == other.style().get_font() && self.text_decoration() == other.text_decoration() && self.white_space() == other.white_space() && (length == 0 || first_unscanned_text.text.char_at_reverse(length) != '\n') } _ => false, } } /// Returns true if and only if this is the *primary fragment* for the fragment's style object /// (conceptually, though style sharing makes this not really true, of course). The primary /// fragment is the one that draws backgrounds, borders, etc., and takes borders, padding and /// margins into account. Every style object has at most one primary fragment. /// /// At present, all fragments are primary fragments except for inline-block and table wrapper /// fragments. Inline-block fragments are not primary fragments because the corresponding block /// flow is the primary fragment, while table wrapper fragments are not primary fragments /// because the corresponding table flow is the primary fragment. pub fn is_primary_fragment(&self) -> bool { match self.specific { SpecificFragmentInfo::InlineBlock(_) | SpecificFragmentInfo::InlineAbsoluteHypothetical(_) | SpecificFragmentInfo::InlineAbsolute(_) | SpecificFragmentInfo::TableWrapper => false, SpecificFragmentInfo::Canvas(_) | SpecificFragmentInfo::Generic | SpecificFragmentInfo::GeneratedContent(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::ScannedText(_) | SpecificFragmentInfo::Table | SpecificFragmentInfo::TableCell | SpecificFragmentInfo::TableColumn(_) | SpecificFragmentInfo::TableRow | SpecificFragmentInfo::UnscannedText(_) => true, } } /// Determines the inline sizes of inline-block fragments. These cannot be fully computed until /// inline size assignment has run for the child flow: thus it is computed "late", during /// block size assignment. pub fn update_late_computed_replaced_inline_size_if_necessary(&mut self) { if let SpecificFragmentInfo::InlineBlock(ref mut inline_block_info) = self.specific { let block_flow = inline_block_info.flow_ref.as_block(); let margin = block_flow.fragment.style.logical_margin(); self.border_box.size.inline = block_flow.fragment.border_box.size.inline + MaybeAuto::from_style(margin.inline_start, Au(0)).specified_or_zero() + MaybeAuto::from_style(margin.inline_end, Au(0)).specified_or_zero() } } pub fn update_late_computed_inline_position_if_necessary(&mut self) { match self.specific { SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut info) => { let position = self.border_box.start.i; info.flow_ref.update_late_computed_inline_position_if_necessary(position) } _ => {} } } pub fn update_late_computed_block_position_if_necessary(&mut self) { match self.specific { SpecificFragmentInfo::InlineAbsoluteHypothetical(ref mut info) => { let position = self.border_box.start.b; info.flow_ref.update_late_computed_block_position_if_necessary(position) } _ => {} } } pub fn repair_style(&mut self, new_style: &Arc<ComputedValues>) { self.style = (*new_style).clone() } /// Given the stacking-context-relative position of the containing flow, returns the border box /// of this fragment relative to the parent stacking context. This takes `position: relative` /// into account. /// /// If `coordinate_system` is `Parent`, this returns the border box in the parent stacking /// context's coordinate system. Otherwise, if `coordinate_system` is `Own` and this fragment /// establishes a stacking context itself, this returns a border box anchored at (0, 0). (If /// this fragment does not establish a stacking context, then it always belongs to its parent /// stacking context and thus `coordinate_system` is ignored.) /// /// This is the method you should use for display list construction as well as /// `getBoundingClientRect()` and so forth. pub fn stacking_relative_border_box(&self, stacking_relative_flow_origin: &Point2D<Au>, relative_containing_block_size: &LogicalSize<Au>, relative_containing_block_mode: WritingMode, coordinate_system: CoordinateSystem) -> Rect<Au> { let container_size = relative_containing_block_size.to_physical(relative_containing_block_mode); let border_box = self.border_box.to_physical(self.style.writing_mode, container_size); if coordinate_system == CoordinateSystem::Own && self.establishes_stacking_context() { return Rect::new(ZERO_POINT, border_box.size) } // FIXME(pcwalton): This can double-count relative position sometimes for inlines (e.g. // `<div style="position:relative">x</div>`, because the `position:relative` trickles down // to the inline flow. Possibly we should extend the notion of "primary fragment" to fix // this. let relative_position = self.relative_position(relative_containing_block_size); border_box.translate_by_size(&relative_position.to_physical(self.style.writing_mode)) .translate(stacking_relative_flow_origin) } /// Given the stacking-context-relative border box, returns the stacking-context-relative /// content box. pub fn stacking_relative_content_box(&self, stacking_relative_border_box: &Rect<Au>) -> Rect<Au> { let border_padding = self.border_padding.to_physical(self.style.writing_mode); Rect::new(Point2D::new(stacking_relative_border_box.origin.x + border_padding.left, stacking_relative_border_box.origin.y + border_padding.top), Size2D::new(stacking_relative_border_box.size.width - border_padding.horizontal(), stacking_relative_border_box.size.height - border_padding.vertical())) } /// Returns true if this fragment establishes a new stacking context and false otherwise. pub fn establishes_stacking_context(&self) -> bool { if self.style().get_effects().opacity != 1.0 { return true } if !self.style().get_effects().filter.is_empty() { return true } if self.style().get_effects().mix_blend_mode != mix_blend_mode::T::normal { return true } if self.style().get_effects().transform.0.is_some() { return true } match self.style().get_used_transform_style() { transform_style::T::flat | transform_style::T::preserve_3d => { return true } transform_style::T::auto => {} } // Canvas always layerizes, as an special case // FIXME(pcwalton): Don't unconditionally form stacking contexts for each canvas. if let SpecificFragmentInfo::Canvas(_) = self.specific { return true } match self.style().get_box().position { position::T::absolute | position::T::fixed => { // FIXME(pcwalton): This should only establish a new stacking context when // `z-index` is not `auto`. But this matches what we did before. true } position::T::relative | position::T::static_ => { // FIXME(pcwalton): `position: relative` establishes a new stacking context if // `z-index` is not `auto`. But this matches what we did before. false } } } /// Computes the overflow rect of this fragment relative to the start of the flow. pub fn compute_overflow(&self) -> Rect<Au> { // FIXME(pcwalton, #2795): Get the real container size. let container_size = Size2D::zero(); let mut border_box = self.border_box.to_physical(self.style.writing_mode, container_size); // Relative position can cause us to draw outside our border box. // // FIXME(pcwalton): I'm not a fan of the way this makes us crawl though so many styles all // the time. Can't we handle relative positioning by just adjusting `border_box`? let relative_position = self.relative_position(&LogicalSize::zero(self.style.writing_mode)); border_box = border_box.translate_by_size(&relative_position.to_physical(self.style.writing_mode)); let mut overflow = border_box; // Box shadows cause us to draw outside our border box. for box_shadow in self.style().get_effects().box_shadow.0.iter() { let offset = Point2D::new(box_shadow.offset_x, box_shadow.offset_y); let inflation = box_shadow.spread_radius + box_shadow.blur_radius * BLUR_INFLATION_FACTOR; overflow = overflow.union(&border_box.translate(&offset).inflate(inflation, inflation)) } // Outlines cause us to draw outside our border box. let outline_width = self.style.get_outline().outline_width; if outline_width != Au(0) { overflow = overflow.union(&border_box.inflate(outline_width, outline_width)) } // FIXME(pcwalton): Sometimes excessively fancy glyphs can make us draw outside our border // box too. overflow } /// Remove any compositor layers associated with this fragment - it is being /// removed from the tree or had its display property set to none. /// TODO(gw): This just hides the compositor layer for now. In the future /// it probably makes sense to provide a hint to the compositor whether /// the layers should be destroyed to free memory. pub fn remove_compositor_layers(&self, constellation_chan: ConstellationChan) { match self.specific { SpecificFragmentInfo::Iframe(ref iframe_info) => { let ConstellationChan(ref chan) = constellation_chan; chan.send(Msg::FrameRect(iframe_info.pipeline_id, iframe_info.subpage_id, Rect::zero())).unwrap(); } _ => {} } } pub fn requires_line_break_afterward_if_wrapping_on_newlines(&self) -> bool { match self.specific { SpecificFragmentInfo::ScannedText(ref scanned_text) => { scanned_text.requires_line_break_afterward_if_wrapping_on_newlines } _ => false, } } pub fn strip_leading_whitespace_if_necessary(&mut self) { let mut scanned_text_fragment_info = match self.specific { SpecificFragmentInfo::ScannedText(ref mut scanned_text_fragment_info) => { scanned_text_fragment_info } _ => return, }; if self.style.get_inheritedtext().white_space == white_space::T::pre { return } let mut leading_whitespace_character_count = 0; { let text = slice_chars( &*scanned_text_fragment_info.run.text, scanned_text_fragment_info.range.begin().to_usize(), scanned_text_fragment_info.range.end().to_usize()); for character in text.chars() { if util::str::char_is_whitespace(character) { leading_whitespace_character_count += 1 } else { break } } } scanned_text_fragment_info.range.adjust_by(CharIndex(leading_whitespace_character_count), -CharIndex(leading_whitespace_character_count)); } pub fn inline_styles<'a>(&'a self) -> InlineStyleIterator<'a> { InlineStyleIterator::new(self) } /// Returns the inline-size of this fragment's margin box. pub fn margin_box_inline_size(&self) -> Au { self.border_box.size.inline + self.margin.inline_start_end() } } impl fmt::Debug for Fragment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "({} {} ", self.debug_id(), self.specific.get_type())); try!(write!(f, "bb {:?} bp {:?} m {:?}{:?}", self.border_box, self.border_padding, self.margin, self.specific)); write!(f, ")") } } bitflags! { flags QuantitiesIncludedInIntrinsicInlineSizes: u8 { const INTRINSIC_INLINE_SIZE_INCLUDES_MARGINS = 0x01, const INTRINSIC_INLINE_SIZE_INCLUDES_PADDING = 0x02, const INTRINSIC_INLINE_SIZE_INCLUDES_BORDER = 0x04, const INTRINSIC_INLINE_SIZE_INCLUDES_SPECIFIED = 0x08, } } bitflags! { // Various flags we can use when splitting fragments. See // `calculate_split_position_using_breaking_strategy()`. flags SplitOptions: u8 { #[doc="True if this is the first fragment on the line."] const STARTS_LINE = 0x01, #[doc="True if we should attempt to split at character boundaries if this split fails. \ This is used to implement `overflow-wrap: break-word`."] const RETRY_AT_CHARACTER_BOUNDARIES = 0x02, } } /// A top-down fragment border box iteration handler. pub trait FragmentBorderBoxIterator { /// The operation to perform. fn process(&mut self, fragment: &Fragment, level: i32, overflow: &Rect<Au>); /// Returns true if this fragment must be processed in-order. If this returns false, /// we skip the operation for this fragment, but continue processing siblings. fn should_process(&mut self, fragment: &Fragment) -> bool; } /// The coordinate system used in `stacking_relative_border_box()`. See the documentation of that /// method for details. #[derive(Clone, PartialEq, Debug)] pub enum CoordinateSystem { /// The border box returned is relative to the fragment's parent stacking context. Parent, /// The border box returned is relative to the fragment's own stacking context, if applicable. Own, } pub struct InlineStyleIterator<'a> { fragment: &'a Fragment, inline_style_index: usize, primary_style_yielded: bool, } impl<'a> Iterator for InlineStyleIterator<'a> { type Item = &'a ComputedValues; fn next(&mut self) -> Option<&'a ComputedValues> { if !self.primary_style_yielded { self.primary_style_yielded = true; return Some(&*self.fragment.style) } let inline_context = match self.fragment.inline_context { None => return None, Some(ref inline_context) => inline_context, }; let inline_style_index = self.inline_style_index; if inline_style_index == inline_context.nodes.len() { return None } self.inline_style_index += 1; Some(&*inline_context.nodes[inline_style_index].style) } } impl<'a> InlineStyleIterator<'a> { fn new<'b>(fragment: &'b Fragment) -> InlineStyleIterator<'b> { InlineStyleIterator { fragment: fragment, inline_style_index: 0, primary_style_yielded: false, } } }<|fim▁end|>
node: node.opaque(),
<|file_name|>medium_maximum_xor_of_two_numbers_in_an_array.cpp<|end_file_name|><|fim▁begin|>#include <vector> #include <iostream> #include <unordered_set> #include <unordered_map> #include <map> #include <sstream> #include <algorithm> #include <queue> #include <set> #include <functional> #include <stdio.h> #include <stdlib.h> using namespace std; #if 0 This algorithm's idea is: to iteratively determine what would be each bit of the final result from left to right. And it narrows down the candidate group iteration by iteration. e.g.assume input are a, b, c, d, ...z, 26 integers in total. In first iteration, if you found that a, d, e, h, u differs on the MSB(most significant bit), so you are sure your final result's MSB is set. Now in second iteration, you try to see if among a, d, e, h, u there are at least two numbers make the 2nd MSB differs, if yes, then definitely, the 2nd MSB will be set in the final result. And maybe at this point the candidate group shinks from a,d,e,h,u to a, e, h. Implicitly, every iteration, you are narrowing down the candidate group, but you don't need to track how the group is shrinking, you only cares about the final result. #endif class Solution { public: int findMaximumXOR(vector<int>& nums) { int max = 0, mask = 0; unordered_set<int> t; #if 0 search from left to right, find out for each bit is there two numbers that has different value #endif for (int i = 31; i >= 0; i--){ /* mask contains the bits considered so far */ mask |= (1 << i); t.clear(); /* store prefix of all number with right i bits discarded */ for (int n : nums){ t.insert(mask & n); } #if 0 now find out if there are two prefix with different i-th bit if there is, the new max should be current max with one 1 bit at i-th position, which is candidate and the two prefix, say A and B, satisfies: A ^ B = candidate so we also have A ^ candidate = B or B ^ candidate = A thus we can use this method to find out if such A and B exists in the set #endif int candidate = max | (1 << i);<|fim▁hole|> for (int prefix : t){ if (t.find(prefix ^ candidate) != t.end()){ max = candidate; break; } } } return max; } }; int main() { { vector<int> nums = { 3, 10, 5, 25, 2, 8 }; cout << Solution().findMaximumXOR(nums) << endl; // 28 } cin.get(); return EXIT_SUCCESS; }<|fim▁end|>
<|file_name|>patternmatch.py<|end_file_name|><|fim▁begin|>import sys import os import time import numpy import cv2 import cv2.cv as cv from PIL import Image sys.path.insert(0, os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(__file__))))) from picture.util import define from picture.util.system import POINT from picture.util.log import LOG as L THRESHOLD = 0.96 class PatternMatch(object): def __init__(self): pass @classmethod def __patternmatch(self, reference, target): L.info("reference : %s" % reference) img_rgb = cv2.imread(reference) img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) template = cv2.imread(target, 0) w, h = template.shape[::-1] res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) loc = numpy.where( res >= THRESHOLD) result = None for pt in zip(*loc[::-1]): result = POINT(pt[0], pt[1], w, h) return result @classmethod def bool(self, reference, target): result = PatternMatch.__patternmatch(reference, target) if result is None: return False else: return True @classmethod def coordinate(self, reference, target): return PatternMatch.__patternmatch(reference, target) if __name__ == "__main__": pmc = PatternMatch() print pmc.bool(os.path.join(define.APP_TMP,"screen.png"),<|fim▁hole|><|fim▁end|>
os.path.join(define.APP_TMP,"login.png"))
<|file_name|>into_searcher.rs<|end_file_name|><|fim▁begin|>#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::str::pattern::Searcher; use core::str::pattern::SearchStep::{Match, Reject, Done}; use core::str::pattern::StrSearcher; use core::str::pattern::Pattern; // #[derive(Copy, Clone, Eq, PartialEq, Debug)] // pub enum SearchStep { // /// Expresses that a match of the pattern has been found at // /// `haystack[a..b]`. // Match(usize, usize), // /// Expresses that `haystack[a..b]` has been rejected as a possible match // /// of the pattern. // /// // /// Note that there might be more than one `Reject` between two `Match`es, // /// there is no requirement for them to be combined into one. // Reject(usize, usize), // /// Expresses that every byte of the haystack has been visted, ending // /// the iteration. // Done // } // #[derive(Clone)] // pub struct StrSearcher<'a, 'b> { // haystack: &'a str, // needle: &'b str, // start: usize, // end: usize, // state: State, // } // #[derive(Clone, PartialEq)] // enum State { Done, NotDone, Reject(usize, usize) } // impl State { // #[inline] fn done(&self) -> bool { *self == State::Done } // #[inline] fn take(&mut self) -> State { ::mem::replace(self, State::NotDone) } // } // pub trait Pattern<'a>: Sized { // /// Associated searcher for this pattern // type Searcher: Searcher<'a>; // // /// Constructs the associated searcher from // /// `self` and the `haystack` to search in. // fn into_searcher(self, haystack: &'a str) -> Self::Searcher; // // /// Checks whether the pattern matches anywhere in the haystack // #[inline] // fn is_contained_in(self, haystack: &'a str) -> bool { // self.into_searcher(haystack).next_match().is_some() // } // // /// Checks whether the pattern matches at the front of the haystack // #[inline] // fn is_prefix_of(self, haystack: &'a str) -> bool { // match self.into_searcher(haystack).next() { // SearchStep::Match(0, _) => true, // _ => false, // } // } // // /// Checks whether the pattern matches at the back of the haystack // // #[inline] // fn is_suffix_of(self, haystack: &'a str) -> bool // where Self::Searcher: ReverseSearcher<'a> // { // match self.into_searcher(haystack).next_back() { // SearchStep::Match(_, j) if haystack.len() == j => true, // _ => false, // } // } // } // macro_rules! pattern_methods {<|fim▁hole|> // type Searcher = $t; // // #[inline] // fn into_searcher(self, haystack: &'a str) -> $t { // ($smap)(($pmap)(self).into_searcher(haystack)) // } // // #[inline] // fn is_contained_in(self, haystack: &'a str) -> bool { // ($pmap)(self).is_contained_in(haystack) // } // // #[inline] // fn is_prefix_of(self, haystack: &'a str) -> bool { // ($pmap)(self).is_prefix_of(haystack) // } // // #[inline] // fn is_suffix_of(self, haystack: &'a str) -> bool // where $t: ReverseSearcher<'a> // { // ($pmap)(self).is_suffix_of(haystack) // } // } // } // impl<'a, 'b> Pattern<'a> for &'b &'b str { // pattern_methods!(StrSearcher<'a, 'b>, |&s| s, |s| s); // } // unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> { // #[inline] // fn haystack(&self) -> &'a str { // self.haystack // } // // #[inline] // fn next(&mut self) -> SearchStep { // str_search_step(self, // |m: &mut StrSearcher| { // // Forward step for empty needle // let current_start = m.start; // if !m.state.done() { // m.start = m.haystack.char_range_at(current_start).next; // m.state = State::Reject(current_start, m.start); // } // SearchStep::Match(current_start, current_start) // }, // |m: &mut StrSearcher| { // // Forward step for nonempty needle // let current_start = m.start; // // Compare byte window because this might break utf8 boundaries // let possible_match = &m.haystack.as_bytes()[m.start .. m.start + m.needle.len()]; // if possible_match == m.needle.as_bytes() { // m.start += m.needle.len(); // SearchStep::Match(current_start, m.start) // } else { // // Skip a char // let haystack_suffix = &m.haystack[m.start..]; // m.start += haystack_suffix.chars().next().unwrap().len_utf8(); // SearchStep::Reject(current_start, m.start) // } // }) // } // } #[test] fn into_searcher_test1() { let string: &str = "玻璃"; let string_ptr: &&str = &string; let haystack: &str = "我能吞下玻璃而不傷身體。"; let mut searcher: StrSearcher = string_ptr.into_searcher(haystack); assert_eq!(searcher.next(), Reject(0, 3)); assert_eq!(searcher.next(), Reject(3, 6)); assert_eq!(searcher.next(), Reject(6, 9)); assert_eq!(searcher.next(), Reject(9, 12)); assert_eq!(searcher.next(), Match(12, 18)); assert_eq!(searcher.next(), Reject(18, 21)); assert_eq!(searcher.next(), Reject(21, 24)); assert_eq!(searcher.next(), Reject(24, 27)); assert_eq!(searcher.next(), Reject(27, 30)); assert_eq!(searcher.next(), Reject(30, 33)); assert_eq!(searcher.next(), Reject(33, 36)); assert_eq!(searcher.next(), Done); } }<|fim▁end|>
// ($t:ty, $pmap:expr, $smap:expr) => {
<|file_name|>font_template.rs<|end_file_name|><|fim▁begin|>/* 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/. */ use std::fs::File; use std::io::Read; use string_cache::Atom; /// Platform specific font representation for Linux. /// The identifier is an absolute path, and the bytes /// field is the loaded data that can be passed to /// freetype and azure directly. #[derive(Deserialize, Serialize)] pub struct FontTemplateData { pub bytes: Vec<u8>, pub identifier: Atom, } impl FontTemplateData { pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> FontTemplateData { let bytes = match font_data { Some(bytes) => { bytes<|fim▁hole|> let mut buffer = vec![]; file.read_to_end(&mut buffer).unwrap(); buffer }, }; FontTemplateData { bytes: bytes, identifier: identifier, } } }<|fim▁end|>
}, None => { // TODO: Handle file load failure! let mut file = File::open(&*identifier).unwrap();
<|file_name|>views.py<|end_file_name|><|fim▁begin|># Patchless XMLRPC Service for Django # Kind of hacky, and stolen from Crast on irc.freenode.net:#django # Self documents as well, so if you call it from outside of an XML-RPC Client # it tells you about itself and its methods # # Brendan W. McAdams <[email protected]> # SimpleXMLRPCDispatcher lets us register xml-rpc calls w/o # running a full XMLRPC Server. It's up to us to dispatch data from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from buildfarm.models import Package, Queue from repository.models import Repository, PisiPackage from source.models import SourcePackage from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger import xmlrpclib from django.template.loader import render_to_string from django.utils import simplejson <|fim▁hole|> from django.utils import simplejson from django.db import transaction from django.shortcuts import redirect from django.contrib.admin.views.decorators import staff_member_required from django.contrib import messages from buildfarm.tasks import build_all_in_queue class NewQueueForm (forms.ModelForm): class Meta: model = Queue fields = ( 'name', 'builder', 'source_repo', 'binman', 'sandboxed') def site_index (request): queues = Queue.objects.all () context = { 'queues': queues, 'navhint': 'queue', 'not_reload': 'true', 'form' : NewQueueForm() } return render (request, "buildfarm/site_index.html", context) def package_progress_json (request, queue_id): rdict = {} q = Queue.objects.get(id=queue_id) packages = Package.objects.filter(queue=q) pct =float ( float(q.current) / q.length ) * 100 rdict = { 'percent' : pct, 'total': q.length, 'current': q.current, 'name_current': q.current_package_name } json = simplejson.dumps(rdict, ensure_ascii=False) return HttpResponse( json, content_type='application/json') @staff_member_required def delete_from_queue (request, package_id): pkg = get_object_or_404 (Package, id=package_id) q_id = pkg.queue.id pkg.delete () return redirect ('/buildfarm/queue/%d/' % q_id) @staff_member_required def delete_queue (request, queue_id): queue = get_object_or_404 (Queue, id=queue_id) queue.delete () return redirect ('/manage/') @staff_member_required def new_queue (request): if request.method == 'POST': # New submission form = NewQueueForm (request.POST) rdict = { 'html': "<b>Fail</b>", 'tags': 'fail' } context = Context ({'form': form}) if form.is_valid (): rdict = { 'html': "The new queue has been set up", 'tags': 'success' } model = form.save (commit=False) model.current = 0 model.length = 0 model.current_package_name = "" model.save () else: html = render_to_string ('buildfarm/new_queue.html', {'form_queue': form}) rdict = { 'html': html, 'tags': 'fail' } json = simplejson.dumps(rdict, ensure_ascii=False) print json # And send it off. return HttpResponse( json, content_type='application/json') else: form = NewQueueForm () context = {'form': form } return render (request, 'buildfarm/new_queue.html', context) def queue_index(request, queue_id=None): q = get_object_or_404 (Queue, id=queue_id) packages = Package.objects.filter(queue=q).order_by('build_status') paginator = Paginator (packages, 15) pkg_count = q.length if (pkg_count > 0): pct =float ( float(q.current) / q.length ) * 100 else: pct = 0 page = request.GET.get("page") try: packages = paginator.page(page) except PageNotAnInteger: packages = paginator.page (1) except EmptyPage: packages = paginator.page (paginator.num_pages) context = {'navhint': 'queue', 'queue': q, 'package_list': packages, 'total_packages': q.length, 'current_package': q.current, 'total_pct': pct, 'current_package_name': q.current_package_name} return render (request, "buildfarm/index.html", context) @staff_member_required def build_queue (request, queue_id): queue = Queue.objects.get (id=queue_id) messages.info (request, "Starting build of \"%s\" queue" % queue.name) build_all_in_queue.delay (queue_id) return redirect ('/manage/') @staff_member_required def populate_queue (request, queue_id): q = Queue.objects.get(id=queue_id) packages = SourcePackage.objects.filter (repository=q.source_repo) failList = list () for package in packages: binaries = PisiPackage.objects.filter(source_name=package.name) if len(binaries) == 0: # We have no binaries print "New package for source: %s" % (package.name) failList.append (package) else: for package2 in binaries: if package2.release != package.release: print "Newer release for: %s" % package2.name failList.append (package) break try: binary = Package.objects.get(queue=q, name=package.name) failList.remove (package) except: pass with transaction.commit_on_success(): for fail in failList: pkg = Package () pkg.name = fail.name pkg.version = fail.version pkg.build_status = "pending" pkg.queue = q pkg.spec_uri = fail.source_uri pkg.save () return redirect ("/buildfarm/queue/%d" % q.id)<|fim▁end|>
from django.template import Context, Template from django import forms
<|file_name|>annotate.py<|end_file_name|><|fim▁begin|># Portions Copyright (c) Meta Platforms, Inc. and affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # Copyright Mercurial Contributors # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from typing import TypeVar, Callable, List, Tuple, Optional from . import mdiff from .thirdparty import attr F = TypeVar("F") L = TypeVar("L") def annotate( base: F, parents: Callable[[F], List[F]], decorate: Callable[[F], Tuple[List[L], bytes]], diffopts: mdiff.diffopts, skip: Optional[Callable[[F], bool]] = None, ) -> Tuple[List[L], bytes]: """annotate algorithm base: starting point, usually a fctx. parents: get parents from F. decorate: get (lines, text) from F. Return (lines, text) for 'base'. """ # This algorithm would prefer to be recursive, but Python is a # bit recursion-hostile. Instead we do an iterative # depth-first search. # 1st DFS pre-calculates pcache and needed visit = [base] pcache = {} needed = {base: 1} while visit: f = visit.pop() if f in pcache: continue pl = parents(f) pcache[f] = pl for p in pl: needed[p] = needed.get(p, 0) + 1 if p not in pcache: visit.append(p) # 2nd DFS does the actual annotate visit[:] = [base] hist = {} while visit: f = visit[-1] if f in hist: visit.pop() continue ready = True pl = pcache[f] for p in pl: if p not in hist: ready = False visit.append(p) if ready: visit.pop() curr = decorate(f) skipchild = False if skip is not None: skipchild = skip(f) curr = _annotatepair([hist[p] for p in pl], f, curr, skipchild, diffopts) for p in pl: if needed[p] == 1: del hist[p] del needed[p] else:<|fim▁hole|> return hist[base] def _annotatepair(parents, childfctx, child, skipchild, diffopts): r""" Given parent and child fctxes and annotate data for parents, for all lines in either parent that match the child, annotate the child with the parent's data. Additionally, if `skipchild` is True, replace all other lines with parent annotate data as well such that child is never blamed for any lines. See test-annotate.py for unit tests. """ pblocks = [ (parent, mdiff.allblocks(parent[1], child[1], opts=diffopts)) for parent in parents ] if skipchild: # Need to iterate over the blocks twice -- make it a list pblocks = [(p, list(blocks)) for (p, blocks) in pblocks] # Mercurial currently prefers p2 over p1 for annotate. # TODO: change this? for parent, blocks in pblocks: for (a1, a2, b1, b2), t in blocks: # Changed blocks ('!') or blocks made only of blank lines ('~') # belong to the child. if t == "=": child[0][b1:b2] = parent[0][a1:a2] if skipchild: # Now try and match up anything that couldn't be matched, # Reversing pblocks maintains bias towards p2, matching above # behavior. pblocks.reverse() # The heuristics are: # * Work on blocks of changed lines (effectively diff hunks with -U0). # This could potentially be smarter but works well enough. # * For a non-matching section, do a best-effort fit. Match lines in # diff hunks 1:1, dropping lines as necessary. # * Repeat the last line as a last resort. # First, replace as much as possible without repeating the last line. remaining = [(parent, []) for parent, _blocks in pblocks] for idx, (parent, blocks) in enumerate(pblocks): for (a1, a2, b1, b2), _t in blocks: if a2 - a1 >= b2 - b1: for bk in range(b1, b2): if child[0][bk].fctx == childfctx: ak = min(a1 + (bk - b1), a2 - 1) child[0][bk] = attr.evolve(parent[0][ak], skip=True) else: remaining[idx][1].append((a1, a2, b1, b2)) # Then, look at anything left, which might involve repeating the last # line. for parent, blocks in remaining: for a1, a2, b1, b2 in blocks: for bk in range(b1, b2): if child[0][bk].fctx == childfctx: ak = min(a1 + (bk - b1), a2 - 1) child[0][bk] = attr.evolve(parent[0][ak], skip=True) return child<|fim▁end|>
needed[p] -= 1 hist[f] = curr del pcache[f]
<|file_name|>search.rs<|end_file_name|><|fim▁begin|>use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap, HashSet}; use std::hash::Hash; /// A node in a graph with a regular grid. pub trait GridNode: PartialEq + Eq + Clone + Hash + PartialOrd + Ord { /// List the neighbor nodes of this graph node. fn neighbors(&self) -> Vec<Self>; } /// A pathfinding map structure. /// /// A Dijkstra map lets you run pathfinding from any graph node it covers /// towards or away from the target nodes of the map. Currently the structure /// only supports underlying graphs with a fixed grid graph where the /// neighbors of each node must be the adjacent grid cells of that node. pub struct Dijkstra<N> { pub weights: HashMap<N, u32>, } impl<N: GridNode> Dijkstra<N> { /// Create a new Dijkstra map up to limit distance from goals, omitting /// nodes for which the is_valid predicate returns false. pub fn new<F: Fn(&N) -> bool>(goals: Vec<N>, is_valid: F, limit: u32) -> Dijkstra<N> { assert!(!goals.is_empty()); let mut weights = HashMap::new(); let mut edge = HashSet::new(); for n in goals { edge.insert(n); } for dist in 0..(limit) { for n in &edge { weights.insert(n.clone(), dist); } let mut new_edge = HashSet::new(); for n in &edge { for m in n.neighbors() { if is_valid(&m) && !weights.contains_key(&m) { new_edge.insert(m); } } } edge = new_edge; if edge.is_empty() { break; } } Dijkstra { weights } } /// Return the neighbors of a cell (if any), sorted from downhill to /// uphill. pub fn sorted_neighbors(&self, node: &N) -> Vec<N> { let mut ret = Vec::new(); for n in &node.neighbors() { if let Some(w) = self.weights.get(n) { ret.push((w, n.clone())); } } ret.sort_by(|&(w1, _), &(w2, _)| w1.cmp(w2)); ret.into_iter().map(|(_, n)| n).collect() } } /// Find A* path in freeform graph. /// /// The `neighbors` function returns neighboring nodes and their estimated distance from the goal. /// The search will treat any node whose distance is zero as a goal and return a path leading to /// it. pub fn astar_path<N, F>(start: N, end: &N, neighbors: F) -> Option<Vec<N>> where N: Eq + Hash + Clone, F: Fn(&N) -> Vec<(N, f32)>, { #[derive(Eq, PartialEq)] struct MetricNode<N> { value: u32, item: N, come_from: Option<N>, } impl<N: Eq> Ord for MetricNode<N> { fn cmp(&self, other: &Self) -> Ordering { self.value.cmp(&other.value) } } impl<N: Eq> PartialOrd for MetricNode<N> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } fn node<N: Eq>(item: N, dist: f32, come_from: Option<N>) -> MetricNode<N> { debug_assert!(dist >= 0.0); // Convert dist to integers so we can push MetricNodes into BinaryHeap that expects Ord. // The trick here is that non-negative IEEE 754 floats have the same ordering as their // binary representations interpreted as integers. // // Also flip the sign on the value, shorter distance means bigger value, since BinaryHeap // returns the largest item first. let value = ::std::u32::MAX - dist.to_bits(); MetricNode { item, value, come_from, } } let mut come_from = HashMap::new(); let mut open = BinaryHeap::new(); open.push(node(start.clone(), ::std::f32::MAX, None)); // Find shortest path. let mut goal = loop { if let Some(closest) = open.pop() { if come_from.contains_key(&closest.item) { // Already saw it through a presumably shorter path... continue; } if let Some(from) = closest.come_from { come_from.insert(closest.item.clone(), from); } if &closest.item == end { break Some(closest.item); } for (item, dist) in neighbors(&closest.item) { let already_seen = come_from.contains_key(&item) || item == start; if already_seen { continue; } open.push(node(item, dist, Some(closest.item.clone()))); } } else { break None; } }; // Extract path from the graph structure. let mut path = Vec::new(); while let Some(x) = goal { goal = come_from.remove(&x); path.push(x); } path.reverse(); if path.is_empty() { None } else { Some(path) } } #[cfg(test)] mod test { use super::*; #[test] fn test_astar() { fn neighbors(origin: i32, &x: &i32) -> Vec<(i32, f32)> { let mut ret = Vec::with_capacity(2); for i in &[-1, 1] { let x = x + i; ret.push((x, (x - origin).abs() as f32)); } ret } assert_eq!(Some(vec![8]), astar_path(8, &8, |_| Vec::new())); assert_eq!(None, astar_path(8, &12, |_| Vec::new())); assert_eq!(Some(vec![8]), astar_path(8, &8, |x| neighbors(8, x))); assert_eq!( Some(vec![8, 9, 10, 11, 12]),<|fim▁hole|> ); } }<|fim▁end|>
astar_path(8, &12, |x| neighbors(8, x))
<|file_name|>ServiceInfo.py<|end_file_name|><|fim▁begin|>from Components.Converter.Converter import Converter from enigma import iServiceInformation, iPlayableService from Components.Element import cached from Tools.Transponder import ConvertToHumanReadable class ServiceInfo(Converter, object): HAS_TELETEXT = 0 IS_MULTICHANNEL = 1 IS_CRYPTED = 2 IS_WIDESCREEN = 3 SUBSERVICES_AVAILABLE = 4 XRES = 5 YRES = 6 APID = 7 VPID = 8 PCRPID = 9 PMTPID = 10 TXTPID = 11 TSID = 12 ONID = 13 SID = 14 FRAMERATE = 15 TRANSFERBPS = 16 HAS_HBBTV = 17<|fim▁hole|> def __init__(self, type): Converter.__init__(self, type) self.type, self.interesting_events = { "HasTelext": (self.HAS_TELETEXT, (iPlayableService.evUpdatedInfo,)), "IsMultichannel": (self.IS_MULTICHANNEL, (iPlayableService.evUpdatedInfo,)), "IsCrypted": (self.IS_CRYPTED, (iPlayableService.evUpdatedInfo,)), "IsWidescreen": (self.IS_WIDESCREEN, (iPlayableService.evVideoSizeChanged,)), "SubservicesAvailable": (self.SUBSERVICES_AVAILABLE, (iPlayableService.evUpdatedEventInfo,)), "VideoWidth": (self.XRES, (iPlayableService.evVideoSizeChanged,)), "VideoHeight": (self.YRES, (iPlayableService.evVideoSizeChanged,)), "AudioPid": (self.APID, (iPlayableService.evUpdatedInfo,)), "VideoPid": (self.VPID, (iPlayableService.evUpdatedInfo,)), "PcrPid": (self.PCRPID, (iPlayableService.evUpdatedInfo,)), "PmtPid": (self.PMTPID, (iPlayableService.evUpdatedInfo,)), "TxtPid": (self.TXTPID, (iPlayableService.evUpdatedInfo,)), "TsId": (self.TSID, (iPlayableService.evUpdatedInfo,)), "OnId": (self.ONID, (iPlayableService.evUpdatedInfo,)), "Sid": (self.SID, (iPlayableService.evUpdatedInfo,)), "Framerate": (self.FRAMERATE, (iPlayableService.evVideoSizeChanged,iPlayableService.evUpdatedInfo,)), "TransferBPS": (self.TRANSFERBPS, (iPlayableService.evUpdatedInfo,)), "HasHBBTV": (self.HAS_HBBTV, (iPlayableService.evUpdatedInfo,iPlayableService.evHBBTVInfo,)), "AudioTracksAvailable": (self.AUDIOTRACKS_AVAILABLE, (iPlayableService.evUpdatedInfo,)), "SubtitlesAvailable": (self.SUBTITLES_AVAILABLE, (iPlayableService.evUpdatedInfo,)), "Freq_Info": (self.FREQ_INFO, (iPlayableService.evUpdatedInfo,)), }[type] def getServiceInfoString(self, info, what, convert = lambda x: "%d" % x): v = info.getInfo(what) if v == -1: return "N/A" if v == -2: return info.getInfoString(what) return convert(v) @cached def getBoolean(self): service = self.source.service info = service and service.info() if not info: return False if self.type == self.HAS_TELETEXT: tpid = info.getInfo(iServiceInformation.sTXTPID) return tpid != -1 elif self.type == self.IS_MULTICHANNEL: # FIXME. but currently iAudioTrackInfo doesn't provide more information. audio = service.audioTracks() if audio: n = audio.getNumberOfTracks() idx = 0 while idx < n: i = audio.getTrackInfo(idx) description = i.getDescription(); if "AC3" in description or "AC-3" in description or "DTS" in description: return True idx += 1 return False elif self.type == self.IS_CRYPTED: return info.getInfo(iServiceInformation.sIsCrypted) == 1 elif self.type == self.IS_WIDESCREEN: return info.getInfo(iServiceInformation.sAspect) in (3, 4, 7, 8, 0xB, 0xC, 0xF, 0x10) elif self.type == self.SUBSERVICES_AVAILABLE: subservices = service.subServices() return subservices and subservices.getNumberOfSubservices() > 0 elif self.type == self.HAS_HBBTV: return info.getInfoString(iServiceInformation.sHBBTVUrl) != "" elif self.type == self.AUDIOTRACKS_AVAILABLE: audio = service.audioTracks() return audio and audio.getNumberOfTracks() > 1 elif self.type == self.SUBTITLES_AVAILABLE: subtitle = service and service.subtitle() subtitlelist = subtitle and subtitle.getSubtitleList() if subtitlelist: return len(subtitlelist) > 0 return False boolean = property(getBoolean) @cached def getText(self): service = self.source.service info = service and service.info() if not info: return "" if self.type == self.XRES: return self.getServiceInfoString(info, iServiceInformation.sVideoWidth) elif self.type == self.YRES: return self.getServiceInfoString(info, iServiceInformation.sVideoHeight) elif self.type == self.APID: return self.getServiceInfoString(info, iServiceInformation.sAudioPID) elif self.type == self.VPID: return self.getServiceInfoString(info, iServiceInformation.sVideoPID) elif self.type == self.PCRPID: return self.getServiceInfoString(info, iServiceInformation.sPCRPID) elif self.type == self.PMTPID: return self.getServiceInfoString(info, iServiceInformation.sPMTPID) elif self.type == self.TXTPID: return self.getServiceInfoString(info, iServiceInformation.sTXTPID) elif self.type == self.TSID: return self.getServiceInfoString(info, iServiceInformation.sTSID) elif self.type == self.ONID: return self.getServiceInfoString(info, iServiceInformation.sONID) elif self.type == self.SID: return self.getServiceInfoString(info, iServiceInformation.sSID) elif self.type == self.FRAMERATE: return self.getServiceInfoString(info, iServiceInformation.sFrameRate, lambda x: "%d fps" % ((x+500)/1000)) elif self.type == self.TRANSFERBPS: return self.getServiceInfoString(info, iServiceInformation.sTransferBPS, lambda x: "%d kB/s" % (x/1024)) elif self.type == self.FREQ_INFO: feinfo = service.frontendInfo() if feinfo is None: return "" feraw = feinfo.getAll(False) if feraw is None: return "" fedata = ConvertToHumanReadable(feraw) if fedata is None: return "" frequency = fedata.get("frequency") if frequency: frequency = str(frequency / 1000) sr_txt = "Sr:" polarization = fedata.get("polarization_abbreviation") if polarization is None: polarization = "" symbolrate = str(int(fedata.get("symbol_rate", 0) / 1000)) if symbolrate == "0": sr_txt = "" symbolrate = "" fec = fedata.get("fec_inner") if fec is None: fec = "" out = "Freq: %s %s %s %s %s" % (frequency, polarization, sr_txt, symbolrate, fec) return out return "" text = property(getText) @cached def getValue(self): service = self.source.service info = service and service.info() if not info: return -1 if self.type == self.XRES: return info.getInfo(iServiceInformation.sVideoWidth) if self.type == self.YRES: return info.getInfo(iServiceInformation.sVideoHeight) if self.type == self.FRAMERATE: return info.getInfo(iServiceInformation.sFrameRate) return -1 value = property(getValue) def changed(self, what): if what[0] != self.CHANGED_SPECIFIC or what[1] in self.interesting_events: Converter.changed(self, what)<|fim▁end|>
AUDIOTRACKS_AVAILABLE = 18 SUBTITLES_AVAILABLE = 19 FREQ_INFO = 20
<|file_name|>Renderer2D.Effort.js<|end_file_name|><|fim▁begin|>window.Rendxx = window.Rendxx || {}; window.Rendxx.Game = window.Rendxx.Game || {}; window.Rendxx.Game.Ghost = window.Rendxx.Game.Ghost || {}; window.Rendxx.Game.Ghost.Renderer2D = window.Rendxx.Game.Ghost.Renderer2D || {}; (function (RENDERER) { var Data = RENDERER.Data; var GridSize = Data.grid.size; var _Data = { size: 3, tileSize: 128, tileDispDuration: 50, Name: { 'Blood': 0, 'Electric': 1 } }; var Effort = function (entity) { // data ---------------------------------------------------------- var that = this, tex = {}, _scene = entity.env.scene['effort']; // callback ------------------------------------------------------ // public method ------------------------------------------------- this.update = function (newEffort) { if (newEffort == null || newEffort.length === 0) return; for (var i = 0, l = newEffort.length; i < l;i++){ createEffort(newEffort[i]); } }; this.render = function (delta) { }; // private method ------------------------------------------------- var createEffort = function (effort) { if (effort==null) return; var effortName = effort[0]; var x = effort[1]; var y = effort[2]; if (!tex.hasOwnProperty(effortName)) return; var item = new PIXI.extras.MovieClip(tex[effortName]); item.loop = false; item.anchor.set(0.5, 0.5); item.animationSpeed = 0.5; item.position.set(x * GridSize, y * GridSize); item.scale.set(_Data.size * GridSize / _Data.tileSize, _Data.size * GridSize / _Data.tileSize); item.onComplete = function () { _scene.removeChild(this) }; _scene.addChild(item); item.play(); }; // setup ----------------------------------------------- var _setupTex = function () { tex = {}; var path = entity.root + Data.files.path[Data.categoryName.sprite]; // texture loader ------------------------------------------------------------------------------------------- PIXI.loader .add(path + 'effort.blood.json') .add(path + 'effort.electric.json') .load(function (loader, resources) { // blood var frames = []; var name = path + 'effort.blood.json'; var _f = resources[name].data.frames; var i = 0; while (true) { var val = i < 10 ? '0' + i : i; if (!_f.hasOwnProperty('animation00' + val)) break; frames.push(loader.resources[name].textures['animation00' + val]); i++; } <|fim▁hole|> var frames = []; var name = path + 'effort.electric.json'; var _f = resources[name].data.frames; var i = 0; while (true) { var val = i < 10 ? '0' + i : i; if (!_f.hasOwnProperty('animation00' + val)) break; frames.push(loader.resources[name].textures['animation00' + val]); i++; } tex[_Data.Name.Electric] = frames; }); }; var _init = function () { _setupTex(); }; _init(); }; RENDERER.Effort = Effort; RENDERER.Effort.Data = _Data; })(window.Rendxx.Game.Ghost.Renderer2D);<|fim▁end|>
tex[_Data.Name.Blood] = frames; // electric
<|file_name|>type_traits.hpp<|end_file_name|><|fim▁begin|>#ifndef __CXXU_TYPE_TRAITS_H__ #define __CXXU_TYPE_TRAITS_H__ #include <type_traits> #include <memory> namespace cxxu { template <typename T> struct is_shared_ptr_helper : std::false_type { typedef T element_type; static element_type& deref(element_type& e) { return e; } static const element_type& deref(const element_type& e) { return e; } }; template <typename T> struct is_shared_ptr_helper<std::shared_ptr<T>> : std::true_type { typedef typename std::remove_cv<T>::type element_type; typedef std::shared_ptr<element_type> ptr_type; <|fim▁hole|> static element_type& deref(ptr_type& p) { return *p; } static const element_type& deref(const ptr_type& p) { return *p; } }; template <typename T> struct is_shared_ptr : is_shared_ptr_helper<typename std::remove_cv<T>::type> {}; } // namespace cxxu #endif // __CXXU_TYPE_TRAITS_H__<|fim▁end|>
<|file_name|>dash.ts<|end_file_name|><|fim▁begin|>/// <reference path="apimanPlugin.ts"/> module Apiman { export var DashController = _module.controller("Apiman.DashController", ['$scope', 'PageLifecycle', 'CurrentUser', ($scope, PageLifecycle, CurrentUser) => { PageLifecycle.loadPage('Dash', undefined, $scope, function() { $scope.isAdmin = CurrentUser.getCurrentUser().admin; $scope.currentUser = CurrentUser.getCurrentUser(); PageLifecycle.setPageTitle('dashboard');<|fim▁hole|><|fim▁end|>
}); }]); }
<|file_name|>lib.setAction.js<|end_file_name|><|fim▁begin|>'use strict'; const setAction = (creep) => { if (creep.memory.action && creep.carry.energy === 0 || creep.memory.role === 'attacker' || creep.memory.role === 'healer'){ creep.memory.action = false; } if (!creep.memory.action && creep.carry.energy === creep.carryCapacity){ <|fim▁hole|> } }; module.exports = setAction;<|fim▁end|>
creep.memory.action = true;
<|file_name|>tls-try-with.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(stable_features)] // ignore-emscripten no threads support #![feature(thread_local_try_with)] use std::thread; static mut DROP_RUN: bool = false; struct Foo; thread_local!(static FOO: Foo = Foo {}); impl Drop for Foo { fn drop(&mut self) { assert!(FOO.try_with(|_| panic!("`try_with` closure run")).is_err()); unsafe { DROP_RUN = true; } } } fn main() { thread::spawn(|| { assert_eq!(FOO.try_with(|_| {<|fim▁hole|> }).expect("`try_with` failed"), 132); }).join().unwrap(); assert!(unsafe { DROP_RUN }); }<|fim▁end|>
132
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>mod state;<|fim▁hole|>pub use self::state::*; pub use self::xml::generate;<|fim▁end|>
mod xml;
<|file_name|>serializers.py<|end_file_name|><|fim▁begin|>from rest_framework import serializers as ser from api.base.serializers import ShowIfVersion from api.providers.serializers import PreprintProviderSerializer class DeprecatedPreprintProviderSerializer(PreprintProviderSerializer): class Meta: type_ = 'preprint_providers' <|fim▁hole|> # Deprecated fields header_text = ShowIfVersion( ser.CharField(read_only=True, default=''), min_version='2.0', max_version='2.3' ) banner_path = ShowIfVersion( ser.CharField(read_only=True, default=''), min_version='2.0', max_version='2.3' ) logo_path = ShowIfVersion( ser.CharField(read_only=True, default=''), min_version='2.0', max_version='2.3' ) email_contact = ShowIfVersion( ser.CharField(read_only=True, allow_null=True), min_version='2.0', max_version='2.3' ) social_twitter = ShowIfVersion( ser.CharField(read_only=True, allow_null=True), min_version='2.0', max_version='2.3' ) social_facebook = ShowIfVersion( ser.CharField(read_only=True, allow_null=True), min_version='2.0', max_version='2.3' ) social_instagram = ShowIfVersion( ser.CharField(read_only=True, allow_null=True), min_version='2.0', max_version='2.3' ) subjects_acceptable = ShowIfVersion( ser.ListField(read_only=True, default=[]), min_version='2.0', max_version='2.4' )<|fim▁end|>
<|file_name|>process.rs<|end_file_name|><|fim▁begin|>// @lecorref - github.com/lecorref, @geam - github.com/geam, // @adjivas - github.com/adjivas. See the LICENSE // file at the top-level directory of this distribution and at // https://github.com/adjivas/krpsim // // This file may not be copied, modified, or distributed // except according to those terms. extern crate krpsim; <|fim▁hole|>#[test] fn test_process_constructor_new() { assert_eq!( format!("{}", Process::from_integer( "knight".to_string(), // name 10, // cycle Inventory::new( vec!( Ressource::new("silver-rupee".to_string(), 200), ) // need ), Inventory::new( vec!( Ressource::new("heart".to_string(), 10), ) // result ), ) ), "knight:(silver-rupee:200):(heart:10):10" ); }<|fim▁end|>
use self::krpsim::format::stock::inventory::Inventory; use self::krpsim::format::stock::ressource::Ressource; use self::krpsim::format::operate::process::Process;
<|file_name|>aggregation_info.py<|end_file_name|><|fim▁begin|>from util import hash256, hash_pks from copy import deepcopy class AggregationInfo: """ AggregationInfo represents information of how a tree of aggregate signatures was created. Different tress will result in different signatures, due to exponentiations required for security. An AggregationInfo is represented as a map from (message_hash, pk) to exponents. When verifying, a verifier will take the signature, along with this map, and raise each public key to the correct exponent, and multiply the pks together, for identical messages. """ def __init__(self, tree, message_hashes, public_keys): self.tree = tree self.message_hashes = message_hashes self.public_keys = public_keys def empty(self): return not self.tree def __eq__(self, other): return not self.__lt__(other) and not other.__lt__(self) def __lt__(self, other): """ Compares two AggregationInfo objects, this is necessary for sorting them. Comparison is done by comparing (message hash, pk, exponent) """ combined = [(self.message_hashes[i], self.public_keys[i], self.tree[(self.message_hashes[i], self.public_keys[i])]) for i in range(len(self.public_keys))] combined_other = [(other.message_hashes[i], other.public_keys[i], other.tree[(other.message_hashes[i], other.public_keys[i])]) for i in range(len(other.public_keys))] for i in range(max(len(combined), len(combined_other))): if i == len(combined): return True if i == len(combined_other): return False if combined[i] < combined_other[i]: return True if combined_other[i] < combined[i]: return False return False def __str__(self): ret = "" for key, value in self.tree.items(): ret += ("(" + key[0].hex() + "," + key[1].serialize().hex() + "):\n" + hex(value) + "\n") return ret def __deepcopy__(self, memo): new_tree = deepcopy(self.tree, memo) new_mh = deepcopy(self.message_hashes, memo) new_pubkeys = deepcopy(self.public_keys, memo) return AggregationInfo(new_tree, new_mh, new_pubkeys) @staticmethod def from_msg_hash(public_key, message_hash): tree = {} tree[(message_hash, public_key)] = 1 return AggregationInfo(tree, [message_hash], [public_key]) @staticmethod def from_msg(pk, message): return AggregationInfo.from_msg_hash(pk, hash256(message)) @staticmethod def simple_merge_infos(aggregation_infos): """ Infos are just merged together with no addition of exponents, since they are disjoint """ new_tree = {} for info in aggregation_infos: new_tree.update(info.tree) mh_pubkeys = [k for k, v in new_tree.items()] mh_pubkeys.sort() message_hashes = [message_hash for (message_hash, public_key) in mh_pubkeys] public_keys = [public_key for (message_hash, public_key) in mh_pubkeys] return AggregationInfo(new_tree, message_hashes, public_keys) @staticmethod def secure_merge_infos(colliding_infos): """ Infos are merged together with combination of exponents """ # Groups are sorted by message then pk then exponent # Each info object (and all of it's exponents) will be # exponentiated by one of the Ts colliding_infos.sort() sorted_keys = [] for info in colliding_infos: for key, value in info.tree.items(): sorted_keys.append(key) sorted_keys.sort() sorted_pks = [public_key for (message_hash, public_key) in sorted_keys] computed_Ts = hash_pks(len(colliding_infos), sorted_pks) # Group order, exponents can be reduced mod the order order = sorted_pks[0].value.ec.n new_tree = {} for i in range(len(colliding_infos)): for key, value in colliding_infos[i].tree.items(): if key not in new_tree: # This message & pk have not been included yet new_tree[key] = (value * computed_Ts[i]) % order else: # This message and pk are already included, so multiply addend = value * computed_Ts[i] new_tree[key] = (new_tree[key] + addend) % order mh_pubkeys = [k for k, v in new_tree.items()] mh_pubkeys.sort() message_hashes = [message_hash for (message_hash, public_key) in mh_pubkeys] public_keys = [public_key for (message_hash, public_key) in mh_pubkeys] return AggregationInfo(new_tree, message_hashes, public_keys) @staticmethod def merge_infos(aggregation_infos): messages = set() colliding_messages = set() for info in aggregation_infos: messages_local = set() for key, value in info.tree.items(): if key[0] in messages and key[0] not in messages_local: colliding_messages.add(key[0]) messages.add(key[0]) messages_local.add(key[0]) if len(colliding_messages) == 0: return AggregationInfo.simple_merge_infos(aggregation_infos) colliding_infos = [] non_colliding_infos = [] for info in aggregation_infos: info_collides = False for key, value in info.tree.items(): if key[0] in colliding_messages: info_collides = True colliding_infos.append(info)<|fim▁hole|> combined = AggregationInfo.secure_merge_infos(colliding_infos) non_colliding_infos.append(combined) return AggregationInfo.simple_merge_infos(non_colliding_infos) """ Copyright 2018 Chia Network 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. """<|fim▁end|>
break if not info_collides: non_colliding_infos.append(info)
<|file_name|>response.py<|end_file_name|><|fim▁begin|># urllib3/response.py # Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import gzip import logging import zlib from io import BytesIO from .exceptions import HTTPError try: basestring = basestring except NameError: # Python 3 basestring = (str, bytes) log = logging.getLogger(__name__) def decode_gzip(data): gzipper = gzip.GzipFile(fileobj=BytesIO(data)) return gzipper.read() def decode_deflate(data): try: return zlib.decompress(data) except zlib.error: return zlib.decompress(data, -zlib.MAX_WBITS) class HTTPResponse(object): """ HTTP Response container. Backwards-compatible to httplib's HTTPResponse but the response ``body`` is loaded and decoded on-demand when the ``data`` property is accessed. Extra parameters for behaviour not present in httplib.HTTPResponse: :param preload_content: If True, the response's body will be preloaded during construction. :param decode_content: If True, attempts to decode specific content-encoding's based on headers (like 'gzip' and 'deflate') will be skipped and raw data will be used instead. :param original_response: When this HTTPResponse wrapper is generated from an httplib.HTTPResponse object, it's convenient to include the original for debug purposes. It's otherwise unused. """ CONTENT_DECODERS = { 'gzip': decode_gzip, 'deflate': decode_deflate, } def __init__(self, body='', headers=None, status=0, version=0, reason=None, strict=0, preload_content=True, decode_content=True, original_response=None, pool=None, connection=None): self.headers = headers or {} self.status = status self.version = version self.reason = reason self.strict = strict self._decode_content = decode_content self._body = body if body and isinstance(body, basestring) else None self._fp = None self._original_response = original_response self._pool = pool self._connection = connection if hasattr(body, 'read'): self._fp = body if preload_content and not self._body: self._body = self.read(decode_content=decode_content) def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in [301, 302, 303, 307]: return self.headers.get('location') return False def release_conn(self): if not self._pool or not self._connection: return self._pool._put_conn(self._connection) self._connection = None @property def data(self): # For backwords-compat with earlier urllib3 0.4 and earlier. if self._body: return self._body if self._fp: return self.read(cache_content=True) def read(self, amt=None, decode_content=None, cache_content=False): """ Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, decoding and caching is skipped because we can't decode partial content nor does it make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. (Overridden if ``amt`` is set.) :param cache_content: If True, will save the returned data such that the same result is returned despite of the state of the underlying file object. This is useful if you want the ``.data`` property to continue working after having ``.read()`` the file object. (Overridden if ``amt`` is set.) """ content_encoding = self.headers.get('content-encoding') decoder = self.CONTENT_DECODERS.get(content_encoding) if decode_content is None: decode_content = self._decode_content if self._fp is None: return try: if amt is None: # cStringIO doesn't like amt=None<|fim▁hole|> try: if decode_content and decoder: data = decoder(data) except IOError: raise HTTPError("Received response with content-encoding: %s, but " "failed to decode it." % content_encoding) if cache_content: self._body = data return data finally: if self._original_response and self._original_response.isclosed(): self.release_conn() @classmethod def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. """ # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, 'strict', 0) return ResponseCls(body=r, # In Python 3, the header keys are returned capitalised headers=dict((k.lower(), v) for k,v in r.getheaders()), status=r.status, version=r.version, reason=r.reason, strict=strict, original_response=r, **response_kw) # Backwards-compatibility methods for httplib.HTTPResponse def getheaders(self): return self.headers def getheader(self, name, default=None): return self.headers.get(name, default)<|fim▁end|>
data = self._fp.read() else: return self._fp.read(amt)
<|file_name|>wmove.rs<|end_file_name|><|fim▁begin|>#[macro_use] extern crate cli_util; extern crate wlib; use std::env; use wlib::window; #[derive(Copy, Clone)] enum Mode { Relative, Absolute } fn main() { let name = cli_util::name(&mut env::args()); parse_args!{ description: "move window", flag mode: Mode = Mode::Relative, (&["-r", "--relative"], Mode::Relative, "move relatively (default)"), (&["-a", "--absolute"], Mode::Absolute, "move absolutely"), arg x: i32, ("x", "x coordinate"), arg y: i32, ("y", "y coordinate"), arg wid: window::ID, ("wid", "window id") } cli_util::handle_error(&name, 1, run(mode, x, y, wid)); } fn run(mode: Mode, x: i32, y: i32, wid: window::ID) -> Result<(), &'static str> {<|fim▁hole|> let mut win = try!( disp.window(wid).map_err(|_| "window does not exist") ); match mode { Mode::Relative => try!(win.reposition_relative(x, y)), Mode::Absolute => try!(win.reposition_absolute(x, y)) } Ok(()) }<|fim▁end|>
let disp = try!(wlib::Display::open());
<|file_name|>nsPlacesTransactionsService.js<|end_file_name|><|fim▁begin|>/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Places Command Controller. * * The Initial Developer of the Original Code is Google Inc. * * Portions created by the Initial Developer are Copyright (C) 2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Sungjoon Steve Won <[email protected]> (Original Author) * Asaf Romano <[email protected]> * Marco Bonarco <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ let Ci = Components.interfaces; let Cc = Components.classes; let Cr = Components.results; const LOAD_IN_SIDEBAR_ANNO = "bookmarkProperties/loadInSidebar"; const DESCRIPTION_ANNO = "bookmarkProperties/description"; const GUID_ANNO = "placesInternal/GUID"; const CLASS_ID = Components.ID("c0844a84-5a12-4808-80a8-809cb002bb4f"); const CONTRACT_ID = "@mozilla.org/browser/placesTransactionsService;1"; Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); __defineGetter__("PlacesUtils", function() { delete this.PlacesUtils var tmpScope = {}; Components.utils.import("resource://gre/modules/utils.js", tmpScope); return this.PlacesUtils = tmpScope.PlacesUtils; }); // The minimum amount of transactions we should tell our observers to begin // batching (rather than letting them do incremental drawing). const MIN_TRANSACTIONS_FOR_BATCH = 5; function placesTransactionsService() { this.mTransactionManager = Cc["@mozilla.org/transactionmanager;1"]. createInstance(Ci.nsITransactionManager); } placesTransactionsService.prototype = { classDescription: "Places Transaction Manager", classID: CLASS_ID, contractID: CONTRACT_ID, QueryInterface: XPCOMUtils.generateQI([Ci.nsIPlacesTransactionsService, Ci.nsITransactionManager]), aggregateTransactions: function placesTxn_aggregateTransactions(aName, aTransactions) { return new placesAggregateTransactions(aName, aTransactions); }, createFolder: function placesTxn_createFolder(aName, aContainer, aIndex, aAnnotations, aChildItemsTransactions) { return new placesCreateFolderTransactions(aName, aContainer, aIndex, aAnnotations, aChildItemsTransactions); }, createItem: function placesTxn_createItem(aURI, aContainer, aIndex, aTitle, aKeyword, aAnnotations, aChildTransactions) { return new placesCreateItemTransactions(aURI, aContainer, aIndex, aTitle, aKeyword, aAnnotations, aChildTransactions); }, createSeparator: function placesTxn_createSeparator(aContainer, aIndex) { return new placesCreateSeparatorTransactions(aContainer, aIndex); }, createLivemark: function placesTxn_createLivemark(aFeedURI, aSiteURI, aName, aContainer, aIndex, aAnnotations) { return new placesCreateLivemarkTransactions(aFeedURI, aSiteURI, aName, aContainer, aIndex, aAnnotations); }, moveItem: function placesTxn_moveItem(aItemId, aNewContainer, aNewIndex) { return new placesMoveItemTransactions(aItemId, aNewContainer, aNewIndex); }, removeItem: function placesTxn_removeItem(aItemId) { if (aItemId == PlacesUtils.tagsFolderId || aItemId == PlacesUtils.placesRootId || aItemId == PlacesUtils.bookmarksMenuFolderId || aItemId == PlacesUtils.toolbarFolderId) throw Cr.NS_ERROR_INVALID_ARG; // if the item lives within a tag container, use the tagging transactions var parent = PlacesUtils.bookmarks.getFolderIdForItem(aItemId); var grandparent = PlacesUtils.bookmarks.getFolderIdForItem(parent); if (grandparent == PlacesUtils.tagsFolderId) { var uri = PlacesUtils.bookmarks.getBookmarkURI(aItemId); return this.untagURI(uri, [parent]); } // if the item is a livemark container we will not save its children and // will use createLivemark to undo. if (PlacesUtils.itemIsLivemark(aItemId)) return new placesRemoveLivemarkTransaction(aItemId); return new placesRemoveItemTransaction(aItemId); }, editItemTitle: function placesTxn_editItemTitle(aItemId, aNewTitle) { return new placesEditItemTitleTransactions(aItemId, aNewTitle); }, editBookmarkURI: function placesTxn_editBookmarkURI(aItemId, aNewURI) { return new placesEditBookmarkURITransactions(aItemId, aNewURI); }, setItemAnnotation: function placesTxn_setItemAnnotation(aItemId, aAnnotationObject) { return new placesSetItemAnnotationTransactions(aItemId, aAnnotationObject); }, setPageAnnotation: function placesTxn_setPageAnnotation(aURI, aAnnotationObject) { return new placesSetPageAnnotationTransactions(aURI, aAnnotationObject); }, setLoadInSidebar: function placesTxn_setLoadInSidebar(aItemId, aLoadInSidebar) { var annoObj = { name: LOAD_IN_SIDEBAR_ANNO, type: Ci.nsIAnnotationService.TYPE_INT32, flags: 0, value: aLoadInSidebar, expires: Ci.nsIAnnotationService.EXPIRE_NEVER }; return this.setItemAnnotation(aItemId, annoObj); }, editItemDescription: function placesTxn_editItemDescription(aItemId, aDescription) { var annoObj = { name: DESCRIPTION_ANNO, type: Ci.nsIAnnotationService.TYPE_STRING, flags: 0, value: aDescription, expires: Ci.nsIAnnotationService.EXPIRE_NEVER }; return this.setItemAnnotation(aItemId, annoObj); }, editBookmarkKeyword: function placesTxn_editBookmarkKeyword(aItemId, aNewKeyword) { return new placesEditBookmarkKeywordTransactions(aItemId, aNewKeyword); }, editBookmarkPostData: function placesTxn_editBookmarkPostdata(aItemId, aPostData) { return new placesEditBookmarkPostDataTransactions(aItemId, aPostData); }, editLivemarkSiteURI: function placesTxn_editLivemarkSiteURI(aLivemarkId, aSiteURI) { return new placesEditLivemarkSiteURITransactions(aLivemarkId, aSiteURI); }, editLivemarkFeedURI: function placesTxn_editLivemarkFeedURI(aLivemarkId, aFeedURI) { return new placesEditLivemarkFeedURITransactions(aLivemarkId, aFeedURI); }, editBookmarkMicrosummary: function placesTxn_editBookmarkMicrosummary(aItemId, aNewMicrosummary) { return new placesEditBookmarkMicrosummaryTransactions(aItemId, aNewMicrosummary); }, editItemDateAdded: function placesTxn_editItemDateAdded(aItemId, aNewDateAdded) { return new placesEditItemDateAddedTransaction(aItemId, aNewDateAdded); }, editItemLastModified: function placesTxn_editItemLastModified(aItemId, aNewLastModified) { return new placesEditItemLastModifiedTransaction(aItemId, aNewLastModified); }, sortFolderByName: function placesTxn_sortFolderByName(aFolderId) { return new placesSortFolderByNameTransactions(aFolderId); }, tagURI: function placesTxn_tagURI(aURI, aTags) { return new placesTagURITransaction(aURI, aTags); }, untagURI: function placesTxn_untagURI(aURI, aTags) { return new placesUntagURITransaction(aURI, aTags); }, // Update commands in the undo group of the active window // commands in inactive windows will are updated on-focus _updateCommands: function placesTxn__updateCommands() { var wm = Cc["@mozilla.org/appshell/window-mediator;1"]. getService(Ci.nsIWindowMediator); var win = wm.getMostRecentWindow(null); if (win) win.updateCommands("undo"); }, // nsITransactionManager beginBatch: function() { this.mTransactionManager.beginBatch(); // A no-op transaction is pushed to the stack, in order to make safe and // easy to implement "Undo" an unknown number of transactions (including 0), // "above" beginBatch and endBatch. Otherwise,implementing Undo that way // head to dataloss: for example, if no changes were done in the // edit-item panel, the last transaction on the undo stack would be the // initial createItem transaction, or even worse, the batched editing of // some other item. // DO NOT MOVE this to the window scope, that would leak (bug 490068)! this.doTransaction({ doTransaction: function() { }, undoTransaction: function() { }, redoTransaction: function() { }, isTransient: false, merge: function() { return false; } }); }, endBatch: function() this.mTransactionManager.endBatch(), doTransaction: function placesTxn_doTransaction(txn) { this.mTransactionManager.doTransaction(txn); this._updateCommands(); }, undoTransaction: function placesTxn_undoTransaction() { this.mTransactionManager.undoTransaction(); this._updateCommands(); }, redoTransaction: function placesTxn_redoTransaction() { this.mTransactionManager.redoTransaction(); this._updateCommands(); }, clear: function() this.mTransactionManager.clear(), get numberOfUndoItems() { return this.mTransactionManager.numberOfUndoItems; }, get numberOfRedoItems() { return this.mTransactionManager.numberOfRedoItems; }, get maxTransactionCount() { return this.mTransactionManager.maxTransactionCount; }, set maxTransactionCount(val) { return this.mTransactionManager.maxTransactionCount = val; }, peekUndoStack: function() this.mTransactionManager.peekUndoStack(), peekRedoStack: function() this.mTransactionManager.peekRedoStack(), getUndoStack: function() this.mTransactionManager.getUndoStack(), getRedoStack: function() this.mTransactionManager.getRedoStack(), AddListener: function(l) this.mTransactionManager.AddListener(l), RemoveListener: function(l) this.mTransactionManager.RemoveListener(l) }; /** * Method and utility stubs for Places Edit Transactions */ function placesBaseTransaction() { } placesBaseTransaction.prototype = { // for child-transactions get wrappedJSObject() { return this; }, // nsITransaction redoTransaction: function PBT_redoTransaction() { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, get isTransient() { return false; }, merge: function mergeFunc(transaction) { return false; }, // nsISupports QueryInterface: XPCOMUtils.generateQI([Ci.nsITransaction]), }; function placesAggregateTransactions(name, transactions) { this._transactions = transactions; this._name = name; this.container = -1; this.redoTransaction = this.doTransaction; // Check child transactions number. We will batch if we have more than // MIN_TRANSACTIONS_FOR_BATCH total number of transactions. var countTransactions = function(aTransactions, aTxnCount) { for (let i = 0; i < aTransactions.length && aTxnCount < MIN_TRANSACTIONS_FOR_BATCH; i++, aTxnCount++) { let txn = aTransactions[i].wrappedJSObject; if (txn && txn.childTransactions && txn.childTransactions.length) aTxnCount = countTransactions(txn.childTransactions, aTxnCount); } return aTxnCount; } var txnCount = countTransactions(transactions, 0); this._useBatch = txnCount >= MIN_TRANSACTIONS_FOR_BATCH; } placesAggregateTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PAT_doTransaction() { if (this._useBatch) { var callback = { _self: this, runBatched: function() { this._self.commit(false); } }; PlacesUtils.bookmarks.runInBatchMode(callback, null); } else this.commit(false); }, undoTransaction: function PAT_undoTransaction() { if (this._useBatch) { var callback = { _self: this, runBatched: function() { this._self.commit(true); } }; PlacesUtils.bookmarks.runInBatchMode(callback, null); } else this.commit(true); }, commit: function PAT_commit(aUndo) { // Use a copy of the transactions array, so we won't reverse the original // one on undoing. var transactions = this._transactions.slice(0); if (aUndo) transactions.reverse(); for (var i = 0; i < transactions.length; i++) { var txn = transactions[i]; if (this.container > -1) txn.wrappedJSObject.container = this.container; if (aUndo) txn.undoTransaction(); else txn.doTransaction(); } } }; function placesCreateFolderTransactions(aName, aContainer, aIndex, aAnnotations, aChildItemsTransactions) { this._name = aName; this._container = aContainer; this._index = typeof(aIndex) == "number" ? aIndex : -1; this._annotations = aAnnotations; this._id = null; this.childTransactions = aChildItemsTransactions || []; this.redoTransaction = this.doTransaction; } placesCreateFolderTransactions.prototype = { __proto__: placesBaseTransaction.prototype, // childItemsTransaction support get container() { return this._container; }, set container(val) { return this._container = val; }, doTransaction: function PCFT_doTransaction() { this._id = PlacesUtils.bookmarks.createFolder(this._container, this._name, this._index); if (this._annotations && this._annotations.length > 0) PlacesUtils.setAnnotationsForItem(this._id, this._annotations); if (this.childTransactions.length) { // Set the new container id into child transactions. for (var i = 0; i < this.childTransactions.length; ++i) { this.childTransactions[i].wrappedJSObject.container = this._id; } let aggregateTxn = new placesAggregateTransactions("Create folder childTxn", this.childTransactions); aggregateTxn.doTransaction(); } if (this._GUID) PlacesUtils.bookmarks.setItemGUID(this._id, this._GUID); }, undoTransaction: function PCFT_undoTransaction() { if (this.childTransactions.length) { let aggregateTxn = new placesAggregateTransactions("Create folder childTxn", this.childTransactions); aggregateTxn.undoTransaction(); } // If a GUID exists for this item, preserve it before removing the item. if (PlacesUtils.annotations.itemHasAnnotation(this._id, GUID_ANNO)) this._GUID = PlacesUtils.bookmarks.getItemGUID(this._id); // Remove item only after all child transactions have been reverted. PlacesUtils.bookmarks.removeItem(this._id); } }; function placesCreateItemTransactions(aURI, aContainer, aIndex, aTitle, aKeyword, aAnnotations, aChildTransactions) { this._uri = aURI; this._container = aContainer; this._index = typeof(aIndex) == "number" ? aIndex : -1; this._title = aTitle; this._keyword = aKeyword; this._annotations = aAnnotations; this.childTransactions = aChildTransactions || []; this.redoTransaction = this.doTransaction; } placesCreateItemTransactions.prototype = { __proto__: placesBaseTransaction.prototype, // childItemsTransactions support for the create-folder transaction get container() { return this._container; }, set container(val) { return this._container = val; }, doTransaction: function PCIT_doTransaction() { this._id = PlacesUtils.bookmarks.insertBookmark(this.container, this._uri, this._index, this._title); if (this._keyword) PlacesUtils.bookmarks.setKeywordForBookmark(this._id, this._keyword); if (this._annotations && this._annotations.length > 0) PlacesUtils.setAnnotationsForItem(this._id, this._annotations); if (this.childTransactions.length) { // Set the new item id into child transactions. for (var i = 0; i < this.childTransactions.length; ++i) { this.childTransactions[i].wrappedJSObject.id = this._id; } let aggregateTxn = new placesAggregateTransactions("Create item childTxn", this.childTransactions); aggregateTxn.doTransaction(); } if (this._GUID) PlacesUtils.bookmarks.setItemGUID(this._id, this._GUID); }, undoTransaction: function PCIT_undoTransaction() { if (this.childTransactions.length) { // Undo transactions should always be done in reverse order. let aggregateTxn = new placesAggregateTransactions("Create item childTxn", this.childTransactions); aggregateTxn.undoTransaction(); } // If a GUID exists for this item, preserve it before removing the item. if (PlacesUtils.annotations.itemHasAnnotation(this._id, GUID_ANNO)) this._GUID = PlacesUtils.bookmarks.getItemGUID(this._id); // Remove item only after all child transactions have been reverted. PlacesUtils.bookmarks.removeItem(this._id); } }; function placesCreateSeparatorTransactions(aContainer, aIndex) { this._container = aContainer; this._index = typeof(aIndex) == "number" ? aIndex : -1; this._id = null; this.redoTransaction = this.doTransaction; } placesCreateSeparatorTransactions.prototype = { __proto__: placesBaseTransaction.prototype, // childItemsTransaction support get container() { return this._container; }, set container(val) { return this._container = val; }, doTransaction: function PCST_doTransaction() { this._id = PlacesUtils.bookmarks .insertSeparator(this.container, this._index); if (this._GUID) PlacesUtils.bookmarks.setItemGUID(this._id, this._GUID); }, undoTransaction: function PCST_undoTransaction() { // If a GUID exists for this item, preserve it before removing the item. if (PlacesUtils.annotations.itemHasAnnotation(this._id, GUID_ANNO)) this._GUID = PlacesUtils.bookmarks.getItemGUID(this._id); PlacesUtils.bookmarks.removeItem(this._id); } }; function placesCreateLivemarkTransactions(aFeedURI, aSiteURI, aName, aContainer, aIndex, aAnnotations) { this.redoTransaction = this.doTransaction; this._feedURI = aFeedURI; this._siteURI = aSiteURI; this._name = aName; this._container = aContainer; this._index = typeof(aIndex) == "number" ? aIndex : -1; this._annotations = aAnnotations; } placesCreateLivemarkTransactions.prototype = { __proto__: placesBaseTransaction.prototype, // childItemsTransaction support get container() { return this._container; }, set container(val) { return this._container = val; }, doTransaction: function PCLT_doTransaction() { this._id = PlacesUtils.livemarks.createLivemark(this._container, this._name, this._siteURI, this._feedURI, this._index); if (this._annotations && this._annotations.length > 0) PlacesUtils.setAnnotationsForItem(this._id, this._annotations); if (this._GUID) PlacesUtils.bookmarks.setItemGUID(this._id, this._GUID); }, undoTransaction: function PCLT_undoTransaction() { // If a GUID exists for this item, preserve it before removing the item. if (PlacesUtils.annotations.itemHasAnnotation(this._id, GUID_ANNO)) this._GUID = PlacesUtils.bookmarks.getItemGUID(this._id); PlacesUtils.bookmarks.removeItem(this._id); } }; function placesRemoveLivemarkTransaction(aFolderId) { this.redoTransaction = this.doTransaction; this._id = aFolderId; this._title = PlacesUtils.bookmarks.getItemTitle(this._id);<|fim▁hole|> "livemark/siteURI", "livemark/expiration", "livemark/loadfailed", "livemark/loading"]; this._annotations = annos.filter(function(aValue, aIndex, aArray) { return annosToExclude.indexOf(aValue.name) == -1; }); this._feedURI = PlacesUtils.livemarks.getFeedURI(this._id); this._siteURI = PlacesUtils.livemarks.getSiteURI(this._id); this._dateAdded = PlacesUtils.bookmarks.getItemDateAdded(this._id); this._lastModified = PlacesUtils.bookmarks.getItemLastModified(this._id); } placesRemoveLivemarkTransaction.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PRLT_doTransaction() { this._index = PlacesUtils.bookmarks.getItemIndex(this._id); PlacesUtils.bookmarks.removeItem(this._id); }, undoTransaction: function PRLT_undoTransaction() { this._id = PlacesUtils.livemarks.createLivemark(this._container, this._title, this._siteURI, this._feedURI, this._index); PlacesUtils.bookmarks.setItemDateAdded(this._id, this._dateAdded); PlacesUtils.bookmarks.setItemLastModified(this._id, this._lastModified); // Restore annotations PlacesUtils.setAnnotationsForItem(this._id, this._annotations); } }; function placesMoveItemTransactions(aItemId, aNewContainer, aNewIndex) { this._id = aItemId; this._oldContainer = PlacesUtils.bookmarks.getFolderIdForItem(this._id); this._newContainer = aNewContainer; this._newIndex = aNewIndex; this.redoTransaction = this.doTransaction; } placesMoveItemTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PMIT_doTransaction() { this._oldIndex = PlacesUtils.bookmarks.getItemIndex(this._id); PlacesUtils.bookmarks.moveItem(this._id, this._newContainer, this._newIndex); this._undoIndex = PlacesUtils.bookmarks.getItemIndex(this._id); }, undoTransaction: function PMIT_undoTransaction() { // moving down in the same container takes in count removal of the item // so to revert positions we must move to oldIndex + 1 if (this._newContainer == this._oldContainer && this._oldIndex > this._undoIndex) PlacesUtils.bookmarks.moveItem(this._id, this._oldContainer, this._oldIndex + 1); else PlacesUtils.bookmarks.moveItem(this._id, this._oldContainer, this._oldIndex); } }; function placesRemoveItemTransaction(aItemId) { this.redoTransaction = this.doTransaction; this._id = aItemId; this._itemType = PlacesUtils.bookmarks.getItemType(this._id); if (this._itemType == Ci.nsINavBookmarksService.TYPE_FOLDER) { this.childTransactions = this._getFolderContentsTransactions(); // Remove this folder itself. let txn = PlacesUtils.bookmarks.getRemoveFolderTransaction(this._id); this.childTransactions.push(txn); } else if (this._itemType == Ci.nsINavBookmarksService.TYPE_BOOKMARK) { this._uri = PlacesUtils.bookmarks.getBookmarkURI(this._id); this._keyword = PlacesUtils.bookmarks.getKeywordForBookmark(this._id); } if (this._itemType != Ci.nsINavBookmarksService.TYPE_SEPARATOR) this._title = PlacesUtils.bookmarks.getItemTitle(this._id); this._oldContainer = PlacesUtils.bookmarks.getFolderIdForItem(this._id); this._annotations = PlacesUtils.getAnnotationsForItem(this._id); this._dateAdded = PlacesUtils.bookmarks.getItemDateAdded(this._id); this._lastModified = PlacesUtils.bookmarks.getItemLastModified(this._id); } placesRemoveItemTransaction.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PRIT_doTransaction() { this._oldIndex = PlacesUtils.bookmarks.getItemIndex(this._id); if (this._itemType == Ci.nsINavBookmarksService.TYPE_FOLDER) { let aggregateTxn = new placesAggregateTransactions("Remove item childTxn", this.childTransactions); aggregateTxn.doTransaction(); } else { PlacesUtils.bookmarks.removeItem(this._id); if (this._uri) { // if this was the last bookmark (excluding tag-items and livemark // children, see getMostRecentBookmarkForURI) for the bookmark's url, // remove the url from tag containers as well. if (PlacesUtils.getMostRecentBookmarkForURI(this._uri) == -1) { this._tags = PlacesUtils.tagging.getTagsForURI(this._uri, {}); PlacesUtils.tagging.untagURI(this._uri, this._tags); } } } }, undoTransaction: function PRIT_undoTransaction() { if (this._itemType == Ci.nsINavBookmarksService.TYPE_BOOKMARK) { this._id = PlacesUtils.bookmarks.insertBookmark(this._oldContainer, this._uri, this._oldIndex, this._title); if (this._tags && this._tags.length > 0) PlacesUtils.tagging.tagURI(this._uri, this._tags); if (this._keyword) PlacesUtils.bookmarks.setKeywordForBookmark(this._id, this._keyword); } else if (this._itemType == Ci.nsINavBookmarksService.TYPE_FOLDER) { let aggregateTxn = new placesAggregateTransactions("Remove item childTxn", this.childTransactions); aggregateTxn.undoTransaction(); } else // TYPE_SEPARATOR this._id = PlacesUtils.bookmarks.insertSeparator(this._oldContainer, this._oldIndex); if (this._annotations.length > 0) PlacesUtils.setAnnotationsForItem(this._id, this._annotations); PlacesUtils.bookmarks.setItemDateAdded(this._id, this._dateAdded); PlacesUtils.bookmarks.setItemLastModified(this._id, this._lastModified); }, /** * Returns a flat, ordered list of transactions for a depth-first recreation * of items within this folder. */ _getFolderContentsTransactions: function PRIT__getFolderContentsTransactions() { var transactions = []; var contents = PlacesUtils.getFolderContents(this._id, false, false).root; for (var i = 0; i < contents.childCount; ++i) { let txn = new placesRemoveItemTransaction(contents.getChild(i).itemId); transactions.push(txn); } contents.containerOpen = false; // Reverse transactions to preserve parent-child relationship. return transactions.reverse(); } }; function placesEditItemTitleTransactions(id, newTitle) { this._id = id; this._newTitle = newTitle; this._oldTitle = ""; this.redoTransaction = this.doTransaction; } placesEditItemTitleTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PEITT_doTransaction() { this._oldTitle = PlacesUtils.bookmarks.getItemTitle(this._id); PlacesUtils.bookmarks.setItemTitle(this._id, this._newTitle); }, undoTransaction: function PEITT_undoTransaction() { PlacesUtils.bookmarks.setItemTitle(this._id, this._oldTitle); } }; function placesEditBookmarkURITransactions(aBookmarkId, aNewURI) { this._id = aBookmarkId; this._newURI = aNewURI; this.redoTransaction = this.doTransaction; } placesEditBookmarkURITransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PEBUT_doTransaction() { this._oldURI = PlacesUtils.bookmarks.getBookmarkURI(this._id); PlacesUtils.bookmarks.changeBookmarkURI(this._id, this._newURI); // move tags from old URI to new URI this._tags = PlacesUtils.tagging.getTagsForURI(this._oldURI, {}); if (this._tags.length != 0) { // only untag the old URI if this is the only bookmark if (PlacesUtils.getBookmarksForURI(this._oldURI, {}).length == 0) PlacesUtils.tagging.untagURI(this._oldURI, this._tags); PlacesUtils.tagging.tagURI(this._newURI, this._tags); } }, undoTransaction: function PEBUT_undoTransaction() { PlacesUtils.bookmarks.changeBookmarkURI(this._id, this._oldURI); // move tags from new URI to old URI if (this._tags.length != 0) { // only untag the new URI if this is the only bookmark if (PlacesUtils.getBookmarksForURI(this._newURI, {}).length == 0) PlacesUtils.tagging.untagURI(this._newURI, this._tags); PlacesUtils.tagging.tagURI(this._oldURI, this._tags); } } }; function placesSetItemAnnotationTransactions(aItemId, aAnnotationObject) { this.id = aItemId; this._anno = aAnnotationObject; // create an empty old anno this._oldAnno = { name: this._anno.name, type: Ci.nsIAnnotationService.TYPE_STRING, flags: 0, value: null, expires: Ci.nsIAnnotationService.EXPIRE_NEVER }; this.redoTransaction = this.doTransaction; } placesSetItemAnnotationTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PSIAT_doTransaction() { // Since this can be used as a child transaction this.id will be known // only at this point, after the external caller has set it. if (PlacesUtils.annotations.itemHasAnnotation(this.id, this._anno.name)) { // Save the old annotation if it is set. var flags = {}, expires = {}, mimeType = {}, type = {}; PlacesUtils.annotations.getItemAnnotationInfo(this.id, this._anno.name, flags, expires, mimeType, type); this._oldAnno.flags = flags.value; this._oldAnno.expires = expires.value; this._oldAnno.mimeType = mimeType.value; this._oldAnno.type = type.value; this._oldAnno.value = PlacesUtils.annotations .getItemAnnotation(this.id, this._anno.name); } PlacesUtils.setAnnotationsForItem(this.id, [this._anno]); }, undoTransaction: function PSIAT_undoTransaction() { PlacesUtils.setAnnotationsForItem(this.id, [this._oldAnno]); } }; function placesSetPageAnnotationTransactions(aURI, aAnnotationObject) { this._uri = aURI; this._anno = aAnnotationObject; // create an empty old anno this._oldAnno = { name: this._anno.name, type: Ci.nsIAnnotationService.TYPE_STRING, flags: 0, value: null, expires: Ci.nsIAnnotationService.EXPIRE_NEVER }; if (PlacesUtils.annotations.pageHasAnnotation(this._uri, this._anno.name)) { // fill the old anno if it is set var flags = {}, expires = {}, mimeType = {}, type = {}; PlacesUtils.annotations.getPageAnnotationInfo(this._uri, this._anno.name, flags, expires, mimeType, type); this._oldAnno.flags = flags.value; this._oldAnno.expires = expires.value; this._oldAnno.mimeType = mimeType.value; this._oldAnno.type = type.value; this._oldAnno.value = PlacesUtils.annotations .getPageAnnotation(this._uri, this._anno.name); } this.redoTransaction = this.doTransaction; } placesSetPageAnnotationTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PSPAT_doTransaction() { PlacesUtils.setAnnotationsForURI(this._uri, [this._anno]); }, undoTransaction: function PSPAT_undoTransaction() { PlacesUtils.setAnnotationsForURI(this._uri, [this._oldAnno]); } }; function placesEditBookmarkKeywordTransactions(id, newKeyword) { this.id = id; this._newKeyword = newKeyword; this._oldKeyword = ""; this.redoTransaction = this.doTransaction; } placesEditBookmarkKeywordTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PEBKT_doTransaction() { this._oldKeyword = PlacesUtils.bookmarks.getKeywordForBookmark(this.id); PlacesUtils.bookmarks.setKeywordForBookmark(this.id, this._newKeyword); }, undoTransaction: function PEBKT_undoTransaction() { PlacesUtils.bookmarks.setKeywordForBookmark(this.id, this._oldKeyword); } }; function placesEditBookmarkPostDataTransactions(aItemId, aPostData) { this.id = aItemId; this._newPostData = aPostData; this._oldPostData = null; this.redoTransaction = this.doTransaction; } placesEditBookmarkPostDataTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PEUPDT_doTransaction() { this._oldPostData = PlacesUtils.getPostDataForBookmark(this.id); PlacesUtils.setPostDataForBookmark(this.id, this._newPostData); }, undoTransaction: function PEUPDT_undoTransaction() { PlacesUtils.setPostDataForBookmark(this.id, this._oldPostData); } }; function placesEditLivemarkSiteURITransactions(folderId, uri) { this._folderId = folderId; this._newURI = uri; this._oldURI = null; this.redoTransaction = this.doTransaction; } placesEditLivemarkSiteURITransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PELSUT_doTransaction() { this._oldURI = PlacesUtils.livemarks.getSiteURI(this._folderId); PlacesUtils.livemarks.setSiteURI(this._folderId, this._newURI); }, undoTransaction: function PELSUT_undoTransaction() { PlacesUtils.livemarks.setSiteURI(this._folderId, this._oldURI); } }; function placesEditLivemarkFeedURITransactions(folderId, uri) { this._folderId = folderId; this._newURI = uri; this._oldURI = null; this.redoTransaction = this.doTransaction; } placesEditLivemarkFeedURITransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PELFUT_doTransaction() { this._oldURI = PlacesUtils.livemarks.getFeedURI(this._folderId); PlacesUtils.livemarks.setFeedURI(this._folderId, this._newURI); PlacesUtils.livemarks.reloadLivemarkFolder(this._folderId); }, undoTransaction: function PELFUT_undoTransaction() { PlacesUtils.livemarks.setFeedURI(this._folderId, this._oldURI); PlacesUtils.livemarks.reloadLivemarkFolder(this._folderId); } }; function placesEditBookmarkMicrosummaryTransactions(aItemId, newMicrosummary) { this.id = aItemId; this._mss = Cc["@mozilla.org/microsummary/service;1"]. getService(Ci.nsIMicrosummaryService); this._newMicrosummary = newMicrosummary; this._oldMicrosummary = null; this.redoTransaction = this.doTransaction; } placesEditBookmarkMicrosummaryTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PEBMT_doTransaction() { this._oldMicrosummary = this._mss.getMicrosummary(this.id); if (this._newMicrosummary) this._mss.setMicrosummary(this.id, this._newMicrosummary); else this._mss.removeMicrosummary(this.id); }, undoTransaction: function PEBMT_undoTransaction() { if (this._oldMicrosummary) this._mss.setMicrosummary(this.id, this._oldMicrosummary); else this._mss.removeMicrosummary(this.id); } }; function placesEditItemDateAddedTransaction(id, newDateAdded) { this.id = id; this._newDateAdded = newDateAdded; this._oldDateAdded = null; this.redoTransaction = this.doTransaction; } placesEditItemDateAddedTransaction.prototype = { __proto__: placesBaseTransaction.prototype, // to support folders as well get container() { return this.id; }, set container(val) { return this.id = val; }, doTransaction: function PEIDA_doTransaction() { this._oldDateAdded = PlacesUtils.bookmarks.getItemDateAdded(this.id); PlacesUtils.bookmarks.setItemDateAdded(this.id, this._newDateAdded); }, undoTransaction: function PEIDA_undoTransaction() { PlacesUtils.bookmarks.setItemDateAdded(this.id, this._oldDateAdded); } }; function placesEditItemLastModifiedTransaction(id, newLastModified) { this.id = id; this._newLastModified = newLastModified; this._oldLastModified = null; this.redoTransaction = this.doTransaction; } placesEditItemLastModifiedTransaction.prototype = { __proto__: placesBaseTransaction.prototype, // to support folders as well get container() { return this.id; }, set container(val) { return this.id = val; }, doTransaction: function PEILM_doTransaction() { this._oldLastModified = PlacesUtils.bookmarks.getItemLastModified(this.id); PlacesUtils.bookmarks.setItemLastModified(this.id, this._newLastModified); }, undoTransaction: function PEILM_undoTransaction() { PlacesUtils.bookmarks.setItemLastModified(this.id, this._oldLastModified); } }; function placesSortFolderByNameTransactions(aFolderId) { this._folderId = aFolderId; this._oldOrder = null, this.redoTransaction = this.doTransaction; } placesSortFolderByNameTransactions.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PSSFBN_doTransaction() { this._oldOrder = []; var contents = PlacesUtils.getFolderContents(this._folderId, false, false).root; var count = contents.childCount; // sort between separators var newOrder = []; var preSep = []; // temporary array for sorting each group of items var sortingMethod = function (a, b) { if (PlacesUtils.nodeIsContainer(a) && !PlacesUtils.nodeIsContainer(b)) return -1; if (!PlacesUtils.nodeIsContainer(a) && PlacesUtils.nodeIsContainer(b)) return 1; return a.title.localeCompare(b.title); }; for (var i = 0; i < count; ++i) { var item = contents.getChild(i); this._oldOrder[item.itemId] = i; if (PlacesUtils.nodeIsSeparator(item)) { if (preSep.length > 0) { preSep.sort(sortingMethod); newOrder = newOrder.concat(preSep); preSep.splice(0); } newOrder.push(item); } else preSep.push(item); } contents.containerOpen = false; if (preSep.length > 0) { preSep.sort(sortingMethod); newOrder = newOrder.concat(preSep); } // set the nex indexes var callback = { runBatched: function() { for (var i = 0; i < newOrder.length; ++i) { PlacesUtils.bookmarks.setItemIndex(newOrder[i].itemId, i); } } }; PlacesUtils.bookmarks.runInBatchMode(callback, null); }, undoTransaction: function PSSFBN_undoTransaction() { var callback = { _self: this, runBatched: function() { for (item in this._self._oldOrder) PlacesUtils.bookmarks.setItemIndex(item, this._self._oldOrder[item]); } }; PlacesUtils.bookmarks.runInBatchMode(callback, null); } }; function placesTagURITransaction(aURI, aTags) { this._uri = aURI; this._tags = aTags; this._unfiledItemId = -1; this.redoTransaction = this.doTransaction; } placesTagURITransaction.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PTU_doTransaction() { if (PlacesUtils.getMostRecentBookmarkForURI(this._uri) == -1) { // Force an unfiled bookmark first this._unfiledItemId = PlacesUtils.bookmarks .insertBookmark(PlacesUtils.unfiledBookmarksFolderId, this._uri, PlacesUtils.bookmarks.DEFAULT_INDEX, PlacesUtils.history.getPageTitle(this._uri)); if (this._GUID) PlacesUtils.bookmarks.setItemGUID(this._unfiledItemId, this._GUID); } PlacesUtils.tagging.tagURI(this._uri, this._tags); }, undoTransaction: function PTU_undoTransaction() { if (this._unfiledItemId != -1) { // If a GUID exists for this item, preserve it before removing the item. if (PlacesUtils.annotations.itemHasAnnotation(this._unfiledItemId, GUID_ANNO)) { this._GUID = PlacesUtils.bookmarks.getItemGUID(this._unfiledItemId); } PlacesUtils.bookmarks.removeItem(this._unfiledItemId); this._unfiledItemId = -1; } PlacesUtils.tagging.untagURI(this._uri, this._tags); } }; function placesUntagURITransaction(aURI, aTags) { this._uri = aURI; if (aTags) { // Within this transaction, we cannot rely on tags given by itemId // since the tag containers may be gone after we call untagURI. // Thus, we convert each tag given by its itemId to name. this._tags = aTags; for (var i=0; i < aTags.length; i++) { if (typeof(this._tags[i]) == "number") this._tags[i] = PlacesUtils.bookmarks.getItemTitle(this._tags[i]); } } else this._tags = PlacesUtils.tagging.getTagsForURI(this._uri, {}); this.redoTransaction = this.doTransaction; } placesUntagURITransaction.prototype = { __proto__: placesBaseTransaction.prototype, doTransaction: function PUTU_doTransaction() { PlacesUtils.tagging.untagURI(this._uri, this._tags); }, undoTransaction: function PUTU_undoTransaction() { PlacesUtils.tagging.tagURI(this._uri, this._tags); } }; function NSGetModule(aCompMgr, aFileSpec) { return XPCOMUtils.generateModule([placesTransactionsService]); }<|fim▁end|>
this._container = PlacesUtils.bookmarks.getFolderIdForItem(this._id); var annos = PlacesUtils.getAnnotationsForItem(this._id); // Exclude livemark service annotations, those will be recreated automatically var annosToExclude = ["livemark/feedURI",
<|file_name|>init-res-into-things.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Resources can't be copied, but storing into data structures counts // as a move unless the stored thing is used afterwards. struct r { i: @mut int, } struct Box { x: r } #[unsafe_destructor] impl Drop for r { fn drop(&self) { unsafe { *(self.i) = *(self.i) + 1; } } } fn r(i: @mut int) -> r { r { i: i } } fn test_box() { let i = @mut 0; { let a = @r(i); } assert_eq!(*i, 1); } fn test_rec() { let i = @mut 0; { let a = Box {x: r(i)}; } assert_eq!(*i, 1); } fn test_tag() { enum t { t0(r), } let i = @mut 0; { let a = t0(r(i)); } assert_eq!(*i, 1); } fn test_tup() { let i = @mut 0; { let a = (r(i), 0); } assert_eq!(*i, 1); }<|fim▁hole|>fn test_unique() { let i = @mut 0; { let a = ~r(i); } assert_eq!(*i, 1); } fn test_box_rec() { let i = @mut 0; { let a = @Box { x: r(i) }; } assert_eq!(*i, 1); } pub fn main() { test_box(); test_rec(); test_tag(); test_tup(); test_unique(); test_box_rec(); }<|fim▁end|>
<|file_name|>new-thread.controller.js<|end_file_name|><|fim▁begin|>(function(){ function newThreadCtrl($location, $state, MessageEditorService){ var vm = this; vm.getConstants = function(){ return MessageEditorService.pmConstants; }; vm.newThread = MessageEditorService.getThreadTemplate($location.search().boardId); vm.returnToBoard = function(){ var boardId = $location.search().boardId; $state.go('board',{boardId: boardId}); }; vm.previewThread = function(){ vm.previewThread = MessageEditorService.getThreadPreview(vm.newThread); vm.previewThread.$promise.then(function(data){ vm.preview = true; }); }; vm.postThread = function(){ MessageEditorService.saveThread(vm.newThread).$promise.then(function(data){ }); } vm.isOpen = false; }<|fim▁hole|> angular.module('zfgc.forum') .controller('newThreadCtrl', ['$location', '$state', 'MessageEditorService', newThreadCtrl]); })();<|fim▁end|>
<|file_name|>pit_shrp.cpp<|end_file_name|><|fim▁begin|>/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * 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 *<|fim▁hole|> * 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. * ------------------------------------------------------------------- */ /**************************************************************************************** Portions of this file are derived from the following 3GPP standard: 3GPP TS 26.173 ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec Available from http://www.3gpp.org (C) 2007, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC) Permission to distribute, modify and use this file under the standard license terms listed above has been obtained from the copyright holder. ****************************************************************************************/ /* ------------------------------------------------------------------------------ Filename: pit_shrp.cpp Date: 05/08/2007 ------------------------------------------------------------------------------ REVISION HISTORY Description: ------------------------------------------------------------------------------ INPUT AND OUTPUT DEFINITIONS int16 * x, in/out: impulse response (or algebraic code) int16 pit_lag, input : pitch lag int16 sharp, input : pitch sharpening factor (Q15) int16 L_subfr input : subframe size ------------------------------------------------------------------------------ FUNCTION DESCRIPTION Performs Pitch sharpening routine ------------------------------------------------------------------------------ REQUIREMENTS ------------------------------------------------------------------------------ REFERENCES ------------------------------------------------------------------------------ PSEUDO-CODE ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #include "pv_amr_wb_type_defs.h" #include "pvamrwbdecoder_basic_op.h" #include "pvamrwbdecoder_acelp.h" /*---------------------------------------------------------------------------- ; MACROS ; Define module specific macros here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; Include all pre-processor statements here. Include conditional ; compile variables also. ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL FUNCTION DEFINITIONS ; Function Prototype declaration ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL STORE/BUFFER/POINTER DEFINITIONS ; Variable declaration - defined here and used outside this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL FUNCTION REFERENCES ; Declare functions defined elsewhere and referenced in this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; FUNCTION CODE ----------------------------------------------------------------------------*/ void Pit_shrp( int16 * x, /* in/out: impulse response (or algebraic code) */ int16 pit_lag, /* input : pitch lag */ int16 sharp, /* input : pitch sharpening factor (Q15) */ int16 L_subfr /* input : subframe size */ ) { int16 i; int32 L_tmp; for (i = pit_lag; i < L_subfr; i++) { L_tmp = mac_16by16_to_int32((int32)x[i] << 16, x[i - pit_lag], sharp); x[i] = amr_wb_round(L_tmp); } return; }<|fim▁end|>
* Unless required by applicable law or agreed to in writing, software
<|file_name|>file.go<|end_file_name|><|fim▁begin|>package build import "go/ast" func NewFile(pkg string, decl ...ast.Decl) *ast.File { return &ast.File{ Name: &ast.Ident{ Name: pkg, }, Decls: decl,<|fim▁hole|><|fim▁end|>
} }
<|file_name|>tree.js<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. cr.define('cr.ui', function() { // require cr.ui.define // require cr.ui.limitInputWidth /** * The number of pixels to indent per level. * @type {number} * @const */ var INDENT = 20; /** * Returns the computed style for an element. * @param {!Element} el The element to get the computed style for. * @return {!CSSStyleDeclaration} The computed style. */ function getComputedStyle(el) { return el.ownerDocument.defaultView.getComputedStyle(el); } /** * Helper function that finds the first ancestor tree item. * @param {!Element} el The element to start searching from. * @return {cr.ui.TreeItem} The found tree item or null if not found. */ function findTreeItem(el) { while (el && !(el instanceof TreeItem)) { el = el.parentNode; } return el; } /** * Creates a new tree element. * @param {Object=} opt_propertyBag Optional properties. * @constructor * @extends {HTMLElement} */ var Tree = cr.ui.define('tree'); Tree.prototype = { __proto__: HTMLElement.prototype, /** * Initializes the element. */ decorate: function() { // Make list focusable if (!this.hasAttribute('tabindex')) this.tabIndex = 0; this.addEventListener('click', this.handleClick); this.addEventListener('mousedown', this.handleMouseDown); this.addEventListener('dblclick', this.handleDblClick); this.addEventListener('keydown', this.handleKeyDown); }, /** * Returns the tree item that are children of this tree. */ get items() { return this.children; }, /** * Adds a tree item to the tree. * @param {!cr.ui.TreeItem} treeItem The item to add. */ add: function(treeItem) { this.addAt(treeItem, 0xffffffff); }, /** * Adds a tree item at the given index. * @param {!cr.ui.TreeItem} treeItem The item to add. * @param {number} index The index where we want to add the item. */ addAt: function(treeItem, index) { this.insertBefore(treeItem, this.children[index]); treeItem.setDepth_(this.depth + 1); }, /** * Removes a tree item child. * @param {!cr.ui.TreeItem} treeItem The tree item to remove. */ remove: function(treeItem) { this.removeChild(treeItem); }, /** * The depth of the node. This is 0 for the tree itself. * @type {number} */ get depth() { return 0; }, /** * Handles click events on the tree and forwards the event to the relevant * tree items as necesary. * @param {Event} e The click event object. */ handleClick: function(e) { var treeItem = findTreeItem(e.target); if (treeItem) treeItem.handleClick(e); }, handleMouseDown: function(e) { if (e.button == 2) // right this.handleClick(e); }, /** * Handles double click events on the tree. * @param {Event} e The dblclick event object. */ handleDblClick: function(e) { var treeItem = findTreeItem(e.target); if (treeItem) treeItem.expanded = !treeItem.expanded; }, /** * Handles keydown events on the tree and updates selection and exanding * of tree items. * @param {Event} e The click event object. */ handleKeyDown: function(e) { var itemToSelect; if (e.ctrlKey) return; var item = this.selectedItem; if (!item) return; var rtl = getComputedStyle(item).direction == 'rtl'; switch (e.keyIdentifier) { case 'Up': itemToSelect = item ? getPrevious(item) : this.items[this.items.length - 1]; break; case 'Down': itemToSelect = item ? getNext(item) : this.items[0]; break; case 'Left': case 'Right': // Don't let back/forward keyboard shortcuts be used. if (!cr.isMac && e.altKey || cr.isMac && e.metaKey) break; if (e.keyIdentifier == 'Left' && !rtl || e.keyIdentifier == 'Right' && rtl) { if (item.expanded) item.expanded = false; else itemToSelect = findTreeItem(item.parentNode); } else { if (!item.expanded) item.expanded = true; else itemToSelect = item.items[0]; } break; case 'Home': itemToSelect = this.items[0]; break; case 'End': itemToSelect = this.items[this.items.length - 1]; break; } if (itemToSelect) { itemToSelect.selected = true; e.preventDefault(); } }, /** * The selected tree item or null if none. * @type {cr.ui.TreeItem} */ get selectedItem() { return this.selectedItem_ || null; }, set selectedItem(item) { var oldSelectedItem = this.selectedItem_; if (oldSelectedItem != item) { // Set the selectedItem_ before deselecting the old item since we only // want one change when moving between items. this.selectedItem_ = item; if (oldSelectedItem) oldSelectedItem.selected = false; if (item) item.selected = true; cr.dispatchSimpleEvent(this, 'change'); } }, /** * @return {!ClientRect} The rect to use for the context menu. */ getRectForContextMenu: function() { // TODO(arv): Add trait support so we can share more code between trees // and lists. if (this.selectedItem) return this.selectedItem.rowElement.getBoundingClientRect(); return this.getBoundingClientRect(); } }; /** * Determines the visibility of icons next to the treeItem labels. If set to * 'hidden', no space is reserved for icons and no icons are displayed next * to treeItem labels. If set to 'parent', folder icons will be displayed * next to expandable parent nodes. If set to 'all' folder icons will be * displayed next to all nodes. Icons can be set using the treeItem's icon * property. */ cr.defineProperty(Tree, 'iconVisibility', cr.PropertyKind.ATTR); /** * This is used as a blueprint for new tree item elements. * @type {!HTMLElement} */ var treeItemProto = (function() { var treeItem = cr.doc.createElement('div'); treeItem.className = 'tree-item'; treeItem.innerHTML = '<div class=tree-row>' + '<span class=expand-icon></span>' + '<span class=tree-label></span>' + '</div>' + '<div class=tree-children></div>'; treeItem.setAttribute('role', 'treeitem'); return treeItem; })(); /** * Creates a new tree item. * @param {Object=} opt_propertyBag Optional properties. * @constructor * @extends {HTMLElement} */ var TreeItem = cr.ui.define(function() { return treeItemProto.cloneNode(true); }); TreeItem.prototype = { __proto__: HTMLElement.prototype, /** * Initializes the element. */ decorate: function() { }, /** * The tree items children. */ get items() { return this.lastElementChild.children; }, /** * The depth of the tree item. * @type {number} */ depth_: 0, get depth() { return this.depth_; }, /** * Sets the depth. * @param {number} depth The new depth. * @private */ setDepth_: function(depth) { if (depth != this.depth_) { this.rowElement.style.WebkitPaddingStart = Math.max(0, depth - 1) * INDENT + 'px'; this.depth_ = depth; var items = this.items; for (var i = 0, item; item = items[i]; i++) { item.setDepth_(depth + 1); } } }, /** * Adds a tree item as a child. * @param {!cr.ui.TreeItem} child The child to add. */ add: function(child) { this.addAt(child, 0xffffffff); }, /** * Adds a tree item as a child at a given index. * @param {!cr.ui.TreeItem} child The child to add. * @param {number} index The index where to add the child. */ addAt: function(child, index) { this.lastElementChild.insertBefore(child, this.items[index]); if (this.items.length == 1) this.hasChildren = true; child.setDepth_(this.depth + 1); }, /** * Removes a child. * @param {!cr.ui.TreeItem} child The tree item child to remove. */ remove: function(child) { // If we removed the selected item we should become selected. var tree = this.tree; var selectedItem = tree.selectedItem; if (selectedItem && child.contains(selectedItem)) this.selected = true; this.lastElementChild.removeChild(child); if (this.items.length == 0) this.hasChildren = false; }, /** * The parent tree item. * @type {!cr.ui.Tree|cr.ui.TreeItem} */ get parentItem() { var p = this.parentNode; while (p && !(p instanceof TreeItem) && !(p instanceof Tree)) { p = p.parentNode; } return p; }, /** * The tree that the tree item belongs to or null of no added to a tree. * @type {cr.ui.Tree} */ get tree() { var t = this.parentItem; while (t && !(t instanceof Tree)) { t = t.parentItem; } return t; }, /** * Whether the tree item is expanded or not. * @type {boolean} */ get expanded() { return this.hasAttribute('expanded'); }, set expanded(b) { if (this.expanded == b) return; var treeChildren = this.lastElementChild; if (b) { if (this.mayHaveChildren_) { this.setAttribute('expanded', ''); treeChildren.setAttribute('expanded', ''); cr.dispatchSimpleEvent(this, 'expand', true); this.scrollIntoViewIfNeeded(false); } } else { var tree = this.tree; if (tree && !this.selected) { var oldSelected = tree.selectedItem; if (oldSelected && this.contains(oldSelected)) this.selected = true; } this.removeAttribute('expanded'); treeChildren.removeAttribute('expanded'); cr.dispatchSimpleEvent(this, 'collapse', true); } }, /** * Expands all parent items. */ reveal: function() { var pi = this.parentItem; while (pi && !(pi instanceof Tree)) { pi.expanded = true; pi = pi.parentItem; } }, /** * The element representing the row that gets highlighted. * @type {!HTMLElement} */ get rowElement() { return this.firstElementChild; }, /** * The element containing the label text and the icon. * @type {!HTMLElement} */ get labelElement() { return this.firstElementChild.lastElementChild; }, /** * The label text. * @type {string} */ get label() { return this.labelElement.textContent; }, set label(s) { this.labelElement.textContent = s; }, /** * The URL for the icon. * @type {string} */ get icon() {<|fim▁hole|> }, /** * Whether the tree item is selected or not. * @type {boolean} */ get selected() { return this.hasAttribute('selected'); }, set selected(b) { if (this.selected == b) return; var rowItem = this.firstElementChild; var tree = this.tree; if (b) { this.setAttribute('selected', ''); rowItem.setAttribute('selected', ''); this.reveal(); this.labelElement.scrollIntoViewIfNeeded(false); if (tree) tree.selectedItem = this; } else { this.removeAttribute('selected'); rowItem.removeAttribute('selected'); if (tree && tree.selectedItem == this) tree.selectedItem = null; } }, /** * Whether the tree item has children. * @type {boolean} */ get mayHaveChildren_() { return this.hasAttribute('may-have-children'); }, set mayHaveChildren_(b) { var rowItem = this.firstElementChild; if (b) { this.setAttribute('may-have-children', ''); rowItem.setAttribute('may-have-children', ''); } else { this.removeAttribute('may-have-children'); rowItem.removeAttribute('may-have-children'); } }, /** * Whether the tree item has children. * @type {boolean} */ get hasChildren() { return !!this.items[0]; }, /** * Whether the tree item has children. * @type {boolean} */ set hasChildren(b) { var rowItem = this.firstElementChild; this.setAttribute('has-children', b); rowItem.setAttribute('has-children', b); if (b) this.mayHaveChildren_ = true; }, /** * Called when the user clicks on a tree item. This is forwarded from the * cr.ui.Tree. * @param {Event} e The click event. */ handleClick: function(e) { if (e.target.className == 'expand-icon') this.expanded = !this.expanded; else this.selected = true; }, /** * Makes the tree item user editable. If the user renamed the item a * bubbling {@code rename} event is fired. * @type {boolean} */ set editing(editing) { var oldEditing = this.editing; if (editing == oldEditing) return; var self = this; var labelEl = this.labelElement; var text = this.label; var input; // Handles enter and escape which trigger reset and commit respectively. function handleKeydown(e) { // Make sure that the tree does not handle the key. e.stopPropagation(); // Calling tree.focus blurs the input which will make the tree item // non editable. switch (e.keyIdentifier) { case 'U+001B': // Esc input.value = text; // fall through case 'Enter': self.tree.focus(); } } function stopPropagation(e) { e.stopPropagation(); } if (editing) { this.selected = true; this.setAttribute('editing', ''); this.draggable = false; // We create an input[type=text] and copy over the label value. When // the input loses focus we set editing to false again. input = this.ownerDocument.createElement('input'); input.value = text; if (labelEl.firstChild) labelEl.replaceChild(input, labelEl.firstChild); else labelEl.appendChild(input); input.addEventListener('keydown', handleKeydown); input.addEventListener('blur', (function() { this.editing = false; }).bind(this)); // Make sure that double clicks do not expand and collapse the tree // item. var eventsToStop = ['mousedown', 'mouseup', 'contextmenu', 'dblclick']; eventsToStop.forEach(function(type) { input.addEventListener(type, stopPropagation); }); // Wait for the input element to recieve focus before sizing it. var rowElement = this.rowElement; function onFocus() { input.removeEventListener('focus', onFocus); // 20 = the padding and border of the tree-row cr.ui.limitInputWidth(input, rowElement, 100); } input.addEventListener('focus', onFocus); input.focus(); input.select(); this.oldLabel_ = text; } else { this.removeAttribute('editing'); this.draggable = true; input = labelEl.firstChild; var value = input.value; if (/^\s*$/.test(value)) { labelEl.textContent = this.oldLabel_; } else { labelEl.textContent = value; if (value != this.oldLabel_) { cr.dispatchSimpleEvent(this, 'rename', true); } } delete this.oldLabel_; } }, get editing() { return this.hasAttribute('editing'); } }; /** * Helper function that returns the next visible tree item. * @param {cr.ui.TreeItem} item The tree item. * @return {cr.ui.TreeItem} The found item or null. */ function getNext(item) { if (item.expanded) { var firstChild = item.items[0]; if (firstChild) { return firstChild; } } return getNextHelper(item); } /** * Another helper function that returns the next visible tree item. * @param {cr.ui.TreeItem} item The tree item. * @return {cr.ui.TreeItem} The found item or null. */ function getNextHelper(item) { if (!item) return null; var nextSibling = item.nextElementSibling; if (nextSibling) { return nextSibling; } return getNextHelper(item.parentItem); } /** * Helper function that returns the previous visible tree item. * @param {cr.ui.TreeItem} item The tree item. * @return {cr.ui.TreeItem} The found item or null. */ function getPrevious(item) { var previousSibling = item.previousElementSibling; return previousSibling ? getLastHelper(previousSibling) : item.parentItem; } /** * Helper function that returns the last visible tree item in the subtree. * @param {cr.ui.TreeItem} item The item to find the last visible item for. * @return {cr.ui.TreeItem} The found item or null. */ function getLastHelper(item) { if (!item) return null; if (item.expanded && item.hasChildren) { var lastChild = item.items[item.items.length - 1]; return getLastHelper(lastChild); } return item; } // Export return { Tree: Tree, TreeItem: TreeItem }; });<|fim▁end|>
return getComputedStyle(this.labelElement).backgroundImage.slice(4, -1); }, set icon(icon) { return this.labelElement.style.backgroundImage = url(icon);
<|file_name|>cases.py<|end_file_name|><|fim▁begin|>from aospy import Run am2_control = Run( name='am2_control', description=( 'Preindustrial control simulation.' ), data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/' 'SM2.1U_Control-1860_lm2_aie_rerun6.YIM/pp'), data_in_dur=5, data_in_start_date='0001-01-01', data_in_end_date='0080-12-31', default_date_range=('0021-01-01', '0080-12-31'), idealized=False ) am2_tropics = Run( name='am2_tropics', description=( 'Anthropogenic sulfate aerosol forcing only in the' ' Northern Hemisphere tropics (EQ to 30N)' ), data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/' 'SM2.1U_Control-1860_lm2_aie2_tropical_rerun6.YIM/pp'), data_in_dur=5, data_in_start_date='0001-01-01', data_in_end_date='0080-12-31', default_date_range=('0021-01-01', '0080-12-31'), idealized=False ) am2_extratropics = Run( name='am2_extratropics', description=( 'Anthropogenic sulfate aerosol forcing only in the' ' Northern Hemisphere extratropics (30N to Pole)' ), data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/' 'SM2.1U_Control-1860_lm2_aie2_extropical_rerun6.YIM/pp'), data_in_dur=5, data_in_start_date='0001-01-01', data_in_end_date='0080-12-31', default_date_range=('0021-01-01', '0080-12-31'), idealized=False ) am2_tropics_and_extratropics = Run( name='am2_tropics+extratropics', description=( 'Anthropogenic sulfate aerosol forcing everywhere' ), data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/' 'SM2.1U_Control-1860_lm2_aie2_rerun6.YIM/pp'), data_in_dur=5, data_in_start_date='0001-01-01', data_in_end_date='0080-12-31', default_date_range=('0021-01-01', '0080-12-31'), idealized=False ) # REYOI Runs - First year is 1982; we throw that out as spinup; # start analysis in 1983. am2_HadISST_control = Run( name='am2_HadISST_control', description=( '1981-2000 HadISST climatological annual cycle of SSTs and sea ' 'ice repeated annually, with PD atmospheric composition.' ), data_in_direc=('/archive/yim/siena_201203/m45_am2p14_1990/' 'gfdl.ncrc2-intel-prod/pp'), data_in_dur=16, data_in_start_date='1983-01-01', data_in_end_date='1998-12-31', default_date_range=('1983-01-01', '1998-12-31'), idealized=False ) am2_reyoi_control = Run( name='am2_reyoi_control', tags=['reyoi', 'cont'], description='PI atmos and Reynolds OI climatological SSTs', data_in_direc=('/archive/Spencer.Hill/am2/am2clim_reyoi/' 'gfdl.ncrc2-default-prod/pp'), data_in_dur=1, data_in_start_date='1982-01-01', data_in_end_date='1998-12-31', default_date_range=('1983-01-01', '1998-12-31'), idealized=False ) am2_reyoi_extratropics_full = Run( name='am2_reyoi_extratropics_full', description=( 'Full SST anomaly pattern applied to REYOI fixed SST climatology.'), data_in_direc=('/archive/Spencer.Clark/am2/' 'am2clim_reyoi_extratropics_full/' 'gfdl.ncrc2-default-prod/pp'), data_in_dur=17, data_in_start_date='1982-01-01', data_in_end_date='1998-12-31', default_date_range=('1983-01-01', '1998-12-31'), idealized=False ) am2_reyoi_extratropics_sp = Run( name='am2_reyoi_extratropics_sp', description=( 'Spatial Pattern SST anomaly pattern applied to' ' REYOI fixed SST climatology.'), data_in_direc=('/archive/Spencer.Clark/am2/' 'am2clim_reyoi_extratropics_sp/gfdl.ncrc2-default-prod/pp'), data_in_dur=17, data_in_start_date='1982-01-01', data_in_end_date='1998-12-31', default_date_range=('1983-01-01', '1998-12-31'), idealized=False ) am2_reyoi_tropics_sp_SI = Run( name='am2_reyoi_tropics_sp_SI', description=( 'Spatial Pattern SST anomaly pattern applied to REYOI fixed SST' ' climatology.'), data_in_direc=('/archive/Spencer.Clark/am2/'<|fim▁hole|> data_in_dur=17, data_in_start_date='1982-01-01', data_in_end_date='1998-12-31', default_date_range=('1983-01-01', '1998-12-31'), idealized=False ) am2_reyoi_tropics_full = Run( name='am2_reyoi_tropics_full', description=( 'Full SST anomaly pattern applied to REYOI fixed SST climatology.'), data_in_direc=('/archive/Spencer.Clark/am2/' 'am2clim_reyoi_tropics_full/gfdl.ncrc2-default-prod/pp'), data_in_dur=17, data_in_start_date='1982-01-01', data_in_end_date='1998-12-31', default_date_range=('1983-01-01', '1998-12-31'), idealized=False ) am2_reyoi_extratropics_sp_SI = Run( name='am2_reyoi_extratropics_sp_SI', description=( 'Spatial Pattern SST anomaly pattern applied to REYOI fixed' ' SST climatology. Fixed sea-ice.'), data_in_direc=('/archive/Spencer.Clark/am2/' 'am2clim_reyoi_extratropics_sp_SI/' 'gfdl.ncrc2-default-prod/pp'), data_in_dur=17, data_in_start_date='1982-01-01', data_in_end_date='1998-12-31', default_date_range=('1983-01-01', '1998-12-31'), idealized=False ) am2_reyoi_extratropics_u = Run( name='am2_reyoi_extratropics_u', description=( 'Uniform SST anomaly pattern applied to REYOI fixed SST climatology.'), data_in_direc=('/archive/Spencer.Clark/am2/' 'am2clim_reyoi_extratropics_u/gfdl.ncrc2-default-prod/pp'), data_in_dur=17, data_in_start_date='1982-01-01', data_in_end_date='1998-12-31', default_date_range=('1983-01-01', '1998-12-31'), idealized=False ) am2_reyoi_tropics_u = Run( name='am2_reyoi_tropics_u', description=( 'Uniform SST anomaly pattern applied to REYOI fixed SST climatology.'), data_in_direc=('/archive/Spencer.Clark/am2/' 'am2clim_reyoi_tropics_u/gfdl.ncrc2-default-prod/pp'), data_in_dur=17, data_in_start_date='1982-01-01', data_in_end_date='1998-12-31', default_date_range=('1983-01-01', '1998-12-31'), idealized=False )<|fim▁end|>
'am2clim_reyoi_tropics_sp_SI/gfdl.ncrc2-default-prod/pp'),
<|file_name|>webpack.config.js<|end_file_name|><|fim▁begin|>require('dotenv').config({ silent: true }); const webpack = require('webpack'); const appConfig = require('@flumens/webpack-config'); appConfig.entry = ['index.js']; const required = ['APP_SENTRY_KEY', 'APP_INDICIA_API_KEY']; const development = { APP_INDICIA_API_HOST: '', }; appConfig.plugins.unshift( new webpack.EnvironmentPlugin(required), new webpack.EnvironmentPlugin(development) ); const unusedFilesPlugin = appConfig.plugins.find(plugin => !!plugin.exclude); unusedFilesPlugin.exclude.push('*.tpl');<|fim▁hole|> test: /(\.eot)/, loader: 'file-loader', options: { name: 'fonts/[name].[ext]', }, }); module.exports = appConfig;<|fim▁end|>
appConfig.module.rules.push({
<|file_name|>IteratorValidatorCreator.java<|end_file_name|><|fim▁begin|>/* * 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.drill.exec.physical.impl.validate; import java.util.List; import org.apache.drill.common.exceptions.ExecutionSetupException; import org.apache.drill.exec.ExecConstants; import org.apache.drill.exec.ops.ExecutorFragmentContext; import org.apache.drill.exec.physical.config.IteratorValidator; import org.apache.drill.exec.physical.impl.BatchCreator; import org.apache.drill.exec.record.RecordBatch; <|fim▁hole|> static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(IteratorValidatorCreator.class); @Override public IteratorValidatorBatchIterator getBatch(ExecutorFragmentContext context, IteratorValidator config, List<RecordBatch> children) throws ExecutionSetupException { Preconditions.checkArgument(children.size() == 1); RecordBatch child = children.iterator().next(); IteratorValidatorBatchIterator iter = new IteratorValidatorBatchIterator(child, config.isRepeatable); boolean validateBatches = context.getOptions().getOption(ExecConstants.ENABLE_VECTOR_VALIDATOR) || context.getConfig().getBoolean(ExecConstants.ENABLE_VECTOR_VALIDATION); iter.enableBatchValidation(validateBatches); logger.trace("Iterator validation enabled for " + child.getClass().getSimpleName() + (validateBatches ? " with vector validation" : "")); return iter; } }<|fim▁end|>
import org.apache.drill.shaded.guava.com.google.common.base.Preconditions; public class IteratorValidatorCreator implements BatchCreator<IteratorValidator>{
<|file_name|>test_parsers.py<|end_file_name|><|fim▁begin|>"""Tests for parsers.py""" import asyncio import unittest import unittest.mock from aiohttp import errors from aiohttp import parsers class StreamParserTests(unittest.TestCase): DATA = b'line1\nline2\nline3\n' def setUp(self): self.lines_parser = parsers.LinesParser() self.loop = asyncio.new_event_loop() asyncio.set_event_loop(None) def tearDown(self): self.loop.close() def test_at_eof(self): proto = parsers.StreamParser() self.assertFalse(proto.at_eof()) proto.feed_eof() self.assertTrue(proto.at_eof()) def test_resume_stream(self): transp = unittest.mock.Mock() proto = parsers.StreamParser() proto.set_transport(transp) proto._paused = True proto._stream_paused = True proto.resume_stream() transp.resume_reading.assert_called_with() self.assertFalse(proto._paused) self.assertFalse(proto._stream_paused) def test_exception(self): stream = parsers.StreamParser() self.assertIsNone(stream.exception()) exc = ValueError() stream.set_exception(exc) self.assertIs(stream.exception(), exc) def test_exception_connection_error(self): stream = parsers.StreamParser() self.assertIsNone(stream.exception()) exc = ConnectionError() stream.set_exception(exc) self.assertIsNot(stream.exception(), exc) self.assertIsInstance(stream.exception(), RuntimeError) self.assertIs(stream.exception().__cause__, exc) self.assertIs(stream.exception().__context__, exc) def test_exception_waiter(self): stream = parsers.StreamParser() stream._parser = self.lines_parser buf = stream._output = parsers.FlowControlDataQueue( stream, loop=self.loop) exc = ValueError() stream.set_exception(exc) self.assertIs(buf.exception(), exc) def test_feed_data(self): stream = parsers.StreamParser() stream.feed_data(self.DATA) self.assertEqual(self.DATA, bytes(stream._buffer)) def test_feed_none_data(self): stream = parsers.StreamParser() stream.feed_data(None) self.assertEqual(b'', bytes(stream._buffer)) def test_feed_data_pause_reading(self): transp = unittest.mock.Mock() proto = parsers.StreamParser() proto.set_transport(transp) proto.feed_data(b'1' * (2 ** 16 * 3)) transp.pause_reading.assert_called_with() self.assertTrue(proto._paused) def test_feed_data_pause_reading_not_supported(self): transp = unittest.mock.Mock() proto = parsers.StreamParser() proto.set_transport(transp) transp.pause_reading.side_effect = NotImplementedError() proto.feed_data(b'1' * (2 ** 16 * 3)) self.assertIsNone(proto._transport) def test_set_parser_unset_prev(self): stream = parsers.StreamParser() stream.set_parser(self.lines_parser) unset = stream.unset_parser = unittest.mock.Mock() stream.set_parser(self.lines_parser) self.assertTrue(unset.called) def test_set_parser_exception(self): stream = parsers.StreamParser() exc = ValueError() stream.set_exception(exc) s = stream.set_parser(self.lines_parser) self.assertIs(s.exception(), exc) def test_set_parser_feed_existing(self): stream = parsers.StreamParser() stream.feed_data(b'line1') stream.feed_data(b'\r\nline2\r\ndata') s = stream.set_parser(self.lines_parser) self.assertEqual([bytearray(b'line1\r\n'), bytearray(b'line2\r\n')], list(s._buffer)) self.assertEqual(b'data', bytes(stream._buffer)) self.assertIsNotNone(stream._parser) stream.unset_parser() self.assertIsNone(stream._parser) self.assertEqual(b'data', bytes(stream._buffer)) self.assertTrue(s._eof) def test_set_parser_feed_existing_exc(self): def p(out, buf): yield from buf.read(1) raise ValueError() stream = parsers.StreamParser() stream.feed_data(b'line1') s = stream.set_parser(p) self.assertIsInstance(s.exception(), ValueError) def test_set_parser_feed_existing_eof(self): stream = parsers.StreamParser() stream.feed_data(b'line1') stream.feed_data(b'\r\nline2\r\ndata') stream.feed_eof() s = stream.set_parser(self.lines_parser) self.assertEqual([bytearray(b'line1\r\n'), bytearray(b'line2\r\n')], list(s._buffer)) self.assertEqual(b'data', bytes(stream._buffer)) self.assertIsNone(stream._parser) def test_set_parser_feed_existing_eof_exc(self): def p(out, buf): try: while True: yield # read chunk except parsers.EofStream: raise ValueError() stream = parsers.StreamParser() stream.feed_data(b'line1') stream.feed_eof() s = stream.set_parser(p) self.assertIsInstance(s.exception(), ValueError) def test_set_parser_feed_existing_eof_unhandled_eof(self): def p(out, buf): while True: yield # read chunk stream = parsers.StreamParser() stream.feed_data(b'line1') stream.feed_eof() s = stream.set_parser(p) self.assertFalse(s.is_eof()) self.assertIsInstance(s.exception(), RuntimeError) def test_set_parser_unset(self): stream = parsers.StreamParser(paused=False) s = stream.set_parser(self.lines_parser) stream.feed_data(b'line1\r\nline2\r\n') self.assertEqual( [bytearray(b'line1\r\n'), bytearray(b'line2\r\n')], list(s._buffer)) self.assertEqual(b'', bytes(stream._buffer)) stream.unset_parser() self.assertTrue(s._eof) self.assertEqual(b'', bytes(stream._buffer)) def test_set_parser_feed_existing_stop(self): def LinesParser(out, buf): try: out.feed_data((yield from buf.readuntil(b'\n'))) out.feed_data((yield from buf.readuntil(b'\n'))) finally: out.feed_eof() stream = parsers.StreamParser() stream.feed_data(b'line1') stream.feed_data(b'\r\nline2\r\ndata') s = stream.set_parser(LinesParser) self.assertEqual(b'line1\r\nline2\r\n', b''.join(s._buffer)) self.assertEqual(b'data', bytes(stream._buffer)) self.assertIsNone(stream._parser) self.assertTrue(s._eof) def test_feed_parser(self): stream = parsers.StreamParser(paused=False) s = stream.set_parser(self.lines_parser) stream.feed_data(b'line1') stream.feed_data(b'\r\nline2\r\ndata') self.assertEqual(b'data', bytes(stream._buffer)) stream.feed_eof() self.assertEqual([bytearray(b'line1\r\n'), bytearray(b'line2\r\n')], list(s._buffer)) self.assertEqual(b'data', bytes(stream._buffer)) self.assertTrue(s.is_eof()) def test_feed_parser_exc(self): def p(out, buf): yield # read chunk raise ValueError() stream = parsers.StreamParser(paused=False) s = stream.set_parser(p) stream.feed_data(b'line1') self.assertIsInstance(s.exception(), ValueError) self.assertEqual(b'', bytes(stream._buffer)) def test_feed_parser_stop(self): def p(out, buf): yield # chunk stream = parsers.StreamParser(paused=False) stream.set_parser(p) stream.feed_data(b'line1') self.assertIsNone(stream._parser) self.assertEqual(b'', bytes(stream._buffer)) def test_feed_eof_exc(self): def p(out, buf): try: while True: yield # read chunk except parsers.EofStream: raise ValueError() stream = parsers.StreamParser() s = stream.set_parser(p) stream.feed_data(b'line1') self.assertIsNone(s.exception()) stream.feed_eof() self.assertIsInstance(s.exception(), ValueError) def test_feed_eof_stop(self): def p(out, buf): try: while True: yield # read chunk except parsers.EofStream: out.feed_eof() stream = parsers.StreamParser() s = stream.set_parser(p) stream.feed_data(b'line1') stream.feed_eof() self.assertTrue(s._eof) def test_feed_eof_unhandled_eof(self): def p(out, buf): while True: yield # read chunk stream = parsers.StreamParser() s = stream.set_parser(p) stream.feed_data(b'line1') stream.feed_eof() self.assertFalse(s.is_eof()) self.assertIsInstance(s.exception(), RuntimeError) def test_feed_parser2(self): stream = parsers.StreamParser() s = stream.set_parser(self.lines_parser) stream.feed_data(b'line1\r\nline2\r\n') stream.feed_eof() self.assertEqual( [bytearray(b'line1\r\n'), bytearray(b'line2\r\n')], list(s._buffer)) self.assertEqual(b'', bytes(stream._buffer)) self.assertTrue(s._eof) def test_unset_parser_eof_exc(self): def p(out, buf): try: while True: yield # read chunk except parsers.EofStream: raise ValueError() stream = parsers.StreamParser() s = stream.set_parser(p) stream.feed_data(b'line1') stream.unset_parser() self.assertIsInstance(s.exception(), ValueError) self.assertIsNone(stream._parser) def test_unset_parser_eof_unhandled_eof(self): def p(out, buf): while True: yield # read chunk stream = parsers.StreamParser() s = stream.set_parser(p) stream.feed_data(b'line1') stream.unset_parser() self.assertIsInstance(s.exception(), RuntimeError) self.assertFalse(s.is_eof()) def test_unset_parser_stop(self): def p(out, buf): try: while True: yield # read chunk except parsers.EofStream: out.feed_eof() stream = parsers.StreamParser() s = stream.set_parser(p) stream.feed_data(b'line1') stream.unset_parser() self.assertTrue(s._eof) def test_eof_exc(self): def p(out, buf): while True: yield # read chunk class CustomEofErr(Exception): pass stream = parsers.StreamParser(eof_exc_class=CustomEofErr) s = stream.set_parser(p) stream.feed_eof() self.assertIsInstance(s.exception(), CustomEofErr) class StreamProtocolTests(unittest.TestCase): def test_connection_made(self): tr = unittest.mock.Mock() proto = parsers.StreamProtocol() self.assertIsNone(proto.transport) proto.connection_made(tr) self.assertIs(proto.transport, tr) def test_connection_lost(self): proto = parsers.StreamProtocol() proto.connection_made(unittest.mock.Mock()) proto.connection_lost(None) self.assertIsNone(proto.transport) self.assertIsNone(proto.writer) self.assertTrue(proto.reader._eof) def test_connection_lost_exc(self): proto = parsers.StreamProtocol() proto.connection_made(unittest.mock.Mock()) exc = ValueError() proto.connection_lost(exc) self.assertIs(proto.reader.exception(), exc) def test_data_received(self): proto = parsers.StreamProtocol() proto.connection_made(unittest.mock.Mock()) proto.reader = unittest.mock.Mock() proto.data_received(b'data') proto.reader.feed_data.assert_called_with(b'data') def test_drain_waiter(self): proto = parsers.StreamProtocol(loop=unittest.mock.Mock()) proto._paused = False self.assertEqual(proto._make_drain_waiter(), ()) proto._paused = True fut = proto._make_drain_waiter() self.assertIsInstance(fut, asyncio.Future) fut2 = proto._make_drain_waiter() self.assertIs(fut, fut2) class ParserBufferTests(unittest.TestCase): def setUp(self): self.stream = unittest.mock.Mock() self.loop = asyncio.new_event_loop() asyncio.set_event_loop(None) def tearDown(self): self.loop.close() def _make_one(self): return parsers.ParserBuffer() def test_feed_data(self): buf = self._make_one() buf.feed_data(b'') self.assertEqual(len(buf), 0) buf.feed_data(b'data') self.assertEqual(len(buf), 4) self.assertEqual(bytes(buf), b'data') def test_read_exc(self): buf = self._make_one() exc = ValueError() buf.set_exception(exc) self.assertIs(buf.exception(), exc) p = buf.read(3) next(p) self.assertRaises(ValueError, p.send, b'1') def test_read(self): buf = self._make_one() p = buf.read(3) next(p) p.send(b'1') try: p.send(b'234') except StopIteration as exc: res = exc.value self.assertEqual(res, b'123') self.assertEqual(b'4', bytes(buf)) def test_readsome(self): buf = self._make_one() p = buf.readsome(3) next(p) try: p.send(b'1') except StopIteration as exc: res = exc.value self.assertEqual(res, b'1') p = buf.readsome(2) next(p) try: p.send(b'234') except StopIteration as exc: res = exc.value self.assertEqual(res, b'23') self.assertEqual(b'4', bytes(buf)) def test_wait(self): buf = self._make_one() p = buf.wait(3) next(p) p.send(b'1') try: p.send(b'234') except StopIteration as exc: res = exc.value self.assertEqual(res, b'123') self.assertEqual(b'1234', bytes(buf)) def test_skip(self): buf = self._make_one() p = buf.skip(3) next(p) p.send(b'1') try: p.send(b'234') except StopIteration as exc: res = exc.value self.assertIsNone(res) self.assertEqual(b'4', bytes(buf)) def test_readuntil_limit(self): buf = self._make_one() p = buf.readuntil(b'\n', 4) next(p) p.send(b'1') p.send(b'234') self.assertRaises(errors.LineLimitExceededParserError, p.send, b'5') buf = parsers.ParserBuffer() p = buf.readuntil(b'\n', 4) next(p) self.assertRaises( errors.LineLimitExceededParserError, p.send, b'12345\n6') buf = parsers.ParserBuffer() p = buf.readuntil(b'\n', 4) next(p) self.assertRaises( errors.LineLimitExceededParserError, p.send, b'12345\n6') def test_readuntil(self): buf = self._make_one() p = buf.readuntil(b'\n', 4) next(p) p.send(b'123') try: p.send(b'\n456') except StopIteration as exc: res = exc.value self.assertEqual(res, b'123\n') self.assertEqual(b'456', bytes(buf)) def test_waituntil_limit(self): buf = self._make_one()<|fim▁hole|> p = buf.waituntil(b'\n', 4) next(p) p.send(b'1') p.send(b'234') self.assertRaises(errors.LineLimitExceededParserError, p.send, b'5') buf = parsers.ParserBuffer() p = buf.waituntil(b'\n', 4) next(p) self.assertRaises( errors.LineLimitExceededParserError, p.send, b'12345\n6') buf = parsers.ParserBuffer() p = buf.waituntil(b'\n', 4) next(p) self.assertRaises( errors.LineLimitExceededParserError, p.send, b'12345\n6') def test_waituntil(self): buf = self._make_one() p = buf.waituntil(b'\n', 4) next(p) p.send(b'123') try: p.send(b'\n456') except StopIteration as exc: res = exc.value self.assertEqual(res, b'123\n') self.assertEqual(b'123\n456', bytes(buf)) def test_skipuntil(self): buf = self._make_one() p = buf.skipuntil(b'\n') next(p) p.send(b'123') try: p.send(b'\n456\n') except StopIteration: pass self.assertEqual(b'456\n', bytes(buf)) p = buf.skipuntil(b'\n') try: next(p) except StopIteration: pass self.assertEqual(b'', bytes(buf)) def test_lines_parser(self): out = parsers.FlowControlDataQueue(self.stream, loop=self.loop) buf = self._make_one() p = parsers.LinesParser()(out, buf) next(p) for d in (b'line1', b'\r\n', b'lin', b'e2\r', b'\ndata'): p.send(d) self.assertEqual( [bytearray(b'line1\r\n'), bytearray(b'line2\r\n')], list(out._buffer)) try: p.throw(parsers.EofStream()) except StopIteration: pass self.assertEqual(bytes(buf), b'data') def test_chunks_parser(self): out = parsers.FlowControlDataQueue(self.stream, loop=self.loop) buf = self._make_one() p = parsers.ChunksParser(5)(out, buf) next(p) for d in (b'line1', b'lin', b'e2d', b'ata'): p.send(d) self.assertEqual( [bytearray(b'line1'), bytearray(b'line2')], list(out._buffer)) try: p.throw(parsers.EofStream()) except StopIteration: pass self.assertEqual(bytes(buf), b'data')<|fim▁end|>
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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<|fim▁hole|>// You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Blockchain params. mod genesis; mod seal; pub mod spec; pub use self::spec::*; pub use self::genesis::Genesis;<|fim▁end|>
// GNU General Public License for more details.
<|file_name|>resume.js<|end_file_name|><|fim▁begin|><|fim▁hole|> import '../styles/custom.css'; const Resume = () => ( <div className="resume-page"> <Head /> <iframe frameBorder="0" className="resume-frame" src="https://souvik.me/resume.pdf"></iframe> <style jsx>{` .resume-frame { width: 100%; height: 100%; min-height: 100%; display: block; } .resume-page { width: 100%; height: 100vh; } `}</style> </div> ); export default Resume;<|fim▁end|>
import React from 'react'; import Head from '../components/head';
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * This module provides a set of common Pipes. */ import {AsyncPipe} from './async_pipe'; import {LowerCasePipe, TitleCasePipe, UpperCasePipe} from './case_conversion_pipes'; import {DatePipe} from './date_pipe'; import {I18nPluralPipe} from './i18n_plural_pipe'; import {I18nSelectPipe} from './i18n_select_pipe'; import {JsonPipe} from './json_pipe'; import {KeyValue, KeyValuePipe} from './keyvalue_pipe'; import {CurrencyPipe, DecimalPipe, PercentPipe} from './number_pipe'; import {SlicePipe} from './slice_pipe'; export { AsyncPipe, CurrencyPipe, DatePipe, DecimalPipe, I18nPluralPipe, I18nSelectPipe, JsonPipe, KeyValue, KeyValuePipe, LowerCasePipe, PercentPipe, SlicePipe, TitleCasePipe, UpperCasePipe, }; /**<|fim▁hole|> UpperCasePipe, LowerCasePipe, JsonPipe, SlicePipe, DecimalPipe, PercentPipe, TitleCasePipe, CurrencyPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, KeyValuePipe, ];<|fim▁end|>
* A collection of Angular pipes that are likely to be used in each and every application. */ export const COMMON_PIPES = [ AsyncPipe,
<|file_name|>Interpreter.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import datetime import os #compsiteとcommandをあわせたような形 #ContextがhandlerでCommandが処理 class JobCommand(object): def execute(self, context): if context.getCurrentCommand() != 'begin': raise Exception('illegal command ' + str(context.getCurrentCommand())) command_list = CommandListCommand() command_list.execute(context.next()) class CommandListCommand(object): def execute(self, context): while (True): current_command = context.getCurrentCommand() if current_command is None: raise Exception('"end" not found ') elif current_command == 'end': break else: command = CommandCommand() command.execute(context) context.next() class CommandCommand(object): def execute(self, context): current_command = context.getCurrentCommand() if current_command == 'diskspace': free_size = 100000000.0 max_size = 210000000.0 ratio = free_size / max_size * 100 print( 'Disk Free : %dMB (%.2f%%)' % (free_size / 1024 / 1024, ratio)) elif current_command == 'date': print datetime.datetime.today().strftime("%Y/%m/%d") elif current_command == 'line': print '--------------------' else: raise Exception('invalid command [' + str(current_command) + ']') class Context(object): def __init__(self, command): self.commands = [] self.current_index = 0 self.max_index = 0 self.commands = command.strip().split() print self.commands self.max_index = len(self.commands) def next(self): self.current_index += 1 print self.current_index return self def getCurrentCommand(self): if self.current_index > len(self.commands): return None return self.commands[self.current_index].strip() <|fim▁hole|> try: job.execute(Context(command)) except Exception, e: print e.args if __name__ == '__main__': command = 'begin date line diskspace end' if command != '': execute(command)<|fim▁end|>
def execute(command): job = JobCommand()
<|file_name|>TDelay.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- from supriya.tools.ugentools.UGen import UGen class TDelay(UGen): r'''A trigger delay. :: >>> source = ugentools.Dust.kr() >>> tdelay = ugentools.TDelay.ar( ... duration=0.1, ... source=source, ... ) >>> tdelay TDelay.ar() ''' ### CLASS VARIABLES ### __documentation_section__ = 'Trigger Utility UGens' __slots__ = () _ordered_input_names = ( 'source', 'duration', ) _valid_calculation_rates = None ### INITIALIZER ### def __init__( self, calculation_rate=None, duration=0.1, source=None, ): UGen.__init__( self, calculation_rate=calculation_rate, duration=duration, source=source, ) ### PUBLIC METHODS ### @classmethod def ar( cls, duration=0.1,<|fim▁hole|> r'''Constructs an audio-rate TDelay. :: >>> source = ugentools.Dust.kr() >>> tdelay = ugentools.TDelay.ar( ... duration=0.1, ... source=source, ... ) >>> tdelay TDelay.ar() Returns ugen graph. ''' from supriya.tools import synthdeftools calculation_rate = synthdeftools.CalculationRate.AUDIO ugen = cls._new_expanded( calculation_rate=calculation_rate, duration=duration, source=source, ) return ugen @classmethod def kr( cls, duration=0.1, source=None, ): r'''Constructs a control-rate TDelay. :: >>> source = ugentools.Dust.kr() >>> tdelay = ugentools.TDelay.kr( ... duration=0.1, ... source=source, ... ) >>> tdelay TDelay.kr() Returns ugen graph. ''' from supriya.tools import synthdeftools calculation_rate = synthdeftools.CalculationRate.CONTROL ugen = cls._new_expanded( calculation_rate=calculation_rate, duration=duration, source=source, ) return ugen ### PUBLIC PROPERTIES ### @property def duration(self): r'''Gets `duration` input of TDelay. :: >>> source = ugentools.Dust.kr() >>> tdelay = ugentools.TDelay.ar( ... duration=0.1, ... source=source, ... ) >>> tdelay.duration 0.1 Returns ugen input. ''' index = self._ordered_input_names.index('duration') return self._inputs[index] @property def source(self): r'''Gets `source` input of TDelay. :: >>> source = ugentools.Dust.kr() >>> tdelay = ugentools.TDelay.ar( ... duration=0.1, ... source=source, ... ) >>> tdelay.source OutputProxy( source=Dust( calculation_rate=CalculationRate.CONTROL, density=0.0 ), output_index=0 ) Returns ugen input. ''' index = self._ordered_input_names.index('source') return self._inputs[index]<|fim▁end|>
source=None, ):
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin<|fim▁hole|>from cobra.core.loading import get_model<|fim▁end|>
<|file_name|>readjson.py<|end_file_name|><|fim▁begin|>import json<|fim▁hole|>data = json.load(json_data) pprint(data) json_data.close()<|fim▁end|>
from pprint import pprint json_data=open('jsonFormated') #json_data=open('jsonFile')
<|file_name|>filtergui.js<|end_file_name|><|fim▁begin|>define([], function () { return function (distributor) { var container = document.createElement("ul") container.classList.add("filters") var div = document.createElement("div") function render(el) { el.appendChild(div) } function filtersChanged(filters) { while (container.firstChild) container.removeChild(container.firstChild) filters.forEach( function (d) { var li = document.createElement("li") container.appendChild(li) d.render(li) var button = document.createElement("button") button.textContent = "" button.onclick = function () { distributor.removeFilter(d) } li.appendChild(button) }) if (container.parentNode === div && filters.length === 0) div.removeChild(container)<|fim▁hole|> else if (filters.length > 0) div.appendChild(container) } return { render: render, filtersChanged: filtersChanged } } })<|fim▁end|>
<|file_name|>mem.go<|end_file_name|><|fim▁begin|>package mem import ( "encoding/json" "github.com/theothertomelliott/gopsutil-nocgo/internal/common" ) var invoke common.Invoker func init() { invoke = common.Invoke{} } // Memory usage statistics. Total, Available and Used contain numbers of bytes // for human consumption. // // The other fields in this struct contain kernel specific values. type VirtualMemoryStat struct { // Total amount of RAM on this system Total uint64 `json:"total"` // RAM available for programs to allocate // // This value is computed from the kernel specific values. Available uint64 `json:"available"` // RAM used by programs // // This value is computed from the kernel specific values. Used uint64 `json:"used"` // Percentage of RAM used by programs // // This value is computed from the kernel specific values. UsedPercent float64 `json:"usedPercent"` // This is the kernel's notion of free memory; RAM chips whose bits nobody // cares about the value of right now. For a human consumable number, // Available is what you really want. Free uint64 `json:"free"` // OS X / BSD specific numbers: // http://www.macyourself.com/2010/02/17/what-is-free-wired-active-and-inactive-system-memory-ram/ Active uint64 `json:"active"` Inactive uint64 `json:"inactive"` Wired uint64 `json:"wired"` // Linux specific numbers // https://www.centos.org/docs/5/html/5.1/Deployment_Guide/s2-proc-meminfo.html // https://www.kernel.org/doc/Documentation/filesystems/proc.txt Buffers uint64 `json:"buffers"` Cached uint64 `json:"cached"` Writeback uint64 `json:"writeback"` Dirty uint64 `json:"dirty"` WritebackTmp uint64 `json:"writebacktmp"` Shared uint64 `json:"shared"` Slab uint64 `json:"slab"` PageTables uint64 `json:"pagetables"` SwapCached uint64 `json:"swapcached"` } type SwapMemoryStat struct { Total uint64 `json:"total"` Used uint64 `json:"used"` Free uint64 `json:"free"` UsedPercent float64 `json:"usedPercent"` Sin uint64 `json:"sin"` Sout uint64 `json:"sout"` }<|fim▁hole|>} func (m SwapMemoryStat) String() string { s, _ := json.Marshal(m) return string(s) }<|fim▁end|>
func (m VirtualMemoryStat) String() string { s, _ := json.Marshal(m) return string(s)
<|file_name|>MyPojoUser.java<|end_file_name|><|fim▁begin|>/******************************************************************************* * Copyright (c) 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.cdi.services.impl; import javax.enterprise.context.Dependent; /** * This class only needs to be here to make sure this is a BDA with a BeanManager<|fim▁hole|> public String getUser() { String s = "DefaultPojoUser"; return s; } }<|fim▁end|>
*/ @Dependent public class MyPojoUser {
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from datetime import datetime import math import pytest from flexget.utils import json from flexget.utils.tools import parse_filesize, split_title_year def compare_floats(float1, float2): eps = 0.0001 return math.fabs(float1 - float2) <= eps <|fim▁hole|> class TestJson(object): def test_json_encode_dt(self): date_str = '2016-03-11T17:12:17Z' dt = datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%SZ') encoded_dt = json.dumps(dt, encode_datetime=True) assert encoded_dt == '"%s"' % date_str def test_json_encode_dt_dict(self): date_str = '2016-03-11T17:12:17Z' dt = datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%SZ') date_obj = {'date': dt} encoded_dt = json.dumps(date_obj, encode_datetime=True) assert encoded_dt == '{"date": "%s"}' % date_str def test_json_decode_dt(self): date_str = '"2016-03-11T17:12:17Z"' dt = datetime.strptime(date_str, '"%Y-%m-%dT%H:%M:%SZ"') decoded_dt = json.loads(date_str, decode_datetime=True) assert dt == decoded_dt def test_json_decode_dt_obj(self): date_str = '"2016-03-11T17:12:17Z"' date_obj_str = '{"date": %s}' % date_str decoded_dt = json.loads(date_obj_str, decode_datetime=True) dt = datetime.strptime(date_str, '"%Y-%m-%dT%H:%M:%SZ"') assert decoded_dt == {'date': dt} class TestParseFilesize(object): def test_parse_filesize_no_space(self): size = '200KB' expected = 200 * 1000 / 1024 ** 2 assert compare_floats(parse_filesize(size), expected) def test_parse_filesize_space(self): size = '200.0 KB' expected = 200 * 1000 / 1024 ** 2 assert compare_floats(parse_filesize(size), expected) def test_parse_filesize_non_si(self): size = '1234 GB' expected = 1234 * 1000 ** 3 / 1024 ** 2 assert compare_floats(parse_filesize(size), expected) def test_parse_filesize_auto(self): size = '1234 GiB' expected = 1234 * 1024 ** 3 / 1024 ** 2 assert compare_floats(parse_filesize(size), expected) def test_parse_filesize_auto_mib(self): size = '1234 MiB' assert compare_floats(parse_filesize(size), 1234) def test_parse_filesize_ib_not_valid(self): with pytest.raises(ValueError): parse_filesize('100 ib') def test_parse_filesize_single_digit(self): size = '1 GiB' assert compare_floats(parse_filesize(size), 1024) def test_parse_filesize_separators(self): size = '1,234 GiB' assert parse_filesize(size) == 1263616 size = '1 234 567 MiB' assert parse_filesize(size) == 1234567 class TestSplitYearTitle(object): @pytest.mark.parametrize('title, expected_title, expected_year', [ ('The Matrix', 'The Matrix', None), ('The Matrix 1999', 'The Matrix', 1999), ('The Matrix (1999)', 'The Matrix', 1999), ('The Matrix - 1999', 'The Matrix -', 1999), ('The.Matrix.1999', 'The.Matrix.', 1999), ('The Human Centipede III (Final Sequence)', 'The Human Centipede III (Final Sequence)', None), ('The Human Centipede III (Final Sequence) (2015)', 'The Human Centipede III (Final Sequence)', 2015), ('2020', '2020', None) ]) def test_split_year_title(self, title, expected_title, expected_year): assert split_title_year(title) == (expected_title, expected_year)<|fim▁end|>
<|file_name|>webglrenderingcontext.rs<|end_file_name|><|fim▁begin|>/* 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/. */ use byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt}; use canvas_traits::{CanvasCommonMsg, CanvasMsg, byte_swap, multiply_u8_pixel}; use core::nonzero::NonZero; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::{self, WebGLContextAttributes}; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextMethods; use dom::bindings::codegen::UnionTypes::ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use dom::bindings::error::{Error, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, LayoutJS, MutNullableJS, Root}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::globalscope::GlobalScope; use dom::htmlcanvaselement::HTMLCanvasElement; use dom::htmlcanvaselement::utils as canvas_utils; use dom::node::{Node, NodeDamage, window_from_node}; use dom::webgl_validations::WebGLValidator; use dom::webgl_validations::tex_image_2d::{CommonTexImage2DValidator, CommonTexImage2DValidatorResult}; use dom::webgl_validations::tex_image_2d::{TexImage2DValidator, TexImage2DValidatorResult}; use dom::webgl_validations::types::{TexDataType, TexFormat, TexImageTarget}; use dom::webglactiveinfo::WebGLActiveInfo; use dom::webglbuffer::WebGLBuffer; use dom::webglcontextevent::WebGLContextEvent; use dom::webglframebuffer::WebGLFramebuffer; use dom::webglprogram::WebGLProgram; use dom::webglrenderbuffer::WebGLRenderbuffer; use dom::webglshader::WebGLShader; use dom::webgltexture::{TexParameterValue, WebGLTexture}; use dom::webgluniformlocation::WebGLUniformLocation; use dom::window::Window; use dom_struct::dom_struct; use euclid::size::Size2D; use ipc_channel::ipc::{self, IpcSender}; use js::conversions::ConversionBehavior; use js::jsapi::{JSContext, JSObject, Type, Rooted}; use js::jsval::{BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, UndefinedValue}; use js::typedarray::{TypedArray, TypedArrayElement, Float32, Int32}; use net_traits::image::base::PixelFormat; use net_traits::image_cache_thread::ImageResponse; use offscreen_gl_context::{GLContextAttributes, GLLimits}; use script_traits::ScriptMsg as ConstellationMsg; use std::cell::Cell; use webrender_traits; use webrender_traits::{WebGLCommand, WebGLError, WebGLFramebufferBindingRequest, WebGLParameter}; use webrender_traits::WebGLError::*; type ImagePixelResult = Result<(Vec<u8>, Size2D<i32>), ()>; pub const MAX_UNIFORM_AND_ATTRIBUTE_LEN: usize = 256; macro_rules! handle_potential_webgl_error { ($context:ident, $call:expr, $return_on_error:expr) => { match $call { Ok(ret) => ret, Err(error) => { $context.webgl_error(error); $return_on_error } } }; ($context:ident, $call:expr) => { handle_potential_webgl_error!($context, $call, ()); }; } // From the GLES 2.0.25 spec, page 85: // // "If a texture that is currently bound to one of the targets // TEXTURE_2D, or TEXTURE_CUBE_MAP is deleted, it is as though // BindTexture had been executed with the same target and texture // zero." // // and similar text occurs for other object types. macro_rules! handle_object_deletion { ($self_:expr, $binding:expr, $object:ident, $unbind_command:expr) => { if let Some(bound_object) = $binding.get() { if bound_object.id() == $object.id() { $binding.set(None); } if let Some(command) = $unbind_command { $self_.ipc_renderer .send(CanvasMsg::WebGL(command)) .unwrap(); } } }; } macro_rules! object_binding_to_js_or_null { ($cx: expr, $binding:expr) => { { rooted!(in($cx) let mut rval = NullValue()); if let Some(bound_object) = $binding.get() { bound_object.to_jsval($cx, rval.handle_mut()); } rval.get() } }; } fn has_invalid_blend_constants(arg1: u32, arg2: u32) -> bool { match (arg1, arg2) { (constants::CONSTANT_COLOR, constants::CONSTANT_ALPHA) => true, (constants::ONE_MINUS_CONSTANT_COLOR, constants::ONE_MINUS_CONSTANT_ALPHA) => true, (constants::ONE_MINUS_CONSTANT_COLOR, constants::CONSTANT_ALPHA) => true, (constants::CONSTANT_COLOR, constants::ONE_MINUS_CONSTANT_ALPHA) => true, (_, _) => false } } /// Set of bitflags for texture unpacking (texImage2d, etc...) bitflags! { #[derive(HeapSizeOf, JSTraceable)] flags TextureUnpacking: u8 { const FLIP_Y_AXIS = 0x01, const PREMULTIPLY_ALPHA = 0x02, const CONVERT_COLORSPACE = 0x04, } } #[dom_struct] pub struct WebGLRenderingContext { reflector_: Reflector, #[ignore_heap_size_of = "Defined in ipc-channel"] ipc_renderer: IpcSender<CanvasMsg>, #[ignore_heap_size_of = "Defined in offscreen_gl_context"] limits: GLLimits, canvas: JS<HTMLCanvasElement>, #[ignore_heap_size_of = "Defined in webrender_traits"] last_error: Cell<Option<WebGLError>>, texture_unpacking_settings: Cell<TextureUnpacking>, texture_unpacking_alignment: Cell<u32>, bound_framebuffer: MutNullableJS<WebGLFramebuffer>, bound_renderbuffer: MutNullableJS<WebGLRenderbuffer>, bound_texture_2d: MutNullableJS<WebGLTexture>, bound_texture_cube_map: MutNullableJS<WebGLTexture>, bound_buffer_array: MutNullableJS<WebGLBuffer>, bound_buffer_element_array: MutNullableJS<WebGLBuffer>, current_program: MutNullableJS<WebGLProgram>, #[ignore_heap_size_of = "Because it's small"] current_vertex_attrib_0: Cell<(f32, f32, f32, f32)>, #[ignore_heap_size_of = "Because it's small"] current_scissor: Cell<(i32, i32, i32, i32)>, #[ignore_heap_size_of = "Because it's small"] current_clear_color: Cell<(f32, f32, f32, f32)>, } impl WebGLRenderingContext { fn new_inherited(window: &Window, canvas: &HTMLCanvasElement, size: Size2D<i32>, attrs: GLContextAttributes) -> Result<WebGLRenderingContext, String> { let (sender, receiver) = ipc::channel().unwrap(); let constellation_chan = window.upcast::<GlobalScope>().constellation_chan(); constellation_chan.send(ConstellationMsg::CreateWebGLPaintThread(size, attrs, sender)) .unwrap(); let result = receiver.recv().unwrap(); result.map(|(ipc_renderer, context_limits)| { WebGLRenderingContext { reflector_: Reflector::new(), ipc_renderer: ipc_renderer, limits: context_limits, canvas: JS::from_ref(canvas), last_error: Cell::new(None), texture_unpacking_settings: Cell::new(CONVERT_COLORSPACE), texture_unpacking_alignment: Cell::new(4), bound_framebuffer: MutNullableJS::new(None), bound_texture_2d: MutNullableJS::new(None), bound_texture_cube_map: MutNullableJS::new(None), bound_buffer_array: MutNullableJS::new(None), bound_buffer_element_array: MutNullableJS::new(None), bound_renderbuffer: MutNullableJS::new(None), current_program: MutNullableJS::new(None), current_vertex_attrib_0: Cell::new((0f32, 0f32, 0f32, 1f32)), current_scissor: Cell::new((0, 0, size.width, size.height)), current_clear_color: Cell::new((0.0, 0.0, 0.0, 0.0)) } }) } #[allow(unrooted_must_root)] pub fn new(window: &Window, canvas: &HTMLCanvasElement, size: Size2D<i32>, attrs: GLContextAttributes) -> Option<Root<WebGLRenderingContext>> { match WebGLRenderingContext::new_inherited(window, canvas, size, attrs) { Ok(ctx) => Some(reflect_dom_object(box ctx, window, WebGLRenderingContextBinding::Wrap)), Err(msg) => { error!("Couldn't create WebGLRenderingContext: {}", msg); let event = WebGLContextEvent::new(window, atom!("webglcontextcreationerror"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable, DOMString::from(msg)); event.upcast::<Event>().fire(canvas.upcast()); None } } } pub fn limits(&self) -> &GLLimits { &self.limits } pub fn bound_texture_for_target(&self, target: &TexImageTarget) -> Option<Root<WebGLTexture>> { match *target { TexImageTarget::Texture2D => self.bound_texture_2d.get(), TexImageTarget::CubeMapPositiveX | TexImageTarget::CubeMapNegativeX | TexImageTarget::CubeMapPositiveY | TexImageTarget::CubeMapNegativeY | TexImageTarget::CubeMapPositiveZ | TexImageTarget::CubeMapNegativeZ => self.bound_texture_cube_map.get(), } } pub fn recreate(&self, size: Size2D<i32>) { self.ipc_renderer.send(CanvasMsg::Common(CanvasCommonMsg::Recreate(size))).unwrap(); // ClearColor needs to be restored because after a resize the GLContext is recreated // and the framebuffer is cleared using the default black transparent color. let color = self.current_clear_color.get(); self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::ClearColor(color.0, color.1, color.2, color.3))) .unwrap(); // WebGL Spec: Scissor rect must not change if the canvas is resized. // See: webgl/conformance-1.0.3/conformance/rendering/gl-scissor-canvas-dimensions.html // NativeContext handling library changes the scissor after a resize, so we need to reset the // default scissor when the canvas was created or the last scissor that the user set. let rect = self.current_scissor.get(); self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Scissor(rect.0, rect.1, rect.2, rect.3))) .unwrap() } pub fn ipc_renderer(&self) -> IpcSender<CanvasMsg> { self.ipc_renderer.clone() } pub fn webgl_error(&self, err: WebGLError) { // TODO(emilio): Add useful debug messages to this warn!("WebGL error: {:?}, previous error was {:?}", err, self.last_error.get()); // If an error has been detected no further errors must be // recorded until `getError` has been called if self.last_error.get().is_none() { self.last_error.set(Some(err)); } } // Helper function for validating framebuffer completeness in // calls touching the framebuffer. From the GLES 2.0.25 spec, // page 119: // // "Effects of Framebuffer Completeness on Framebuffer // Operations // // If the currently bound framebuffer is not framebuffer // complete, then it is an error to attempt to use the // framebuffer for writing or reading. This means that // rendering commands such as DrawArrays and DrawElements, as // well as commands that read the framebuffer such as // ReadPixels and CopyTexSubImage, will generate the error // INVALID_FRAMEBUFFER_OPERATION if called while the // framebuffer is not framebuffer complete." // // The WebGL spec mentions a couple more operations that trigger // this: clear() and getParameter(IMPLEMENTATION_COLOR_READ_*). fn validate_framebuffer_complete(&self) -> bool { match self.bound_framebuffer.get() { Some(fb) => match fb.check_status() { constants::FRAMEBUFFER_COMPLETE => return true, _ => { self.webgl_error(InvalidFramebufferOperation); return false; } }, // The default framebuffer is always complete. None => return true, } } fn tex_parameter(&self, target: u32, name: u32, value: TexParameterValue) { let texture = match target { constants::TEXTURE_2D => self.bound_texture_2d.get(), constants::TEXTURE_CUBE_MAP => self.bound_texture_cube_map.get(), _ => return self.webgl_error(InvalidEnum), }; if let Some(texture) = texture { handle_potential_webgl_error!(self, texture.tex_parameter(target, name, value)); } else { self.webgl_error(InvalidOperation) } } fn mark_as_dirty(&self) { self.canvas.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage); } fn vertex_attrib(&self, indx: u32, x: f32, y: f32, z: f32, w: f32) { if indx > self.limits.max_vertex_attribs { return self.webgl_error(InvalidValue); } if indx == 0 { self.current_vertex_attrib_0.set((x, y, z, w)) } self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::VertexAttrib(indx, x, y, z, w))) .unwrap(); } fn get_current_framebuffer_size(&self) -> Option<(i32, i32)> { match self.bound_framebuffer.get() { Some(fb) => return fb.size(), // The window system framebuffer is bound None => return Some((self.DrawingBufferWidth(), self.DrawingBufferHeight())), } } fn validate_stencil_actions(&self, action: u32) -> bool { match action { 0 | constants::KEEP | constants::REPLACE | constants::INCR | constants::DECR | constants::INVERT | constants::INCR_WRAP | constants::DECR_WRAP => true, _ => false, } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 // https://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml // https://www.khronos.org/registry/gles/specs/2.0/es_full_spec_2.0.25.pdf#nameddest=section-2.10.4 fn validate_uniform_parameters<T>(&self, uniform: Option<&WebGLUniformLocation>, uniform_type: UniformSetterType, data: &[T]) -> bool { let uniform = match uniform { Some(uniform) => uniform, None => return false, }; let program = self.current_program.get(); match program { Some(ref program) if program.id() == uniform.program_id() => {}, _ => { self.webgl_error(InvalidOperation); return false; }, }; // TODO(emilio): Get more complex uniform info from ANGLE, and use it to // properly validate that the uniform setter type is compatible with the // uniform type, and that the uniform size matches. if data.len() % uniform_type.element_count() != 0 { self.webgl_error(InvalidOperation); return false; } true } /// Translates an image in rgba8 (red in the first byte) format to /// the format that was requested of TexImage. /// /// From the WebGL 1.0 spec, 5.14.8: /// /// "The source image data is conceptually first converted to /// the data type and format specified by the format and type /// arguments, and then transferred to the WebGL /// implementation. If a packed pixel format is specified /// which would imply loss of bits of precision from the image /// data, this loss of precision must occur." fn rgba8_image_to_tex_image_data(&self, format: TexFormat, data_type: TexDataType, pixels: Vec<u8>) -> Vec<u8> { // hint for vector allocation sizing. let pixel_count = pixels.len() / 4; match (format, data_type) { (TexFormat::RGBA, TexDataType::UnsignedByte) => pixels, (TexFormat::RGB, TexDataType::UnsignedByte) => pixels, (TexFormat::RGBA, TexDataType::UnsignedShort4444) => { let mut rgba4 = Vec::<u8>::with_capacity(pixel_count * 2); for rgba8 in pixels.chunks(4) { rgba4.write_u16::<NativeEndian>((rgba8[0] as u16 & 0xf0) << 8 | (rgba8[1] as u16 & 0xf0) << 4 | (rgba8[2] as u16 & 0xf0) | (rgba8[3] as u16 & 0xf0) >> 4).unwrap(); } rgba4 } (TexFormat::RGBA, TexDataType::UnsignedShort5551) => { let mut rgba5551 = Vec::<u8>::with_capacity(pixel_count * 2); for rgba8 in pixels.chunks(4) { rgba5551.write_u16::<NativeEndian>((rgba8[0] as u16 & 0xf8) << 8 | (rgba8[1] as u16 & 0xf8) << 3 | (rgba8[2] as u16 & 0xf8) >> 2 | (rgba8[3] as u16) >> 7).unwrap(); } rgba5551 } (TexFormat::RGB, TexDataType::UnsignedShort565) => { let mut rgb565 = Vec::<u8>::with_capacity(pixel_count * 2); for rgba8 in pixels.chunks(4) { rgb565.write_u16::<NativeEndian>((rgba8[0] as u16 & 0xf8) << 8 | (rgba8[1] as u16 & 0xfc) << 3 | (rgba8[2] as u16 & 0xf8) >> 3).unwrap(); } rgb565 } // Validation should have ensured that we only hit the // above cases, but we haven't turned the (format, type) // into an enum yet so there's a default case here. _ => unreachable!() } } fn get_image_pixels(&self, source: Option<ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement>) -> ImagePixelResult { let source = match source { Some(s) => s, None => return Err(()), }; // NOTE: Getting the pixels probably can be short-circuited if some // parameter is invalid. // // Nontheless, since it's the error case, I'm not totally sure the // complexity is worth it. let (pixels, size) = match source { ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement::ImageData(image_data) => { (image_data.get_data_array(), image_data.get_size()) }, ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement::HTMLImageElement(image) => { let img_url = match image.get_url() { Some(url) => url, None => return Err(()), }; let window = window_from_node(&*self.canvas); let img = match canvas_utils::request_image_from_cache(&window, img_url) { ImageResponse::Loaded(img) => img, ImageResponse::PlaceholderLoaded(_) | ImageResponse::None | ImageResponse::MetadataLoaded(_) => return Err(()), }; let size = Size2D::new(img.width as i32, img.height as i32); // For now Servo's images are all stored as RGBA8 internally. let mut data = match img.format { PixelFormat::RGBA8 => img.bytes.to_vec(), _ => unimplemented!(), }; byte_swap(&mut data); (data, size) }, // TODO(emilio): Getting canvas data is implemented in CanvasRenderingContext2D, // but we need to refactor it moving it to `HTMLCanvasElement` and support // WebGLContext (probably via GetPixels()). ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement::HTMLCanvasElement(canvas) => { if let Some((mut data, size)) = canvas.fetch_all_data() { byte_swap(&mut data); (data, size) } else { return Err(()); } }, ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement::HTMLVideoElement(_rooted_video) => unimplemented!(), }; return Ok((pixels, size)); } // TODO(emilio): Move this logic to a validator. #[allow(unsafe_code)] unsafe fn validate_tex_image_2d_data(&self, width: u32, height: u32, format: TexFormat, data_type: TexDataType, unpacking_alignment: u32, data: *mut JSObject, cx: *mut JSContext) -> Result<u32, ()> { let element_size = data_type.element_size(); let components_per_element = data_type.components_per_element(); let components = format.components(); // If data is non-null, the type of pixels must match the type of the // data to be read. // If it is UNSIGNED_BYTE, a Uint8Array must be supplied; // if it is UNSIGNED_SHORT_5_6_5, UNSIGNED_SHORT_4_4_4_4, // or UNSIGNED_SHORT_5_5_5_1, a Uint16Array must be supplied. // If the types do not match, an INVALID_OPERATION error is generated. typedarray!(in(cx) let typedarray_u8: Uint8Array = data); typedarray!(in(cx) let typedarray_u16: Uint16Array = data); let received_size = if data.is_null() { element_size } else { if typedarray_u16.is_ok() { 2 } else if typedarray_u8.is_ok() { 1 } else { self.webgl_error(InvalidOperation); return Err(()); } }; if received_size != element_size { self.webgl_error(InvalidOperation); return Err(()); } // NOTE: width and height are positive or zero due to validate() if height == 0 { return Ok(0); } else { // We need to be careful here to not count unpack // alignment at the end of the image, otherwise (for // example) passing a single byte for uploading a 1x1 // GL_ALPHA/GL_UNSIGNED_BYTE texture would throw an error. let cpp = element_size * components / components_per_element; let stride = (width * cpp + unpacking_alignment - 1) & !(unpacking_alignment - 1); return Ok(stride * (height - 1) + width * cpp); } } /// Flips the pixels in the Vec on the Y axis if /// UNPACK_FLIP_Y_WEBGL is currently enabled. fn flip_teximage_y(&self, pixels: Vec<u8>, internal_format: TexFormat, data_type: TexDataType, width: usize, height: usize, unpacking_alignment: usize) -> Vec<u8> { if !self.texture_unpacking_settings.get().contains(FLIP_Y_AXIS) { return pixels; } let cpp = (data_type.element_size() * internal_format.components() / data_type.components_per_element()) as usize; let stride = (width * cpp + unpacking_alignment - 1) & !(unpacking_alignment - 1); let mut flipped = Vec::<u8>::with_capacity(pixels.len()); for y in 0..height { let flipped_y = height - 1 - y; let start = flipped_y * stride; flipped.extend_from_slice(&pixels[start..(start + width * cpp)]); flipped.extend(vec![0u8; stride - width * cpp]); } flipped } /// Performs premultiplication of the pixels if /// UNPACK_PREMULTIPLY_ALPHA_WEBGL is currently enabled. fn premultiply_pixels(&self, format: TexFormat, data_type: TexDataType, pixels: Vec<u8>) -> Vec<u8> { if !self.texture_unpacking_settings.get().contains(PREMULTIPLY_ALPHA) { return pixels; } match (format, data_type) { (TexFormat::RGBA, TexDataType::UnsignedByte) => { let mut premul = Vec::<u8>::with_capacity(pixels.len()); for rgba in pixels.chunks(4) { premul.push(multiply_u8_pixel(rgba[0], rgba[3])); premul.push(multiply_u8_pixel(rgba[1], rgba[3])); premul.push(multiply_u8_pixel(rgba[2], rgba[3])); premul.push(rgba[3]); } premul } (TexFormat::LuminanceAlpha, TexDataType::UnsignedByte) => { let mut premul = Vec::<u8>::with_capacity(pixels.len()); for la in pixels.chunks(2) { premul.push(multiply_u8_pixel(la[0], la[1])); premul.push(la[1]); } premul } (TexFormat::RGBA, TexDataType::UnsignedShort5551) => { let mut premul = Vec::<u8>::with_capacity(pixels.len()); for mut rgba in pixels.chunks(2) { let pix = rgba.read_u16::<NativeEndian>().unwrap(); if pix & (1 << 15) != 0 { premul.write_u16::<NativeEndian>(pix).unwrap(); } else { premul.write_u16::<NativeEndian>(0).unwrap(); } } premul } (TexFormat::RGBA, TexDataType::UnsignedShort4444) => { let mut premul = Vec::<u8>::with_capacity(pixels.len()); for mut rgba in pixels.chunks(2) { let pix = rgba.read_u16::<NativeEndian>().unwrap(); let extend_to_8_bits = |val| { (val | val << 4) as u8 }; let r = extend_to_8_bits(pix & 0x000f); let g = extend_to_8_bits((pix & 0x00f0) >> 4); let b = extend_to_8_bits((pix & 0x0f00) >> 8); let a = extend_to_8_bits((pix & 0xf000) >> 12); premul.write_u16::<NativeEndian>((multiply_u8_pixel(r, a) & 0xf0) as u16 >> 4 | (multiply_u8_pixel(g, a) & 0xf0) as u16 | ((multiply_u8_pixel(b, a) & 0xf0) as u16) << 4 | pix & 0xf000).unwrap(); } premul } // Other formats don't have alpha, so return their data untouched. _ => pixels } } fn tex_image_2d(&self, texture: Root<WebGLTexture>, target: TexImageTarget, data_type: TexDataType, internal_format: TexFormat, level: u32, width: u32, height: u32, _border: u32, unpacking_alignment: u32, pixels: Vec<u8>) { // NB: pixels should NOT be premultipied // FINISHME: Consider doing premultiply and flip in a single mutable Vec. let pixels = self.premultiply_pixels(internal_format, data_type, pixels); let pixels = self.flip_teximage_y(pixels, internal_format, data_type, width as usize, height as usize, unpacking_alignment as usize); // TexImage2D depth is always equal to 1 handle_potential_webgl_error!(self, texture.initialize(target, width, height, 1, internal_format, level, Some(data_type))); // Set the unpack alignment. For textures coming from arrays, // this will be the current value of the context's // GL_UNPACK_ALIGNMENT, while for textures from images or // canvas (produced by rgba8_image_to_tex_image_data()), it // will be 1. self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::PixelStorei(constants::UNPACK_ALIGNMENT, unpacking_alignment as i32))) .unwrap(); // TODO(emilio): convert colorspace if requested let msg = WebGLCommand::TexImage2D(target.as_gl_constant(), level as i32, internal_format.as_gl_constant() as i32, width as i32, height as i32, internal_format.as_gl_constant(), data_type.as_gl_constant(), pixels); self.ipc_renderer .send(CanvasMsg::WebGL(msg)) .unwrap(); if let Some(fb) = self.bound_framebuffer.get() { fb.invalidate_texture(&*texture); } } fn tex_sub_image_2d(&self, texture: Root<WebGLTexture>, target: TexImageTarget, level: u32, xoffset: i32, yoffset: i32, width: u32, height: u32, format: TexFormat, data_type: TexDataType, unpacking_alignment: u32, pixels: Vec<u8>) { // NB: pixels should NOT be premultipied // We have already validated level let image_info = texture.image_info_for_target(&target, level); // GL_INVALID_VALUE is generated if: // - xoffset or yoffset is less than 0 // - x offset plus the width is greater than the texture width // - y offset plus the height is greater than the texture height if xoffset < 0 || (xoffset as u32 + width) > image_info.width() || yoffset < 0 || (yoffset as u32 + height) > image_info.height() { return self.webgl_error(InvalidValue); } // NB: format and internal_format must match. if format != image_info.internal_format().unwrap() || data_type != image_info.data_type().unwrap() { return self.webgl_error(InvalidOperation); } // FINISHME: Consider doing premultiply and flip in a single mutable Vec. let pixels = self.premultiply_pixels(format, data_type, pixels); let pixels = self.flip_teximage_y(pixels, format, data_type, width as usize, height as usize, unpacking_alignment as usize); // Set the unpack alignment. For textures coming from arrays, // this will be the current value of the context's // GL_UNPACK_ALIGNMENT, while for textures from images or // canvas (produced by rgba8_image_to_tex_image_data()), it // will be 1. self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::PixelStorei(constants::UNPACK_ALIGNMENT, unpacking_alignment as i32))) .unwrap(); // TODO(emilio): convert colorspace if requested let msg = WebGLCommand::TexSubImage2D(target.as_gl_constant(), level as i32, xoffset, yoffset, width as i32, height as i32, format.as_gl_constant(), data_type.as_gl_constant(), pixels); self.ipc_renderer .send(CanvasMsg::WebGL(msg)) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14 fn validate_feature_enum(&self, cap: u32) -> bool { match cap { constants::BLEND | constants::CULL_FACE | constants::DEPTH_TEST | constants::DITHER | constants::POLYGON_OFFSET_FILL | constants::SAMPLE_ALPHA_TO_COVERAGE | constants::SAMPLE_COVERAGE | constants::SAMPLE_COVERAGE_INVERT | constants::SCISSOR_TEST | constants::STENCIL_TEST => true, _ => { self.webgl_error(InvalidEnum); false }, } } } impl Drop for WebGLRenderingContext { fn drop(&mut self) { self.ipc_renderer.send(CanvasMsg::Common(CanvasCommonMsg::Close)).unwrap(); } } // FIXME: After [1] lands and the relevant Servo and codegen PR too, we should // convert all our raw JSObject pointers to proper types. // // [1]: https://github.com/servo/rust-mozjs/pull/304 #[allow(unsafe_code)] unsafe fn typed_array_or_sequence_to_vec<T>(cx: *mut JSContext, sequence_or_abv: *mut JSObject, config: <T::Element as FromJSValConvertible>::Config) -> Result<Vec<T::Element>, Error> where T: TypedArrayElement, T::Element: FromJSValConvertible + Clone, <T::Element as FromJSValConvertible>::Config: Clone, { // TODO(servo/rust-mozjs#330): replace this with a macro that supports generic types. let mut typed_array_root = Rooted::new_unrooted(); let typed_array: Option<TypedArray<T>> = TypedArray::from(cx, &mut typed_array_root, sequence_or_abv).ok(); if let Some(mut typed_array) = typed_array { return Ok(typed_array.as_slice().to_vec()); } assert!(!sequence_or_abv.is_null()); rooted!(in(cx) let mut val = UndefinedValue()); sequence_or_abv.to_jsval(cx, val.handle_mut()); match Vec::<T::Element>::from_jsval(cx, val.handle(), config) { Ok(ConversionResult::Success(v)) => Ok(v), Ok(ConversionResult::Failure(error)) => Err(Error::Type(error.into_owned())), // FIXME: What to do here? Generated code only aborts the execution of // the script. Err(err) => panic!("unexpected conversion error: {:?}", err), } } #[allow(unsafe_code)] unsafe fn fallible_array_buffer_view_to_vec(cx: *mut JSContext, abv: *mut JSObject) -> Result<Vec<u8>, Error> { assert!(!abv.is_null()); typedarray!(in(cx) let array_buffer_view: ArrayBufferView = abv); match array_buffer_view { Ok(mut v) => Ok(v.as_slice().to_vec()), Err(_) => Err(Error::Type("Not an ArrayBufferView".to_owned())), } } impl WebGLRenderingContextMethods for WebGLRenderingContext { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.1 fn Canvas(&self) -> Root<HTMLCanvasElement> { Root::from_ref(&*self.canvas) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11 fn Flush(&self) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Flush)) .unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11 fn Finish(&self) { let (sender, receiver) = webrender_traits::channel::msg_channel().unwrap(); self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Finish(sender))) .unwrap(); receiver.recv().unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.1 fn DrawingBufferWidth(&self) -> i32 { let (sender, receiver) = webrender_traits::channel::msg_channel().unwrap(); self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::DrawingBufferWidth(sender))) .unwrap(); receiver.recv().unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.1 fn DrawingBufferHeight(&self) -> i32 { let (sender, receiver) = webrender_traits::channel::msg_channel().unwrap(); self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::DrawingBufferHeight(sender))) .unwrap(); receiver.recv().unwrap() } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 unsafe fn GetBufferParameter(&self, _cx: *mut JSContext, target: u32, parameter: u32) -> JSVal { let (sender, receiver) = webrender_traits::channel::msg_channel().unwrap(); self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::GetBufferParameter(target, parameter, sender))) .unwrap(); match handle_potential_webgl_error!(self, receiver.recv().unwrap(), WebGLParameter::Invalid) { WebGLParameter::Int(val) => Int32Value(val), WebGLParameter::Bool(_) => panic!("Buffer parameter should not be bool"), WebGLParameter::Float(_) => panic!("Buffer parameter should not be float"), WebGLParameter::FloatArray(_) => panic!("Buffer parameter should not be float array"), WebGLParameter::String(_) => panic!("Buffer parameter should not be string"), WebGLParameter::Invalid => NullValue(), } } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 unsafe fn GetParameter(&self, cx: *mut JSContext, parameter: u32) -> JSVal { // Handle the GL_*_BINDING without going all the way // to the GL, since we would just need to map back from GL's // returned ID to the WebGL* object we're tracking. match parameter { constants::ARRAY_BUFFER_BINDING => return object_binding_to_js_or_null!(cx, &self.bound_buffer_array), constants::ELEMENT_ARRAY_BUFFER_BINDING => return object_binding_to_js_or_null!(cx, &self.bound_buffer_element_array), constants::FRAMEBUFFER_BINDING => return object_binding_to_js_or_null!(cx, &self.bound_framebuffer), constants::RENDERBUFFER_BINDING => return object_binding_to_js_or_null!(cx, &self.bound_renderbuffer), constants::TEXTURE_BINDING_2D => return object_binding_to_js_or_null!(cx, &self.bound_texture_2d), constants::TEXTURE_BINDING_CUBE_MAP => return object_binding_to_js_or_null!(cx, &self.bound_texture_cube_map), // In readPixels we currently support RGBA/UBYTE only. If // we wanted to support other formats, we could ask the // driver, but we would need to check for // GL_OES_read_format support (assuming an underlying GLES // driver. Desktop is happy to format convert for us). constants::IMPLEMENTATION_COLOR_READ_FORMAT => { if !self.validate_framebuffer_complete() { return NullValue(); } else { return Int32Value(constants::RGBA as i32); } } constants::IMPLEMENTATION_COLOR_READ_TYPE => { if !self.validate_framebuffer_complete() { return NullValue(); } else { return Int32Value(constants::UNSIGNED_BYTE as i32); } } _ => {} } let (sender, receiver) = webrender_traits::channel::msg_channel().unwrap(); self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::GetParameter(parameter, sender))) .unwrap(); match handle_potential_webgl_error!(self, receiver.recv().unwrap(), WebGLParameter::Invalid) { WebGLParameter::Int(val) => Int32Value(val), WebGLParameter::Bool(val) => BooleanValue(val), WebGLParameter::Float(val) => DoubleValue(val as f64), WebGLParameter::FloatArray(_) => panic!("Parameter should not be float array"), WebGLParameter::String(val) => { rooted!(in(cx) let mut rval = UndefinedValue()); val.to_jsval(cx, rval.handle_mut()); rval.get() } WebGLParameter::Invalid => NullValue(), } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn GetError(&self) -> u32 { let error_code = if let Some(error) = self.last_error.get() { match error { WebGLError::InvalidEnum => constants::INVALID_ENUM, WebGLError::InvalidFramebufferOperation => constants::INVALID_FRAMEBUFFER_OPERATION, WebGLError::InvalidValue => constants::INVALID_VALUE, WebGLError::InvalidOperation => constants::INVALID_OPERATION, WebGLError::OutOfMemory => constants::OUT_OF_MEMORY, WebGLError::ContextLost => constants::CONTEXT_LOST_WEBGL, } } else { constants::NO_ERROR }; self.last_error.set(None); error_code } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.2 fn GetContextAttributes(&self) -> Option<WebGLContextAttributes> { let (sender, receiver) = webrender_traits::channel::msg_channel().unwrap(); // If the send does not succeed, assume context lost if let Err(_) = self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::GetContextAttributes(sender))) { return None; } let attrs = receiver.recv().unwrap(); Some(WebGLContextAttributes { alpha: attrs.alpha, antialias: attrs.antialias, depth: attrs.depth, failIfMajorPerformanceCaveat: false, preferLowPowerToHighPerformance: false, premultipliedAlpha: attrs.premultiplied_alpha, preserveDrawingBuffer: attrs.preserve_drawing_buffer, stencil: attrs.stencil }) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 fn GetSupportedExtensions(&self) -> Option<Vec<DOMString>> { Some(vec![]) } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 unsafe fn GetExtension(&self, _cx: *mut JSContext, _name: DOMString) -> Option<NonZero<*mut JSObject>> { None } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn ActiveTexture(&self, texture: u32) { self.ipc_renderer.send(CanvasMsg::WebGL(WebGLCommand::ActiveTexture(texture))).unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn BlendColor(&self, r: f32, g: f32, b: f32, a: f32) { self.ipc_renderer.send(CanvasMsg::WebGL(WebGLCommand::BlendColor(r, g, b, a))).unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn BlendEquation(&self, mode: u32) { if mode != constants::FUNC_ADD { return self.webgl_error(InvalidEnum); } self.ipc_renderer.send(CanvasMsg::WebGL(WebGLCommand::BlendEquation(mode))).unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn BlendEquationSeparate(&self, mode_rgb: u32, mode_alpha: u32) { if mode_rgb != constants::FUNC_ADD || mode_alpha != constants::FUNC_ADD { return self.webgl_error(InvalidEnum); } self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::BlendEquationSeparate(mode_rgb, mode_alpha))) .unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn BlendFunc(&self, src_factor: u32, dest_factor: u32) { // From the WebGL 1.0 spec, 6.13: Viewport Depth Range: // // A call to blendFunc will generate an INVALID_OPERATION error if one of the two // factors is set to CONSTANT_COLOR or ONE_MINUS_CONSTANT_COLOR and the other to // CONSTANT_ALPHA or ONE_MINUS_CONSTANT_ALPHA. if has_invalid_blend_constants(src_factor, dest_factor) { return self.webgl_error(InvalidOperation); } if has_invalid_blend_constants(dest_factor, src_factor) { return self.webgl_error(InvalidOperation); } self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::BlendFunc(src_factor, dest_factor))) .unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn BlendFuncSeparate(&self, src_rgb: u32, dest_rgb: u32, src_alpha: u32, dest_alpha: u32) { // From the WebGL 1.0 spec, 6.13: Viewport Depth Range: // // A call to blendFuncSeparate will generate an INVALID_OPERATION error if srcRGB is // set to CONSTANT_COLOR or ONE_MINUS_CONSTANT_COLOR and dstRGB is set to // CONSTANT_ALPHA or ONE_MINUS_CONSTANT_ALPHA or vice versa. if has_invalid_blend_constants(src_rgb, dest_rgb) { return self.webgl_error(InvalidOperation); } if has_invalid_blend_constants(dest_rgb, src_rgb) { return self.webgl_error(InvalidOperation); } self.ipc_renderer.send( CanvasMsg::WebGL(WebGLCommand::BlendFuncSeparate(src_rgb, dest_rgb, src_alpha, dest_alpha))).unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn AttachShader(&self, program: Option<&WebGLProgram>, shader: Option<&WebGLShader>) { if let Some(program) = program { if let Some(shader) = shader { handle_potential_webgl_error!(self, program.attach_shader(shader)); } } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn DetachShader(&self, program: Option<&WebGLProgram>, shader: Option<&WebGLShader>) { if let Some(program) = program { if let Some(shader) = shader { handle_potential_webgl_error!(self, program.detach_shader(shader)); } } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn BindAttribLocation(&self, program: Option<&WebGLProgram>, index: u32, name: DOMString) { if let Some(program) = program { handle_potential_webgl_error!(self, program.bind_attrib_location(index, name)); } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 fn BindBuffer(&self, target: u32, buffer: Option<&WebGLBuffer>) { let slot = match target { constants::ARRAY_BUFFER => &self.bound_buffer_array, constants::ELEMENT_ARRAY_BUFFER => &self.bound_buffer_element_array, _ => return self.webgl_error(InvalidEnum), }; if let Some(buffer) = buffer { match buffer.bind(target) { Ok(_) => slot.set(Some(buffer)), Err(e) => return self.webgl_error(e), } } else { slot.set(None); // Unbind the current buffer self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::BindBuffer(target, None))) .unwrap() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 fn BindFramebuffer(&self, target: u32, framebuffer: Option<&WebGLFramebuffer>) { if target != constants::FRAMEBUFFER { return self.webgl_error(InvalidOperation); } if let Some(framebuffer) = framebuffer { if framebuffer.is_deleted() { // From the WebGL spec: // // "An attempt to bind a deleted framebuffer will // generate an INVALID_OPERATION error, and the // current binding will remain untouched." return self.webgl_error(InvalidOperation); } else { framebuffer.bind(target); self.bound_framebuffer.set(Some(framebuffer)); } } else { // Bind the default framebuffer let cmd = WebGLCommand::BindFramebuffer(target, WebGLFramebufferBindingRequest::Default); self.ipc_renderer.send(CanvasMsg::WebGL(cmd)).unwrap(); self.bound_framebuffer.set(framebuffer); } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 fn BindRenderbuffer(&self, target: u32, renderbuffer: Option<&WebGLRenderbuffer>) { if target != constants::RENDERBUFFER { return self.webgl_error(InvalidEnum); } match renderbuffer { // Implementations differ on what to do in the deleted // case: Chromium currently unbinds, and Gecko silently // returns. The conformance tests don't cover this case. Some(renderbuffer) if !renderbuffer.is_deleted() => { self.bound_renderbuffer.set(Some(renderbuffer)); renderbuffer.bind(target); } _ => { self.bound_renderbuffer.set(None); // Unbind the currently bound renderbuffer self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::BindRenderbuffer(target, None))) .unwrap() } } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn BindTexture(&self, target: u32, texture: Option<&WebGLTexture>) { let slot = match target { constants::TEXTURE_2D => &self.bound_texture_2d, constants::TEXTURE_CUBE_MAP => &self.bound_texture_cube_map, _ => return self.webgl_error(InvalidEnum), }; if let Some(texture) = texture { match texture.bind(target) { Ok(_) => slot.set(Some(texture)), Err(err) => return self.webgl_error(err), } } else { slot.set(None); // Unbind the currently bound texture self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::BindTexture(target, None))) .unwrap() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn GenerateMipmap(&self, target: u32) { let slot = match target { constants::TEXTURE_2D => &self.bound_texture_2d, constants::TEXTURE_CUBE_MAP => &self.bound_texture_cube_map, _ => return self.webgl_error(InvalidEnum), }; match slot.get() { Some(texture) => handle_potential_webgl_error!(self, texture.generate_mipmap()), None => self.webgl_error(InvalidOperation) } } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 unsafe fn BufferData(&self, cx: *mut JSContext, target: u32, data: *mut JSObject, usage: u32) -> Fallible<()> { if data.is_null() { return Ok(self.webgl_error(InvalidValue)); } typedarray!(in(cx) let array_buffer: ArrayBuffer = data); let data_vec = match array_buffer { Ok(mut data) => data.as_slice().to_vec(), Err(_) => try!(fallible_array_buffer_view_to_vec(cx, data)), }; let bound_buffer = match target { constants::ARRAY_BUFFER => self.bound_buffer_array.get(), constants::ELEMENT_ARRAY_BUFFER => self.bound_buffer_element_array.get(), _ => return Ok(self.webgl_error(InvalidEnum)), }; let bound_buffer = match bound_buffer { Some(bound_buffer) => bound_buffer, None => return Ok(self.webgl_error(InvalidValue)), }; match usage { constants::STREAM_DRAW | constants::STATIC_DRAW | constants::DYNAMIC_DRAW => (), _ => return Ok(self.webgl_error(InvalidEnum)), } handle_potential_webgl_error!(self, bound_buffer.buffer_data(target, &data_vec, usage)); Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 fn BufferData_(&self, target: u32, size: i64, usage: u32) -> Fallible<()> { let bound_buffer = match target { constants::ARRAY_BUFFER => self.bound_buffer_array.get(), constants::ELEMENT_ARRAY_BUFFER => self.bound_buffer_element_array.get(), _ => return Ok(self.webgl_error(InvalidEnum)), }; let bound_buffer = match bound_buffer { Some(bound_buffer) => bound_buffer, None => return Ok(self.webgl_error(InvalidValue)), }; if size < 0 { return Ok(self.webgl_error(InvalidValue)); } match usage { constants::STREAM_DRAW | constants::STATIC_DRAW | constants::DYNAMIC_DRAW => (), _ => return Ok(self.webgl_error(InvalidEnum)), } // FIXME: Allocating a buffer based on user-requested size is // not great, but we don't have a fallible allocation to try. let data = vec![0u8; size as usize]; handle_potential_webgl_error!(self, bound_buffer.buffer_data(target, &data, usage)); Ok(()) } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 unsafe fn BufferSubData(&self, cx: *mut JSContext, target: u32, offset: i64, data: *mut JSObject) -> Fallible<()> { if data.is_null() { return Ok(self.webgl_error(InvalidValue)); } typedarray!(in(cx) let array_buffer: ArrayBuffer = data); let data_vec = match array_buffer { Ok(mut data) => data.as_slice().to_vec(), Err(_) => try!(fallible_array_buffer_view_to_vec(cx, data)), }; let bound_buffer = match target { constants::ARRAY_BUFFER => self.bound_buffer_array.get(), constants::ELEMENT_ARRAY_BUFFER => self.bound_buffer_element_array.get(), _ => return Ok(self.webgl_error(InvalidEnum)), }; let bound_buffer = match bound_buffer { Some(bound_buffer) => bound_buffer, None => return Ok(self.webgl_error(InvalidOperation)), }; if offset < 0 { return Ok(self.webgl_error(InvalidValue)); } if (offset as usize) + data_vec.len() > bound_buffer.capacity() { return Ok(self.webgl_error(InvalidValue)); } self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::BufferSubData(target, offset as isize, data_vec))) .unwrap(); Ok(()) } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 unsafe fn CompressedTexImage2D(&self, cx: *mut JSContext, _target: u32, _level: i32, _internal_format: u32, _width: i32, _height: i32, _border: i32, pixels: *mut JSObject) -> Fallible<()> { let _data = try!(fallible_array_buffer_view_to_vec(cx, pixels) ); // FIXME: No compressed texture format is currently supported, so error out as per // https://www.khronos.org/registry/webgl/specs/latest/1.0/#COMPRESSED_TEXTURE_SUPPORT self.webgl_error(InvalidEnum); Ok(()) } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 unsafe fn CompressedTexSubImage2D(&self, cx: *mut JSContext, _target: u32, _level: i32, _xoffset: i32, _yoffset: i32, _width: i32, _height: i32, _format: u32, pixels: *mut JSObject) -> Fallible<()> { let _data = try!(fallible_array_buffer_view_to_vec(cx, pixels)); // FIXME: No compressed texture format is currently supported, so error out as per // https://www.khronos.org/registry/webgl/specs/latest/1.0/#COMPRESSED_TEXTURE_SUPPORT self.webgl_error(InvalidEnum); Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn CopyTexImage2D(&self, target: u32, level: i32, internal_format: u32, x: i32, y: i32, width: i32, height: i32, border: i32) { if !self.validate_framebuffer_complete() { return; } let validator = CommonTexImage2DValidator::new(self, target, level, internal_format, width, height, border); let CommonTexImage2DValidatorResult { texture, target, level, internal_format, width, height, border, } = match validator.validate() { Ok(result) => result, Err(_) => return, }; let image_info = texture.image_info_for_target(&target, level); // The color buffer components can be dropped during the conversion to // the internal_format, but new components cannot be added. // // Note that this only applies if we're copying to an already // initialized texture. // // GL_INVALID_OPERATION is generated if the color buffer cannot be // converted to the internal_format. if let Some(old_internal_format) = image_info.internal_format() { if old_internal_format.components() > internal_format.components() { return self.webgl_error(InvalidOperation); } } // NB: TexImage2D depth is always equal to 1 handle_potential_webgl_error!(self, texture.initialize(target, width as u32, height as u32, 1, internal_format, level as u32, None)); let msg = WebGLCommand::CopyTexImage2D(target.as_gl_constant(), level as i32, internal_format.as_gl_constant(), x, y, width as i32, height as i32, border as i32); self.ipc_renderer.send(CanvasMsg::WebGL(msg)).unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn CopyTexSubImage2D(&self, target: u32, level: i32, xoffset: i32, yoffset: i32, x: i32, y: i32, width: i32, height: i32) { if !self.validate_framebuffer_complete() { return; } // NB: We use a dummy (valid) format and border in order to reuse the // common validations, but this should have its own validator. let validator = CommonTexImage2DValidator::new(self, target, level, TexFormat::RGBA.as_gl_constant(), width, height, 0); let CommonTexImage2DValidatorResult { texture, target, level, width, height, .. } = match validator.validate() { Ok(result) => result, Err(_) => return, }; let image_info = texture.image_info_for_target(&target, level); // GL_INVALID_VALUE is generated if: // - xoffset or yoffset is less than 0 // - x offset plus the width is greater than the texture width // - y offset plus the height is greater than the texture height if xoffset < 0 || (xoffset as u32 + width) > image_info.width() || yoffset < 0 || (yoffset as u32 + height) > image_info.height() { self.webgl_error(InvalidValue); return; } let msg = WebGLCommand::CopyTexSubImage2D(target.as_gl_constant(), level as i32, xoffset, yoffset, x, y, width as i32, height as i32); self.ipc_renderer.send(CanvasMsg::WebGL(msg)).unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11 fn Clear(&self, mask: u32) { if !self.validate_framebuffer_complete() { return; } self.ipc_renderer.send(CanvasMsg::WebGL(WebGLCommand::Clear(mask))).unwrap(); self.mark_as_dirty(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn ClearColor(&self, red: f32, green: f32, blue: f32, alpha: f32) { self.current_clear_color.set((red, green, blue, alpha)); self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::ClearColor(red, green, blue, alpha))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn ClearDepth(&self, depth: f32) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::ClearDepth(depth as f64))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn ClearStencil(&self, stencil: i32) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::ClearStencil(stencil))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn ColorMask(&self, r: bool, g: bool, b: bool, a: bool) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::ColorMask(r, g, b, a))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn CullFace(&self, mode: u32) { match mode { constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::CullFace(mode))) .unwrap(), _ => self.webgl_error(InvalidEnum), } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn FrontFace(&self, mode: u32) { match mode { constants::CW | constants::CCW => self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::FrontFace(mode))) .unwrap(), _ => self.webgl_error(InvalidEnum), } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn DepthFunc(&self, func: u32) { match func { constants::NEVER | constants::LESS | constants::EQUAL | constants::LEQUAL | constants::GREATER | constants::NOTEQUAL | constants::GEQUAL | constants::ALWAYS => self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::DepthFunc(func))) .unwrap(), _ => self.webgl_error(InvalidEnum), } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn DepthMask(&self, flag: bool) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::DepthMask(flag))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn DepthRange(&self, near: f32, far: f32) { // From the WebGL 1.0 spec, 6.12: Viewport Depth Range: // // "A call to depthRange will generate an // INVALID_OPERATION error if zNear is greater than // zFar." if near > far { return self.webgl_error(InvalidOperation); } self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::DepthRange(near as f64, far as f64))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn Enable(&self, cap: u32) { if self.validate_feature_enum(cap) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Enable(cap))) .unwrap(); } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn Disable(&self, cap: u32) { if self.validate_feature_enum(cap) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Disable(cap))) .unwrap() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn CompileShader(&self, shader: Option<&WebGLShader>) { if let Some(shader) = shader { shader.compile() } } // TODO(emilio): Probably in the future we should keep track of the // generated objects, either here or in the webgl thread // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 fn CreateBuffer(&self) -> Option<Root<WebGLBuffer>> { WebGLBuffer::maybe_new(self.global().as_window(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 fn CreateFramebuffer(&self) -> Option<Root<WebGLFramebuffer>> { WebGLFramebuffer::maybe_new(self.global().as_window(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 fn CreateRenderbuffer(&self) -> Option<Root<WebGLRenderbuffer>> { WebGLRenderbuffer::maybe_new(self.global().as_window(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn CreateTexture(&self) -> Option<Root<WebGLTexture>> { WebGLTexture::maybe_new(self.global().as_window(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn CreateProgram(&self) -> Option<Root<WebGLProgram>> { WebGLProgram::maybe_new(self.global().as_window(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn CreateShader(&self, shader_type: u32) -> Option<Root<WebGLShader>> { match shader_type { constants::VERTEX_SHADER | constants::FRAGMENT_SHADER => {}, _ => { self.webgl_error(InvalidEnum); return None; } } WebGLShader::maybe_new(self.global().as_window(), self.ipc_renderer.clone(), shader_type) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 fn DeleteBuffer(&self, buffer: Option<&WebGLBuffer>) { if let Some(buffer) = buffer { handle_object_deletion!(self, self.bound_buffer_array, buffer, Some(WebGLCommand::BindBuffer(constants::ARRAY_BUFFER, None))); handle_object_deletion!(self, self.bound_buffer_element_array, buffer, Some(WebGLCommand::BindBuffer(constants::ELEMENT_ARRAY_BUFFER, None))); buffer.delete() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 fn DeleteFramebuffer(&self, framebuffer: Option<&WebGLFramebuffer>) { if let Some(framebuffer) = framebuffer { handle_object_deletion!(self, self.bound_framebuffer, framebuffer, Some(WebGLCommand::BindFramebuffer(constants::FRAMEBUFFER, WebGLFramebufferBindingRequest::Default))); framebuffer.delete() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 fn DeleteRenderbuffer(&self, renderbuffer: Option<&WebGLRenderbuffer>) { if let Some(renderbuffer) = renderbuffer { handle_object_deletion!(self, self.bound_renderbuffer, renderbuffer, Some(WebGLCommand::BindRenderbuffer(constants::RENDERBUFFER, None))); // From the GLES 2.0.25 spec, page 113: // // "If a renderbuffer object is deleted while its // image is attached to the currently bound // framebuffer, then it is as if // FramebufferRenderbuffer had been called, with a // renderbuffer of 0, for each attachment point to // which this image was attached in the currently // bound framebuffer." // if let Some(fb) = self.bound_framebuffer.get() { fb.detach_renderbuffer(renderbuffer); } renderbuffer.delete() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn DeleteTexture(&self, texture: Option<&WebGLTexture>) { if let Some(texture) = texture { handle_object_deletion!(self, self.bound_texture_2d, texture, Some(WebGLCommand::BindTexture(constants::TEXTURE_2D, None))); handle_object_deletion!(self, self.bound_texture_cube_map, texture, Some(WebGLCommand::BindTexture(constants::TEXTURE_CUBE_MAP, None))); // From the GLES 2.0.25 spec, page 113: // // "If a texture object is deleted while its image is // attached to the currently bound framebuffer, then // it is as if FramebufferTexture2D had been called, // with a texture of 0, for each attachment point to // which this image was attached in the currently // bound framebuffer." if let Some(fb) = self.bound_framebuffer.get() { fb.detach_texture(texture); } texture.delete() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn DeleteProgram(&self, program: Option<&WebGLProgram>) { if let Some(program) = program { // FIXME: We should call glUseProgram(0), but // WebGLCommand::UseProgram() doesn't take an Option // currently. This is also a problem for useProgram(null) handle_object_deletion!(self, self.current_program, program, None); program.delete() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn DeleteShader(&self, shader: Option<&WebGLShader>) { if let Some(shader) = shader { shader.delete() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11 fn DrawArrays(&self, mode: u32, first: i32, count: i32) { match mode { constants::POINTS | constants::LINE_STRIP | constants::LINE_LOOP | constants::LINES | constants::TRIANGLE_STRIP | constants::TRIANGLE_FAN | constants::TRIANGLES => { if self.current_program.get().is_none() { return self.webgl_error(InvalidOperation); } if first < 0 || count < 0 { return self.webgl_error(InvalidValue); } if !self.validate_framebuffer_complete() { return; } self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::DrawArrays(mode, first, count))) .unwrap(); self.mark_as_dirty(); }, _ => self.webgl_error(InvalidEnum), } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.11 fn DrawElements(&self, mode: u32, count: i32, type_: u32, offset: i64) { // From the GLES 2.0.25 spec, page 21: // // "type must be one of UNSIGNED_BYTE or UNSIGNED_SHORT" let type_size = match type_ { constants::UNSIGNED_BYTE => 1, constants::UNSIGNED_SHORT => 2, _ => return self.webgl_error(InvalidEnum), }; if offset % type_size != 0 { return self.webgl_error(InvalidOperation); } if count < 0 { return self.webgl_error(InvalidValue); } if offset < 0 { return self.webgl_error(InvalidValue); } if self.current_program.get().is_none() { // From the WebGL spec // // If the CURRENT_PROGRAM is null, an INVALID_OPERATION error will be generated. // WebGL performs additional error checking beyond that specified // in OpenGL ES 2.0 during calls to drawArrays and drawElements. // return self.webgl_error(InvalidOperation); } if let Some(array_buffer) = self.bound_buffer_element_array.get() { // WebGL Spec: check buffer overflows, must be a valid multiple of the size. let val = offset as u64 + (count as u64 * type_size as u64); if val > array_buffer.capacity() as u64 { return self.webgl_error(InvalidOperation); } } else { // From the WebGL spec // // a non-null WebGLBuffer must be bound to the ELEMENT_ARRAY_BUFFER binding point // or an INVALID_OPERATION error will be generated. // return self.webgl_error(InvalidOperation); } if !self.validate_framebuffer_complete() { return; } match mode { constants::POINTS | constants::LINE_STRIP | constants::LINE_LOOP | constants::LINES | constants::TRIANGLE_STRIP | constants::TRIANGLE_FAN | constants::TRIANGLES => { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::DrawElements(mode, count, type_, offset))) .unwrap(); self.mark_as_dirty(); }, _ => self.webgl_error(InvalidEnum), } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn EnableVertexAttribArray(&self, attrib_id: u32) { if attrib_id > self.limits.max_vertex_attribs { return self.webgl_error(InvalidValue); } self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::EnableVertexAttribArray(attrib_id))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn DisableVertexAttribArray(&self, attrib_id: u32) { if attrib_id > self.limits.max_vertex_attribs { return self.webgl_error(InvalidValue); } self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::DisableVertexAttribArray(attrib_id))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn GetActiveUniform(&self, program: Option<&WebGLProgram>, index: u32) -> Option<Root<WebGLActiveInfo>> { let program = match program { Some(program) => program, None => { // Reasons to generate InvalidValue error // From the GLES 2.0 spec // // "INVALID_VALUE is generated if index is greater than or equal // to the number of active uniform variables in program" // // A null program has no uniforms so any index is always greater than the active uniforms // WebGl conformance expects error with null programs. Check tests in get-active-test.html self.webgl_error(InvalidValue); return None; } }; match program.get_active_uniform(index) { Ok(ret) => Some(ret), Err(e) => { self.webgl_error(e); return None; } } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn GetActiveAttrib(&self, program: Option<&WebGLProgram>, index: u32) -> Option<Root<WebGLActiveInfo>> { let program = match program { Some(program) => program, None => { // Reasons to generate InvalidValue error // From the GLES 2.0 spec // // "INVALID_VALUE is generated if index is greater than or equal // to the number of active attribute variables in program" // // A null program has no attributes so any index is always greater than the active uniforms // WebGl conformance expects error with null programs. Check tests in get-active-test.html self.webgl_error(InvalidValue); return None; } }; match program.get_active_attrib(index) { Ok(ret) => Some(ret), Err(e) => { self.webgl_error(e); return None; } } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn GetAttribLocation(&self, program: Option<&WebGLProgram>, name: DOMString) -> i32 { if let Some(program) = program { handle_potential_webgl_error!(self, program.get_attrib_location(name), None).unwrap_or(-1) } else { -1 } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn GetProgramInfoLog(&self, program: Option<&WebGLProgram>) -> Option<DOMString> { if let Some(program) = program { match program.get_info_log() { Ok(value) => Some(DOMString::from(value)), Err(e) => { self.webgl_error(e); None } } } else { self.webgl_error(WebGLError::InvalidValue); None } } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 unsafe fn GetProgramParameter(&self, _: *mut JSContext, program: Option<&WebGLProgram>, param_id: u32) -> JSVal { if let Some(program) = program { match handle_potential_webgl_error!(self, program.parameter(param_id), WebGLParameter::Invalid) { WebGLParameter::Int(val) => Int32Value(val), WebGLParameter::Bool(val) => BooleanValue(val), WebGLParameter::String(_) => panic!("Program parameter should not be string"), WebGLParameter::Float(_) => panic!("Program parameter should not be float"), WebGLParameter::FloatArray(_) => { panic!("Program paramenter should not be float array") } WebGLParameter::Invalid => NullValue(), } } else { NullValue() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn GetShaderInfoLog(&self, shader: Option<&WebGLShader>) -> Option<DOMString> { shader.and_then(|s| s.info_log()).map(DOMString::from) } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 unsafe fn GetShaderParameter(&self, _: *mut JSContext, shader: Option<&WebGLShader>, param_id: u32) -> JSVal { if let Some(shader) = shader { match handle_potential_webgl_error!(self, shader.parameter(param_id), WebGLParameter::Invalid) { WebGLParameter::Int(val) => Int32Value(val), WebGLParameter::Bool(val) => BooleanValue(val), WebGLParameter::String(_) => panic!("Shader parameter should not be string"), WebGLParameter::Float(_) => panic!("Shader parameter should not be float"), WebGLParameter::FloatArray(_) => { panic!("Shader paramenter should not be float array") } WebGLParameter::Invalid => NullValue(), } } else { NullValue() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn GetUniformLocation(&self, program: Option<&WebGLProgram>, name: DOMString) -> Option<Root<WebGLUniformLocation>> { program.and_then(|p| { handle_potential_webgl_error!(self, p.get_uniform_location(name), None) .map(|location| WebGLUniformLocation::new(self.global().as_window(), location, p.id())) }) } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 unsafe fn GetVertexAttrib(&self, cx: *mut JSContext, index: u32, pname: u32) -> JSVal { if index == 0 && pname == constants::CURRENT_VERTEX_ATTRIB { rooted!(in(cx) let mut result = UndefinedValue()); let (x, y, z, w) = self.current_vertex_attrib_0.get(); let attrib = vec![x, y, z, w]; attrib.to_jsval(cx, result.handle_mut()); return result.get() } let (sender, receiver) = webrender_traits::channel::msg_channel().unwrap(); self.ipc_renderer.send(CanvasMsg::WebGL(WebGLCommand::GetVertexAttrib(index, pname, sender))).unwrap(); match handle_potential_webgl_error!(self, receiver.recv().unwrap(), WebGLParameter::Invalid) { WebGLParameter::Int(val) => Int32Value(val), WebGLParameter::Bool(val) => BooleanValue(val), WebGLParameter::String(_) => panic!("Vertex attrib should not be string"), WebGLParameter::Float(_) => panic!("Vertex attrib should not be float"), WebGLParameter::FloatArray(val) => { rooted!(in(cx) let mut result = UndefinedValue()); val.to_jsval(cx, result.handle_mut()); result.get() } WebGLParameter::Invalid => NullValue(), } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn Hint(&self, target: u32, mode: u32) { if target != constants::GENERATE_MIPMAP_HINT { return self.webgl_error(InvalidEnum); } match mode { constants::FASTEST | constants::NICEST | constants::DONT_CARE => (), _ => return self.webgl_error(InvalidEnum), } self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Hint(target, mode))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 fn IsBuffer(&self, buffer: Option<&WebGLBuffer>) -> bool { buffer.map_or(false, |buf| buf.target().is_some() && !buf.is_deleted()) } // TODO: We could write this without IPC, recording the calls to `enable` and `disable`. // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn IsEnabled(&self, cap: u32) -> bool { if self.validate_feature_enum(cap) { let (sender, receiver) = webrender_traits::channel::msg_channel().unwrap(); self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::IsEnabled(cap, sender))) .unwrap(); return receiver.recv().unwrap(); } false } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 fn IsFramebuffer(&self, frame_buffer: Option<&WebGLFramebuffer>) -> bool { frame_buffer.map_or(false, |buf| buf.target().is_some() && !buf.is_deleted()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn IsProgram(&self, program: Option<&WebGLProgram>) -> bool { program.map_or(false, |p| !p.is_deleted()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 fn IsRenderbuffer(&self, render_buffer: Option<&WebGLRenderbuffer>) -> bool { render_buffer.map_or(false, |buf| buf.ever_bound() && !buf.is_deleted()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn IsShader(&self, shader: Option<&WebGLShader>) -> bool { shader.map_or(false, |s| !s.is_deleted() || s.is_attached()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn IsTexture(&self, texture: Option<&WebGLTexture>) -> bool { texture.map_or(false, |tex| tex.target().is_some() && !tex.is_deleted()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn LineWidth(&self, width: f32) { if width.is_nan() || width <= 0f32 { return self.webgl_error(InvalidValue); } self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::LineWidth(width))) .unwrap() } // NOTE: Usage of this function could affect rendering while we keep using // readback to render to the page. // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn PixelStorei(&self, param_name: u32, param_value: i32) { let mut texture_settings = self.texture_unpacking_settings.get(); match param_name { constants::UNPACK_FLIP_Y_WEBGL => { if param_value != 0 { texture_settings.insert(FLIP_Y_AXIS) } else { texture_settings.remove(FLIP_Y_AXIS) } self.texture_unpacking_settings.set(texture_settings); return; }, constants::UNPACK_PREMULTIPLY_ALPHA_WEBGL => { if param_value != 0 { texture_settings.insert(PREMULTIPLY_ALPHA) } else { texture_settings.remove(PREMULTIPLY_ALPHA) } self.texture_unpacking_settings.set(texture_settings); return; }, constants::UNPACK_COLORSPACE_CONVERSION_WEBGL => { match param_value as u32 { constants::BROWSER_DEFAULT_WEBGL => texture_settings.insert(CONVERT_COLORSPACE), constants::NONE => texture_settings.remove(CONVERT_COLORSPACE), _ => return self.webgl_error(InvalidEnum), } self.texture_unpacking_settings.set(texture_settings); return; }, constants::UNPACK_ALIGNMENT | constants::PACK_ALIGNMENT => { match param_value { 1 | 2 | 4 | 8 => (), _ => return self.webgl_error(InvalidValue), } self.texture_unpacking_alignment.set(param_value as u32); return; }, _ => return self.webgl_error(InvalidEnum), } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn PolygonOffset(&self, factor: f32, units: f32) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::PolygonOffset(factor, units))) .unwrap() } #[allow(unsafe_code)] // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.12 unsafe fn ReadPixels(&self, cx: *mut JSContext, x: i32, y: i32, width: i32, height: i32, format: u32, pixel_type: u32, pixels: *mut JSObject) -> Fallible<()> { if pixels.is_null() { return Ok(self.webgl_error(InvalidValue)); } typedarray!(in(cx) let mut pixels_data: ArrayBufferView = pixels); let (array_type, mut data) = match { pixels_data.as_mut() } { Ok(data) => (data.get_array_type(), data.as_mut_slice()), Err(_) => return Err(Error::Type("Not an ArrayBufferView".to_owned())), }; if !self.validate_framebuffer_complete() { return Ok(()); } match array_type { Type::Uint8 => (), _ => return Ok(self.webgl_error(InvalidOperation)), } // From the WebGL specification, 5.14.12 Reading back pixels // // "Only two combinations of format and type are // accepted. The first is format RGBA and type // UNSIGNED_BYTE. The second is an implementation-chosen // format. The values of format and type for this format // may be determined by calling getParameter with the // symbolic constants IMPLEMENTATION_COLOR_READ_FORMAT // and IMPLEMENTATION_COLOR_READ_TYPE, respectively. The // implementation-chosen format may vary depending on the // format of the currently bound rendering // surface. Unsupported combinations of format and type // will generate an INVALID_OPERATION error." // // To avoid having to support general format packing math, we // always report RGBA/UNSIGNED_BYTE as our only supported // format. if format != constants::RGBA || pixel_type != constants::UNSIGNED_BYTE { return Ok(self.webgl_error(InvalidOperation)); } let cpp = 4; // "If pixels is non-null, but is not large enough to // retrieve all of the pixels in the specified rectangle // taking into account pixel store modes, an // INVALID_OPERATION error is generated." let stride = match width.checked_mul(cpp) { Some(stride) => stride, _ => return Ok(self.webgl_error(InvalidOperation)), }; match height.checked_mul(stride) { Some(size) if size <= data.len() as i32 => {} _ => return Ok(self.webgl_error(InvalidOperation)), } // "For any pixel lying outside the frame buffer, the // corresponding destination buffer range remains // untouched; see Reading Pixels Outside the // Framebuffer." let mut x = x; let mut y = y; let mut width = width; let mut height = height; let mut dst_offset = 0; if x < 0 { dst_offset += cpp * -x; width += x; x = 0; } if y < 0 { dst_offset += stride * -y; height += y; y = 0; } if width < 0 || height < 0 { return Ok(self.webgl_error(InvalidValue)); } match self.get_current_framebuffer_size() { Some((fb_width, fb_height)) => { if x + width > fb_width { width = fb_width - x; } if y + height > fb_height { height = fb_height - y; } } _ => return Ok(self.webgl_error(InvalidOperation)), }; let (sender, receiver) = webrender_traits::channel::msg_channel().unwrap(); self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::ReadPixels(x, y, width, height, format, pixel_type, sender))) .unwrap(); let result = receiver.recv().unwrap(); for i in 0..height { for j in 0..(width * cpp) { data[(dst_offset + i * stride + j) as usize] = result[(i * width * cpp + j) as usize]; } } Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn SampleCoverage(&self, value: f32, invert: bool) { self.ipc_renderer.send(CanvasMsg::WebGL(WebGLCommand::SampleCoverage(value, invert))).unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.4 fn Scissor(&self, x: i32, y: i32, width: i32, height: i32) { if width < 0 || height < 0 { return self.webgl_error(InvalidValue) } self.current_scissor.set((x, y, width, height)); self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Scissor(x, y, width, height))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn StencilFunc(&self, func: u32, ref_: i32, mask: u32) { match func { constants::NEVER | constants::LESS | constants::EQUAL | constants::LEQUAL | constants::GREATER | constants::NOTEQUAL | constants::GEQUAL | constants::ALWAYS => self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::StencilFunc(func, ref_, mask))) .unwrap(), _ => self.webgl_error(InvalidEnum), } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn StencilFuncSeparate(&self, face: u32, func: u32, ref_: i32, mask: u32) { match face { constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => (), _ => return self.webgl_error(InvalidEnum), } match func { constants::NEVER | constants::LESS | constants::EQUAL | constants::LEQUAL | constants::GREATER | constants::NOTEQUAL | constants::GEQUAL | constants::ALWAYS => self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::StencilFuncSeparate(face, func, ref_, mask))) .unwrap(), _ => self.webgl_error(InvalidEnum), } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn StencilMask(&self, mask: u32) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::StencilMask(mask))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn StencilMaskSeparate(&self, face: u32, mask: u32) { match face { constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::StencilMaskSeparate(face, mask))) .unwrap(), _ => return self.webgl_error(InvalidEnum), } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn StencilOp(&self, fail: u32, zfail: u32, zpass: u32) { if self.validate_stencil_actions(fail) && self.validate_stencil_actions(zfail) && self.validate_stencil_actions(zpass) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::StencilOp(fail, zfail, zpass))) .unwrap() } else { self.webgl_error(InvalidEnum) } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 fn StencilOpSeparate(&self, face: u32, fail: u32, zfail: u32, zpass: u32) { match face { constants::FRONT | constants::BACK | constants::FRONT_AND_BACK => (), _ => return self.webgl_error(InvalidEnum), } if self.validate_stencil_actions(fail) && self.validate_stencil_actions(zfail) && self.validate_stencil_actions(zpass) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::StencilOpSeparate(face, fail, zfail, zpass))) .unwrap() } else { self.webgl_error(InvalidEnum) } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn LinkProgram(&self, program: Option<&WebGLProgram>) { if let Some(program) = program { if let Err(e) = program.link() { self.webgl_error(e); } } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn ShaderSource(&self, shader: Option<&WebGLShader>, source: DOMString) { if let Some(shader) = shader { shader.set_source(source) } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn GetShaderSource(&self, shader: Option<&WebGLShader>) -> Option<DOMString> { shader.and_then(|s| s.source()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn Uniform1f(&self, uniform: Option<&WebGLUniformLocation>, val: f32) { if self.validate_uniform_parameters(uniform, UniformSetterType::Float, &[val]) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform1f(uniform.unwrap().id(), val))) .unwrap() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn Uniform1i(&self, uniform: Option<&WebGLUniformLocation>, val: i32) { if self.validate_uniform_parameters(uniform, UniformSetterType::Int, &[val]) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform1i(uniform.unwrap().id(), val))) .unwrap() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform1iv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Int32>(cx, data, ConversionBehavior::Default)); if self.validate_uniform_parameters(uniform, UniformSetterType::Int, &data_vec) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform1iv(uniform.unwrap().id(), data_vec))) .unwrap() } Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform1fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::Float, &data_vec) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform1fv(uniform.unwrap().id(), data_vec))) .unwrap() } Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn Uniform2f(&self, uniform: Option<&WebGLUniformLocation>, x: f32, y: f32) { if self.validate_uniform_parameters(uniform, UniformSetterType::FloatVec2, &[x, y]) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform2f(uniform.unwrap().id(), x, y))) .unwrap() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform2fv(&self,<|fim▁hole|> data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::FloatVec2, &data_vec) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform2fv(uniform.unwrap().id(), data_vec))) .unwrap() } Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn Uniform2i(&self, uniform: Option<&WebGLUniformLocation>, x: i32, y: i32) { if self.validate_uniform_parameters(uniform, UniformSetterType::IntVec2, &[x, y]) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform2i(uniform.unwrap().id(), x, y))) .unwrap() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform2iv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Int32>(cx, data, ConversionBehavior::Default)); if self.validate_uniform_parameters(uniform, UniformSetterType::IntVec2, &data_vec) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform2iv(uniform.unwrap().id(), data_vec))) .unwrap() } Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn Uniform3f(&self, uniform: Option<&WebGLUniformLocation>, x: f32, y: f32, z: f32) { if self.validate_uniform_parameters(uniform, UniformSetterType::FloatVec3, &[x, y, z]) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform3f(uniform.unwrap().id(), x, y, z))) .unwrap() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform3fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::FloatVec3, &data_vec) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform3fv(uniform.unwrap().id(), data_vec))) .unwrap() } Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn Uniform3i(&self, uniform: Option<&WebGLUniformLocation>, x: i32, y: i32, z: i32) { if self.validate_uniform_parameters(uniform, UniformSetterType::IntVec3, &[x, y, z]) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform3i(uniform.unwrap().id(), x, y, z))) .unwrap() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform3iv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Int32>(cx, data, ConversionBehavior::Default)); if self.validate_uniform_parameters(uniform, UniformSetterType::IntVec3, &data_vec) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform3iv(uniform.unwrap().id(), data_vec))) .unwrap() } Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn Uniform4i(&self, uniform: Option<&WebGLUniformLocation>, x: i32, y: i32, z: i32, w: i32) { if self.validate_uniform_parameters(uniform, UniformSetterType::IntVec4, &[x, y, z, w]) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform4i(uniform.unwrap().id(), x, y, z, w))) .unwrap() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform4iv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Int32>(cx, data, ConversionBehavior::Default)); if self.validate_uniform_parameters(uniform, UniformSetterType::IntVec4, &data_vec) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform4iv(uniform.unwrap().id(), data_vec))) .unwrap() } Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn Uniform4f(&self, uniform: Option<&WebGLUniformLocation>, x: f32, y: f32, z: f32, w: f32) { if self.validate_uniform_parameters(uniform, UniformSetterType::FloatVec4, &[x, y, z, w]) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform4f(uniform.unwrap().id(), x, y, z, w))) .unwrap() } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn Uniform4fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::FloatVec4, &data_vec) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Uniform4fv(uniform.unwrap().id(), data_vec))) .unwrap() } Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn UniformMatrix2fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, transpose: bool, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::FloatMat2, &data_vec) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::UniformMatrix2fv(uniform.unwrap().id(), transpose, data_vec))) .unwrap() } Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn UniformMatrix3fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, transpose: bool, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::FloatMat3, &data_vec) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::UniformMatrix3fv(uniform.unwrap().id(), transpose, data_vec))) .unwrap() } Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn UniformMatrix4fv(&self, cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>, transpose: bool, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); if self.validate_uniform_parameters(uniform, UniformSetterType::FloatMat4, &data_vec) { self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::UniformMatrix4fv(uniform.unwrap().id(), transpose, data_vec))) .unwrap() } Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn UseProgram(&self, program: Option<&WebGLProgram>) { if let Some(program) = program { match program.use_program() { Ok(()) => self.current_program.set(Some(program)), Err(e) => self.webgl_error(e), } } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn ValidateProgram(&self, program: Option<&WebGLProgram>) { if let Some(program) = program { if let Err(e) = program.validate() { self.webgl_error(e); } } } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn VertexAttrib1f(&self, indx: u32, x: f32) { self.vertex_attrib(indx, x, 0f32, 0f32, 1f32) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn VertexAttrib1fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); if data_vec.len() < 1 { return Ok(self.webgl_error(InvalidOperation)); } self.vertex_attrib(indx, data_vec[0], 0f32, 0f32, 1f32); Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn VertexAttrib2f(&self, indx: u32, x: f32, y: f32) { self.vertex_attrib(indx, x, y, 0f32, 1f32) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn VertexAttrib2fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); if data_vec.len() < 2 { return Ok(self.webgl_error(InvalidOperation)); } self.vertex_attrib(indx, data_vec[0], data_vec[1], 0f32, 1f32); Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn VertexAttrib3f(&self, indx: u32, x: f32, y: f32, z: f32) { self.vertex_attrib(indx, x, y, z, 1f32) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn VertexAttrib3fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); if data_vec.len() < 3 { return Ok(self.webgl_error(InvalidOperation)); } self.vertex_attrib(indx, data_vec[0], data_vec[1], data_vec[2], 1f32); Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn VertexAttrib4f(&self, indx: u32, x: f32, y: f32, z: f32, w: f32) { self.vertex_attrib(indx, x, y, z, w) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 #[allow(unsafe_code)] unsafe fn VertexAttrib4fv(&self, cx: *mut JSContext, indx: u32, data: *mut JSObject) -> Fallible<()> { assert!(!data.is_null()); let data_vec = try!(typed_array_or_sequence_to_vec::<Float32>(cx, data, ())); if data_vec.len() < 4 { return Ok(self.webgl_error(InvalidOperation)); } self.vertex_attrib(indx, data_vec[0], data_vec[1], data_vec[2], data_vec[3]); Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 fn VertexAttribPointer(&self, attrib_id: u32, size: i32, data_type: u32, normalized: bool, stride: i32, offset: i64) { if attrib_id > self.limits.max_vertex_attribs { return self.webgl_error(InvalidValue); } // GLES spec: If offset or stride is negative, an INVALID_VALUE error will be generated // WebGL spec: the maximum supported stride is 255 if stride < 0 || stride > 255 || offset < 0 { return self.webgl_error(InvalidValue); } if size < 1 || size > 4 { return self.webgl_error(InvalidValue); } if self.bound_buffer_array.get().is_none() { return self.webgl_error(InvalidOperation); } // stride and offset must be multiple of data_type match data_type { constants::BYTE | constants::UNSIGNED_BYTE => {}, constants::SHORT | constants::UNSIGNED_SHORT => { if offset % 2 > 0 || stride % 2 > 0 { return self.webgl_error(InvalidOperation); } }, constants::FLOAT => { if offset % 4 > 0 || stride % 4 > 0 { return self.webgl_error(InvalidOperation); } }, _ => return self.webgl_error(InvalidEnum), } let msg = CanvasMsg::WebGL( WebGLCommand::VertexAttribPointer(attrib_id, size, data_type, normalized, stride, offset as u32)); self.ipc_renderer.send(msg).unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.4 fn Viewport(&self, x: i32, y: i32, width: i32, height: i32) { if width < 0 || height < 0 { return self.webgl_error(InvalidValue) } self.ipc_renderer .send(CanvasMsg::WebGL(WebGLCommand::Viewport(x, y, width, height))) .unwrap() } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 #[allow(unsafe_code)] unsafe fn TexImage2D(&self, cx: *mut JSContext, target: u32, level: i32, internal_format: u32, width: i32, height: i32, border: i32, format: u32, data_type: u32, data_ptr: *mut JSObject) -> Fallible<()> { let data = if data_ptr.is_null() { None } else { Some(try!(fallible_array_buffer_view_to_vec(cx, data_ptr))) }; let validator = TexImage2DValidator::new(self, target, level, internal_format, width, height, border, format, data_type); let TexImage2DValidatorResult { texture, target, width, height, level, border, format, data_type, } = match validator.validate() { Ok(result) => result, Err(_) => return Ok(()), // NB: The validator sets the correct error for us. }; let unpacking_alignment = self.texture_unpacking_alignment.get(); let expected_byte_length = match { self.validate_tex_image_2d_data(width, height, format, data_type, unpacking_alignment, data_ptr, cx) } { Ok(byte_length) => byte_length, Err(()) => return Ok(()), }; // If data is null, a buffer of sufficient size // initialized to 0 is passed. let buff = match data { None => vec![0u8; expected_byte_length as usize], Some(data) => data, }; // From the WebGL spec: // // "If pixels is non-null but its size is less than what // is required by the specified width, height, format, // type, and pixel storage parameters, generates an // INVALID_OPERATION error." if buff.len() < expected_byte_length as usize { return Ok(self.webgl_error(InvalidOperation)); } self.tex_image_2d(texture, target, data_type, format, level, width, height, border, unpacking_alignment, buff); Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn TexImage2D_(&self, target: u32, level: i32, internal_format: u32, format: u32, data_type: u32, source: Option<ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement>) -> Fallible<()> { // Get pixels from image source let (pixels, size) = match self.get_image_pixels(source) { Ok((pixels, size)) => (pixels, size), Err(_) => return Ok(()), }; let validator = TexImage2DValidator::new(self, target, level, internal_format, size.width, size.height, 0, format, data_type); let TexImage2DValidatorResult { texture, target, width, height, level, border, format, data_type, } = match validator.validate() { Ok(result) => result, Err(_) => return Ok(()), // NB: The validator sets the correct error for us. }; let pixels = self.rgba8_image_to_tex_image_data(format, data_type, pixels); self.tex_image_2d(texture, target, data_type, format, level, width, height, border, 1, pixels); Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 #[allow(unsafe_code)] unsafe fn TexSubImage2D(&self, cx: *mut JSContext, target: u32, level: i32, xoffset: i32, yoffset: i32, width: i32, height: i32, format: u32, data_type: u32, data_ptr: *mut JSObject) -> Fallible<()> { let data = if data_ptr.is_null() { None } else { Some(try!(fallible_array_buffer_view_to_vec(cx, data_ptr))) }; let validator = TexImage2DValidator::new(self, target, level, format, width, height, 0, format, data_type); let TexImage2DValidatorResult { texture, target, width, height, level, format, data_type, .. } = match validator.validate() { Ok(result) => result, Err(_) => return Ok(()), // NB: The validator sets the correct error for us. }; let unpacking_alignment = self.texture_unpacking_alignment.get(); let expected_byte_length = match { self.validate_tex_image_2d_data(width, height, format, data_type, unpacking_alignment, data_ptr, cx) } { Ok(byte_length) => byte_length, Err(()) => return Ok(()), }; // If data is null, a buffer of sufficient size // initialized to 0 is passed. let buff = match data { None => vec![0u8; expected_byte_length as usize], Some(data) => data, }; // From the WebGL spec: // // "If pixels is non-null but its size is less than what // is required by the specified width, height, format, // type, and pixel storage parameters, generates an // INVALID_OPERATION error." if buff.len() < expected_byte_length as usize { return Ok(self.webgl_error(InvalidOperation)); } self.tex_sub_image_2d(texture, target, level, xoffset, yoffset, width, height, format, data_type, unpacking_alignment, buff); Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn TexSubImage2D_(&self, target: u32, level: i32, xoffset: i32, yoffset: i32, format: u32, data_type: u32, source: Option<ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement>) -> Fallible<()> { let (pixels, size) = match self.get_image_pixels(source) { Ok((pixels, size)) => (pixels, size), Err(_) => return Ok(()), }; let validator = TexImage2DValidator::new(self, target, level, format, size.width, size.height, 0, format, data_type); let TexImage2DValidatorResult { texture, target, width, height, level, format, data_type, .. } = match validator.validate() { Ok(result) => result, Err(_) => return Ok(()), // NB: The validator sets the correct error for us. }; let pixels = self.rgba8_image_to_tex_image_data(format, data_type, pixels); self.tex_sub_image_2d(texture, target, level, xoffset, yoffset, width, height, format, data_type, 1, pixels); Ok(()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn TexParameterf(&self, target: u32, name: u32, value: f32) { self.tex_parameter(target, name, TexParameterValue::Float(value)) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn TexParameteri(&self, target: u32, name: u32, value: i32) { self.tex_parameter(target, name, TexParameterValue::Int(value)) } fn CheckFramebufferStatus(&self, target: u32) -> u32 { // From the GLES 2.0.25 spec, 4.4 ("Framebuffer Objects"): // // "If target is not FRAMEBUFFER, INVALID_ENUM is // generated. If CheckFramebufferStatus generates an // error, 0 is returned." if target != constants::FRAMEBUFFER { self.webgl_error(InvalidEnum); return 0; } match self.bound_framebuffer.get() { Some(fb) => return fb.check_status(), None => return constants::FRAMEBUFFER_COMPLETE, } } fn RenderbufferStorage(&self, target: u32, internal_format: u32, width: i32, height: i32) { // From the GLES 2.0.25 spec: // // "target must be RENDERBUFFER." if target != constants::RENDERBUFFER { return self.webgl_error(InvalidOperation) } // From the GLES 2.0.25 spec: // // "If either width or height is greater than the value of // MAX_RENDERBUFFER_SIZE , the error INVALID_VALUE is // generated." // // and we have to throw out negative-size values as well just // like for TexImage. // // FIXME: Handle max_renderbuffer_size, which doesn't seem to // be in limits. if width < 0 || height < 0 { return self.webgl_error(InvalidValue); } match self.bound_renderbuffer.get() { Some(rb) => { handle_potential_webgl_error!(self, rb.storage(internal_format, width, height)); if let Some(fb) = self.bound_framebuffer.get() { fb.invalidate_renderbuffer(&*rb); } } None => self.webgl_error(InvalidOperation), }; // FIXME: We need to clear the renderbuffer before it can be // accessed. See https://github.com/servo/servo/issues/13710 } fn FramebufferRenderbuffer(&self, target: u32, attachment: u32, renderbuffertarget: u32, rb: Option<&WebGLRenderbuffer>) { if target != constants::FRAMEBUFFER || renderbuffertarget != constants::RENDERBUFFER { return self.webgl_error(InvalidEnum); } match self.bound_framebuffer.get() { Some(fb) => handle_potential_webgl_error!(self, fb.renderbuffer(attachment, rb)), None => self.webgl_error(InvalidOperation), }; } fn FramebufferTexture2D(&self, target: u32, attachment: u32, textarget: u32, texture: Option<&WebGLTexture>, level: i32) { if target != constants::FRAMEBUFFER { return self.webgl_error(InvalidEnum); } match self.bound_framebuffer.get() { Some(fb) => handle_potential_webgl_error!(self, fb.texture2d(attachment, textarget, texture, level)), None => self.webgl_error(InvalidOperation), }; } } pub trait LayoutCanvasWebGLRenderingContextHelpers { #[allow(unsafe_code)] unsafe fn get_ipc_renderer(&self) -> IpcSender<CanvasMsg>; } impl LayoutCanvasWebGLRenderingContextHelpers for LayoutJS<WebGLRenderingContext> { #[allow(unsafe_code)] unsafe fn get_ipc_renderer(&self) -> IpcSender<CanvasMsg> { (*self.unsafe_get()).ipc_renderer.clone() } } #[derive(Debug, PartialEq)] pub enum UniformSetterType { Int, IntVec2, IntVec3, IntVec4, Float, FloatVec2, FloatVec3, FloatVec4, FloatMat2, FloatMat3, FloatMat4, } impl UniformSetterType { pub fn element_count(&self) -> usize { match *self { UniformSetterType::Int => 1, UniformSetterType::IntVec2 => 2, UniformSetterType::IntVec3 => 3, UniformSetterType::IntVec4 => 4, UniformSetterType::Float => 1, UniformSetterType::FloatVec2 => 2, UniformSetterType::FloatVec3 => 3, UniformSetterType::FloatVec4 => 4, UniformSetterType::FloatMat2 => 4, UniformSetterType::FloatMat3 => 9, UniformSetterType::FloatMat4 => 16, } } }<|fim▁end|>
cx: *mut JSContext, uniform: Option<&WebGLUniformLocation>,
<|file_name|>test_wheel.py<|end_file_name|><|fim▁begin|>"""Tests for wheel binary packages and .dist-info.""" import os import pytest from mock import patch, Mock from pip._vendor import pkg_resources from pip import pep425tags, wheel from pip.exceptions import InvalidWheelFilename, UnsupportedWheel from pip.utils import unpack_file def test_get_entrypoints(tmpdir): with open(str(tmpdir.join("entry_points.txt")), "w") as fp: fp.write(""" [console_scripts] pip = pip.main:pip """) assert wheel.get_entrypoints(str(tmpdir.join("entry_points.txt"))) == ( {"pip": "pip.main:pip"}, {}, ) def test_uninstallation_paths(): class dist(object): def get_metadata_lines(self, record): return ['file.py,,', 'file.pyc,,', 'file.so,,', 'nopyc.py'] location = '' d = dist() paths = list(wheel.uninstallation_paths(d)) expected = ['file.py', 'file.pyc', 'file.so', 'nopyc.py', 'nopyc.pyc'] assert paths == expected # Avoid an easy 'unique generator' bug paths2 = list(wheel.uninstallation_paths(d)) assert paths2 == paths def test_wheel_version(tmpdir, data): future_wheel = 'futurewheel-1.9-py2.py3-none-any.whl' broken_wheel = 'brokenwheel-1.0-py2.py3-none-any.whl' future_version = (1, 9) unpack_file(data.packages.join(future_wheel), tmpdir + 'future', None, None) unpack_file(data.packages.join(broken_wheel), tmpdir + 'broken', None, None) assert wheel.wheel_version(tmpdir + 'future') == future_version assert not wheel.wheel_version(tmpdir + 'broken') def test_check_compatibility(): name = 'test' vc = wheel.VERSION_COMPATIBLE # Major version is higher - should be incompatible higher_v = (vc[0] + 1, vc[1]) # test raises with correct error with pytest.raises(UnsupportedWheel) as e: wheel.check_compatibility(higher_v, name) assert 'is not compatible' in str(e) # Should only log.warn - minor version is greator higher_v = (vc[0], vc[1] + 1) wheel.check_compatibility(higher_v, name) # These should work fine wheel.check_compatibility(wheel.VERSION_COMPATIBLE, name) # E.g if wheel to install is 1.0 and we support up to 1.2 lower_v = (vc[0], max(0, vc[1] - 1)) wheel.check_compatibility(lower_v, name) class TestWheelFile(object): def test_std_wheel_pattern(self): w = wheel.Wheel('simple-1.1.1-py2-none-any.whl') assert w.name == 'simple' assert w.version == '1.1.1' assert w.pyversions == ['py2'] assert w.abis == ['none'] assert w.plats == ['any'] def test_wheel_pattern_multi_values(self): w = wheel.Wheel('simple-1.1-py2.py3-abi1.abi2-any.whl') assert w.name == 'simple' assert w.version == '1.1' assert w.pyversions == ['py2', 'py3'] assert w.abis == ['abi1', 'abi2'] assert w.plats == ['any'] def test_wheel_with_build_tag(self): # pip doesn't do anything with build tags, but theoretically, we might # see one, in this case the build tag = '4' w = wheel.Wheel('simple-1.1-4-py2-none-any.whl') assert w.name == 'simple' assert w.version == '1.1' assert w.pyversions == ['py2'] assert w.abis == ['none'] assert w.plats == ['any']<|fim▁hole|> assert w.version == '1' def test_missing_version_raises(self): with pytest.raises(InvalidWheelFilename): wheel.Wheel('Cython-cp27-none-linux_x86_64.whl') def test_invalid_filename_raises(self): with pytest.raises(InvalidWheelFilename): wheel.Wheel('invalid.whl') def test_supported_single_version(self): """ Test single-version wheel is known to be supported """ w = wheel.Wheel('simple-0.1-py2-none-any.whl') assert w.supported(tags=[('py2', 'none', 'any')]) def test_supported_multi_version(self): """ Test multi-version wheel is known to be supported """ w = wheel.Wheel('simple-0.1-py2.py3-none-any.whl') assert w.supported(tags=[('py3', 'none', 'any')]) def test_not_supported_version(self): """ Test unsupported wheel is known to be unsupported """ w = wheel.Wheel('simple-0.1-py2-none-any.whl') assert not w.supported(tags=[('py1', 'none', 'any')]) @patch('sys.platform', 'darwin') @patch('pip.pep425tags.get_abbr_impl', lambda: 'cp') @patch('pip.pep425tags.get_platform', lambda: 'macosx_10_9_intel') def test_supported_osx_version(self): """ Wheels built for OS X 10.6 are supported on 10.9 """ tags = pep425tags.get_supported(['27'], False) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_6_intel.whl') assert w.supported(tags=tags) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_9_intel.whl') assert w.supported(tags=tags) @patch('sys.platform', 'darwin') @patch('pip.pep425tags.get_abbr_impl', lambda: 'cp') @patch('pip.pep425tags.get_platform', lambda: 'macosx_10_6_intel') def test_not_supported_osx_version(self): """ Wheels built for OS X 10.9 are not supported on 10.6 """ tags = pep425tags.get_supported(['27'], False) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_9_intel.whl') assert not w.supported(tags=tags) @patch('sys.platform', 'darwin') @patch('pip.pep425tags.get_abbr_impl', lambda: 'cp') def test_supported_multiarch_darwin(self): """ Multi-arch wheels (intel) are supported on components (i386, x86_64) """ with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_universal'): universal = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_intel'): intel = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_x86_64'): x64 = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_i386'): i386 = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_ppc'): ppc = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_ppc64'): ppc64 = pep425tags.get_supported(['27'], False) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_5_intel.whl') assert w.supported(tags=intel) assert w.supported(tags=x64) assert w.supported(tags=i386) assert not w.supported(tags=universal) assert not w.supported(tags=ppc) assert not w.supported(tags=ppc64) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_5_universal.whl') assert w.supported(tags=universal) assert w.supported(tags=intel) assert w.supported(tags=x64) assert w.supported(tags=i386) assert w.supported(tags=ppc) assert w.supported(tags=ppc64) @patch('sys.platform', 'darwin') @patch('pip.pep425tags.get_abbr_impl', lambda: 'cp') def test_not_supported_multiarch_darwin(self): """ Single-arch wheels (x86_64) are not supported on multi-arch (intel) """ with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_universal'): universal = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_intel'): intel = pep425tags.get_supported(['27'], False) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_5_i386.whl') assert not w.supported(tags=intel) assert not w.supported(tags=universal) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_5_x86_64.whl') assert not w.supported(tags=intel) assert not w.supported(tags=universal) def test_support_index_min(self): """ Test results from `support_index_min` """ tags = [ ('py2', 'none', 'TEST'), ('py2', 'TEST', 'any'), ('py2', 'none', 'any'), ] w = wheel.Wheel('simple-0.1-py2-none-any.whl') assert w.support_index_min(tags=tags) == 2 w = wheel.Wheel('simple-0.1-py2-none-TEST.whl') assert w.support_index_min(tags=tags) == 0 def test_support_index_min_none(self): """ Test `support_index_min` returns None, when wheel not supported """ w = wheel.Wheel('simple-0.1-py2-none-any.whl') assert w.support_index_min(tags=[]) is None def test_unpack_wheel_no_flatten(self): from pip import utils from tempfile import mkdtemp from shutil import rmtree filepath = '../data/packages/meta-1.0-py2.py3-none-any.whl' if not os.path.exists(filepath): pytest.skip("%s does not exist" % filepath) try: tmpdir = mkdtemp() utils.unpack_file(filepath, tmpdir, 'application/zip', None) assert os.path.isdir(os.path.join(tmpdir, 'meta-1.0.dist-info')) finally: rmtree(tmpdir) pass def test_purelib_platlib(self, data): """ Test the "wheel is purelib/platlib" code. """ packages = [ ("pure_wheel", data.packages.join("pure_wheel-1.7"), True), ("plat_wheel", data.packages.join("plat_wheel-1.7"), False), ] for name, path, expected in packages: assert wheel.root_is_purelib(name, path) == expected def test_version_underscore_conversion(self): """ Test that we convert '_' to '-' for versions parsed out of wheel filenames """ w = wheel.Wheel('simple-0.1_1-py2-none-any.whl') assert w.version == '0.1-1' class TestPEP425Tags(object): def test_broken_sysconfig(self): """ Test that pep425tags still works when sysconfig is broken. Can be a problem on Python 2.7 Issue #1074. """ import pip.pep425tags def raises_ioerror(var): raise IOError("I have the wrong path!") with patch('pip.pep425tags.sysconfig.get_config_var', raises_ioerror): assert len(pip.pep425tags.get_supported()) class TestMoveWheelFiles(object): """ Tests for moving files from wheel src to scheme paths """ def prep(self, data, tmpdir): self.name = 'sample' self.wheelpath = data.packages.join( 'sample-1.2.0-py2.py3-none-any.whl') self.req = pkg_resources.Requirement.parse('sample') self.src = os.path.join(tmpdir, 'src') self.dest = os.path.join(tmpdir, 'dest') unpack_file(self.wheelpath, self.src, None, None) self.scheme = { 'scripts': os.path.join(self.dest, 'bin'), 'purelib': os.path.join(self.dest, 'lib'), 'data': os.path.join(self.dest, 'data'), } self.src_dist_info = os.path.join( self.src, 'sample-1.2.0.dist-info') self.dest_dist_info = os.path.join( self.scheme['purelib'], 'sample-1.2.0.dist-info') def assert_installed(self): # lib assert os.path.isdir( os.path.join(self.scheme['purelib'], 'sample')) # dist-info metadata = os.path.join(self.dest_dist_info, 'METADATA') assert os.path.isfile(metadata) # data files data_file = os.path.join(self.scheme['data'], 'my_data', 'data_file') assert os.path.isfile(data_file) # package data pkg_data = os.path.join( self.scheme['purelib'], 'sample', 'package_data.dat') assert os.path.isfile(pkg_data) def test_std_install(self, data, tmpdir): self.prep(data, tmpdir) wheel.move_wheel_files( self.name, self.req, self.src, scheme=self.scheme) self.assert_installed() def test_dist_info_contains_empty_dir(self, data, tmpdir): """ Test that empty dirs are not installed """ # e.g. https://github.com/pypa/pip/issues/1632#issuecomment-38027275 self.prep(data, tmpdir) src_empty_dir = os.path.join( self.src_dist_info, 'empty_dir', 'empty_dir') os.makedirs(src_empty_dir) assert os.path.isdir(src_empty_dir) wheel.move_wheel_files( self.name, self.req, self.src, scheme=self.scheme) self.assert_installed() assert not os.path.isdir( os.path.join(self.dest_dist_info, 'empty_dir')) class TestWheelBuilder(object): def test_skip_building_wheels(self, caplog): with patch('pip.wheel.WheelBuilder._build_one') as mock_build_one: wheel_req = Mock(is_wheel=True, editable=False) reqset = Mock(requirements=Mock(values=lambda: [wheel_req]), wheel_download_dir='/wheel/dir') wb = wheel.WheelBuilder(reqset, Mock()) wb.build() assert "due to already being wheel" in caplog.text() assert mock_build_one.mock_calls == [] def test_skip_building_editables(self, caplog): with patch('pip.wheel.WheelBuilder._build_one') as mock_build_one: editable_req = Mock(editable=True, is_wheel=False) reqset = Mock(requirements=Mock(values=lambda: [editable_req]), wheel_download_dir='/wheel/dir') wb = wheel.WheelBuilder(reqset, Mock()) wb.build() assert "due to being editable" in caplog.text() assert mock_build_one.mock_calls == []<|fim▁end|>
def test_single_digit_version(self): w = wheel.Wheel('simple-1-py2-none-any.whl')
<|file_name|>long64.rs<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
#pragma version(1) #pragma rs java_package_name(foo) long l = 1L << 32;
<|file_name|>window.rs<|end_file_name|><|fim▁begin|>/* 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/. */ //! A windowing implementation using glutin. use compositing::compositor_task::{self, CompositorProxy, CompositorReceiver}; use compositing::windowing::{WindowEvent, WindowMethods}; use geom::scale_factor::ScaleFactor; use geom::size::{Size2D, TypedSize2D}; use gleam::gl; use glutin; use layers::geometry::DevicePixel; use layers::platform::surface::NativeGraphicsMetadata; use msg::constellation_msg; use msg::constellation_msg::Key; use net::net_error_list::NetError; use std::rc::Rc; use std::sync::mpsc::{channel, Sender}; use url::Url; use util::cursor::Cursor; use util::geometry::ScreenPx; use NestedEventLoopListener; #[cfg(feature = "window")] use compositing::windowing::{MouseWindowEvent, WindowNavigateMsg}; #[cfg(feature = "window")] use geom::point::Point2D; #[cfg(feature = "window")] use glutin::{Api, ElementState, Event, GlRequest, MouseButton, VirtualKeyCode}; #[cfg(feature = "window")] use msg::constellation_msg::{KeyState, CONTROL, SHIFT, ALT}; #[cfg(feature = "window")] use std::cell::{Cell, RefCell}; #[cfg(feature = "window")] use util::opts; #[cfg(all(feature = "headless", target_os="linux"))] use std::ptr; #[cfg(feature = "window")] static mut g_nested_event_loop_listener: Option<*mut (NestedEventLoopListener + 'static)> = None; #[cfg(feature = "window")] bitflags! { flags KeyModifiers: u8 { const LEFT_CONTROL = 1, const RIGHT_CONTROL = 2, const LEFT_SHIFT = 4, const RIGHT_SHIFT = 8, const LEFT_ALT = 16, const RIGHT_ALT = 32, } } /// The type of a window. #[cfg(feature = "window")] pub struct Window { window: glutin::Window, mouse_down_button: Cell<Option<glutin::MouseButton>>, mouse_down_point: Cell<Point2D<i32>>, event_queue: RefCell<Vec<WindowEvent>>, mouse_pos: Cell<Point2D<i32>>, key_modifiers: Cell<KeyModifiers>, } #[cfg(feature = "window")] impl Window { pub fn new(is_foreground: bool, window_size: TypedSize2D<DevicePixel, u32>, parent: glutin::WindowID) -> Rc<Window> { let mut glutin_window = glutin::WindowBuilder::new() .with_title("Servo".to_string()) .with_dimensions(window_size.to_untyped().width, window_size.to_untyped().height) .with_gl(Window::gl_version()) .with_visibility(is_foreground) .with_parent(parent) .build() .unwrap(); unsafe { glutin_window.make_current() }; glutin_window.set_window_resize_callback(Some(Window::nested_window_resize as fn(u32, u32))); Window::load_gl_functions(&glutin_window); let window = Window { window: glutin_window, event_queue: RefCell::new(vec!()), mouse_down_button: Cell::new(None), mouse_down_point: Cell::new(Point2D::new(0, 0)), mouse_pos: Cell::new(Point2D::new(0, 0)), key_modifiers: Cell::new(KeyModifiers::empty()), }; gl::clear_color(0.6, 0.6, 0.6, 1.0); gl::clear(gl::COLOR_BUFFER_BIT); gl::finish(); window.present(); Rc::new(window) } pub fn platform_window(&self) -> glutin::WindowID { unsafe { self.window.platform_window() } } fn nested_window_resize(width: u32, height: u32) { unsafe { match g_nested_event_loop_listener { None => {} Some(listener) => { (*listener).handle_event_from_nested_event_loop( WindowEvent::Resize(Size2D::typed(width, height))); } } } } #[cfg(not(target_os="android"))] fn gl_version() -> GlRequest { GlRequest::Specific(Api::OpenGl, (3, 0)) } #[cfg(target_os="android")] fn gl_version() -> GlRequest { GlRequest::Specific(Api::OpenGlEs, (2, 0)) } #[cfg(not(target_os="android"))] fn load_gl_functions(window: &glutin::Window) { gl::load_with(|s| window.get_proc_address(s)); } #[cfg(target_os="android")] fn load_gl_functions(_: &glutin::Window) { } fn handle_window_event(&self, event: glutin::Event) -> bool { match event { Event::KeyboardInput(element_state, _scan_code, virtual_key_code) => { if virtual_key_code.is_some() { let virtual_key_code = virtual_key_code.unwrap(); match (element_state, virtual_key_code) { (_, VirtualKeyCode::LControl) => self.toggle_modifier(LEFT_CONTROL), (_, VirtualKeyCode::RControl) => self.toggle_modifier(RIGHT_CONTROL), (_, VirtualKeyCode::LShift) => self.toggle_modifier(LEFT_SHIFT), (_, VirtualKeyCode::RShift) => self.toggle_modifier(RIGHT_SHIFT), (_, VirtualKeyCode::LAlt) => self.toggle_modifier(LEFT_ALT), (_, VirtualKeyCode::RAlt) => self.toggle_modifier(RIGHT_ALT), (ElementState::Pressed, VirtualKeyCode::Escape) => return true, (_, key_code) => { match Window::glutin_key_to_script_key(key_code) { Ok(key) => { let state = match element_state { ElementState::Pressed => KeyState::Pressed, ElementState::Released => KeyState::Released, }; let modifiers = Window::glutin_mods_to_script_mods(self.key_modifiers.get()); self.event_queue.borrow_mut().push(WindowEvent::KeyEvent(key, state, modifiers)); } _ => {} } } } } } Event::Resized(width, height) => { self.event_queue.borrow_mut().push(WindowEvent::Resize(Size2D::typed(width, height))); } Event::MouseInput(element_state, mouse_button) => { if mouse_button == MouseButton::Left || mouse_button == MouseButton::Right { let mouse_pos = self.mouse_pos.get(); self.handle_mouse(mouse_button, element_state, mouse_pos.x, mouse_pos.y); } } Event::MouseMoved((x, y)) => { self.mouse_pos.set(Point2D::new(x, y)); self.event_queue.borrow_mut().push( WindowEvent::MouseWindowMoveEventClass(Point2D::typed(x as f32, y as f32))); } Event::MouseWheel(delta) => { if self.ctrl_pressed() { // Ctrl-Scrollwheel simulates a "pinch zoom" gesture. if delta < 0 { self.event_queue.borrow_mut().push(WindowEvent::PinchZoom(1.0/1.1)); } else if delta > 0 { self.event_queue.borrow_mut().push(WindowEvent::PinchZoom(1.1)); } } else { let dx = 0.0; let dy = delta as f32; self.scroll_window(dx, dy); } }, Event::Refresh => { self.event_queue.borrow_mut().push(WindowEvent::Refresh); } _ => {} } false } #[inline] fn ctrl_pressed(&self) -> bool { self.key_modifiers.get().intersects(LEFT_CONTROL | RIGHT_CONTROL) } fn toggle_modifier(&self, modifier: KeyModifiers) { let mut modifiers = self.key_modifiers.get(); modifiers.toggle(modifier); self.key_modifiers.set(modifiers); } /// Helper function to send a scroll event. fn scroll_window(&self, dx: f32, dy: f32) { let mouse_pos = self.mouse_pos.get(); let event = WindowEvent::Scroll(Point2D::typed(dx as f32, dy as f32), Point2D::typed(mouse_pos.x as i32, mouse_pos.y as i32)); self.event_queue.borrow_mut().push(event); } /// Helper function to handle a click fn handle_mouse(&self, button: glutin::MouseButton, action: glutin::ElementState, x: i32, y: i32) { use script_traits::MouseButton; // FIXME(tkuehn): max pixel dist should be based on pixel density let max_pixel_dist = 10f64; let event = match action { ElementState::Pressed => { self.mouse_down_point.set(Point2D::new(x, y)); self.mouse_down_button.set(Some(button)); MouseWindowEvent::MouseDown(MouseButton::Left, Point2D::typed(x as f32, y as f32)) } ElementState::Released => { let mouse_up_event = MouseWindowEvent::MouseUp(MouseButton::Left, Point2D::typed(x as f32, y as f32)); match self.mouse_down_button.get() { None => mouse_up_event, Some(but) if button == but => { let pixel_dist = self.mouse_down_point.get() - Point2D::new(x, y); let pixel_dist = ((pixel_dist.x * pixel_dist.x + pixel_dist.y * pixel_dist.y) as f64).sqrt(); if pixel_dist < max_pixel_dist { self.event_queue.borrow_mut().push(WindowEvent::MouseWindowEventClass(mouse_up_event)); MouseWindowEvent::Click(MouseButton::Left, Point2D::typed(x as f32, y as f32)) } else { mouse_up_event } }, Some(_) => mouse_up_event, } } }; self.event_queue.borrow_mut().push(WindowEvent::MouseWindowEventClass(event)); } #[cfg(target_os="macos")] fn handle_next_event(&self) -> bool { let event = self.window.wait_events().next().unwrap(); let mut close = self.handle_window_event(event); if !close { while let Some(event) = self.window.poll_events().next() { if self.handle_window_event(event) { close = true; break } } } close } #[cfg(any(target_os="linux", target_os="android"))] fn handle_next_event(&self) -> bool { use std::thread::sleep_ms; // TODO(gw): This is an awful hack to work around the // broken way we currently call X11 from multiple threads. // // On some (most?) X11 implementations, blocking here // with XPeekEvent results in the paint task getting stuck // in XGetGeometry randomly. When this happens the result // is that until you trigger the XPeekEvent to return // (by moving the mouse over the window) the paint task // never completes and you don't see the most recent // results. // // For now, poll events and sleep for ~1 frame if there // are no events. This means we don't spin the CPU at // 100% usage, but is far from ideal! // // See https://github.com/servo/servo/issues/5780 // let first_event = self.window.poll_events().next(); match first_event { Some(event) => { self.handle_window_event(event) } None => { sleep_ms(16); false } } } pub fn wait_events(&self) -> Vec<WindowEvent> { use std::mem; let mut events = mem::replace(&mut *self.event_queue.borrow_mut(), Vec::new()); let mut close_event = false; // When writing to a file then exiting, use event // polling so that we don't block on a GUI event // such as mouse click. if opts::get().output_file.is_some() { while let Some(event) = self.window.poll_events().next() { close_event = self.handle_window_event(event) || close_event; } } else { close_event = self.handle_next_event(); } if close_event || self.window.is_closed() { events.push(WindowEvent::Quit) } events.extend(mem::replace(&mut *self.event_queue.borrow_mut(), Vec::new()).into_iter()); events } pub unsafe fn set_nested_event_loop_listener( &self, listener: *mut (NestedEventLoopListener + 'static)) { g_nested_event_loop_listener = Some(listener) } pub unsafe fn remove_nested_event_loop_listener(&self) { g_nested_event_loop_listener = None } fn glutin_key_to_script_key(key: glutin::VirtualKeyCode) -> Result<constellation_msg::Key, ()> { // TODO(negge): add more key mappings match key { VirtualKeyCode::A => Ok(Key::A), VirtualKeyCode::B => Ok(Key::B), VirtualKeyCode::C => Ok(Key::C), VirtualKeyCode::D => Ok(Key::D), VirtualKeyCode::E => Ok(Key::E), VirtualKeyCode::F => Ok(Key::F), VirtualKeyCode::G => Ok(Key::G), VirtualKeyCode::H => Ok(Key::H), VirtualKeyCode::I => Ok(Key::I), VirtualKeyCode::J => Ok(Key::J), VirtualKeyCode::K => Ok(Key::K), VirtualKeyCode::L => Ok(Key::L), VirtualKeyCode::M => Ok(Key::M), VirtualKeyCode::N => Ok(Key::N), VirtualKeyCode::O => Ok(Key::O), VirtualKeyCode::P => Ok(Key::P), VirtualKeyCode::Q => Ok(Key::Q), VirtualKeyCode::R => Ok(Key::R), VirtualKeyCode::S => Ok(Key::S), VirtualKeyCode::T => Ok(Key::T), VirtualKeyCode::U => Ok(Key::U), VirtualKeyCode::V => Ok(Key::V), VirtualKeyCode::W => Ok(Key::W), VirtualKeyCode::X => Ok(Key::X), VirtualKeyCode::Y => Ok(Key::Y), VirtualKeyCode::Z => Ok(Key::Z), VirtualKeyCode::Numpad0 => Ok(Key::Kp0), VirtualKeyCode::Numpad1 => Ok(Key::Kp1), VirtualKeyCode::Numpad2 => Ok(Key::Kp2), VirtualKeyCode::Numpad3 => Ok(Key::Kp3), VirtualKeyCode::Numpad4 => Ok(Key::Kp4), VirtualKeyCode::Numpad5 => Ok(Key::Kp5), VirtualKeyCode::Numpad6 => Ok(Key::Kp6), VirtualKeyCode::Numpad7 => Ok(Key::Kp7), VirtualKeyCode::Numpad8 => Ok(Key::Kp8), VirtualKeyCode::Numpad9 => Ok(Key::Kp9), VirtualKeyCode::Key0 => Ok(Key::Num0), VirtualKeyCode::Key1 => Ok(Key::Num1), VirtualKeyCode::Key2 => Ok(Key::Num2), VirtualKeyCode::Key3 => Ok(Key::Num3), VirtualKeyCode::Key4 => Ok(Key::Num4), VirtualKeyCode::Key5 => Ok(Key::Num5), VirtualKeyCode::Key6 => Ok(Key::Num6), VirtualKeyCode::Key7 => Ok(Key::Num7), VirtualKeyCode::Key8 => Ok(Key::Num8), VirtualKeyCode::Key9 => Ok(Key::Num9), VirtualKeyCode::Return => Ok(Key::Enter), VirtualKeyCode::Space => Ok(Key::Space), VirtualKeyCode::Escape => Ok(Key::Escape), VirtualKeyCode::Equals => Ok(Key::Equal), VirtualKeyCode::Minus => Ok(Key::Minus), VirtualKeyCode::Back => Ok(Key::Backspace), VirtualKeyCode::PageDown => Ok(Key::PageDown), VirtualKeyCode::PageUp => Ok(Key::PageUp), VirtualKeyCode::Insert => Ok(Key::Insert), VirtualKeyCode::Home => Ok(Key::Home), VirtualKeyCode::Delete => Ok(Key::Delete), VirtualKeyCode::End => Ok(Key::End), VirtualKeyCode::Left => Ok(Key::Left), VirtualKeyCode::Up => Ok(Key::Up), VirtualKeyCode::Right => Ok(Key::Right), VirtualKeyCode::Down => Ok(Key::Down), VirtualKeyCode::Apostrophe => Ok(Key::Apostrophe), VirtualKeyCode::Backslash => Ok(Key::Backslash), VirtualKeyCode::Comma => Ok(Key::Comma), VirtualKeyCode::Grave => Ok(Key::GraveAccent), VirtualKeyCode::LBracket => Ok(Key::LeftBracket), VirtualKeyCode::Period => Ok(Key::Period), VirtualKeyCode::RBracket => Ok(Key::RightBracket), VirtualKeyCode::Semicolon => Ok(Key::Semicolon), VirtualKeyCode::Slash => Ok(Key::Slash), VirtualKeyCode::Tab => Ok(Key::Tab), VirtualKeyCode::Subtract => Ok(Key::Minus), _ => Err(()), } } fn glutin_mods_to_script_mods(modifiers: KeyModifiers) -> constellation_msg::KeyModifiers { let mut result = constellation_msg::KeyModifiers::from_bits(0).unwrap(); if modifiers.intersects(LEFT_SHIFT | RIGHT_SHIFT) { result.insert(SHIFT); } if modifiers.intersects(LEFT_CONTROL | RIGHT_CONTROL) { result.insert(CONTROL); } if modifiers.intersects(LEFT_ALT | RIGHT_ALT) { result.insert(ALT); } result } } // WindowProxy is not implemented for android yet #[cfg(all(feature = "window", target_os="android"))] fn create_window_proxy(_: &Rc<Window>) -> Option<glutin::WindowProxy> { None } #[cfg(all(feature = "window", not(target_os="android")))] fn create_window_proxy(window: &Rc<Window>) -> Option<glutin::WindowProxy> { Some(window.window.create_window_proxy()) } #[cfg(feature = "window")] impl WindowMethods for Window { fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, u32> { let scale_factor = self.window.hidpi_factor() as u32; let (width, height) = self.window.get_inner_size().unwrap(); Size2D::typed(width * scale_factor, height * scale_factor) } fn size(&self) -> TypedSize2D<ScreenPx, f32> { let (width, height) = self.window.get_inner_size().unwrap(); Size2D::typed(width as f32, height as f32) } fn present(&self) { self.window.swap_buffers() } fn create_compositor_channel(window: &Option<Rc<Window>>) -> (Box<CompositorProxy+Send>, Box<CompositorReceiver>) { let (sender, receiver) = channel(); let window_proxy = match window { &Some(ref window) => create_window_proxy(window), &None => None, }; (box GlutinCompositorProxy { sender: sender, window_proxy: window_proxy, } as Box<CompositorProxy+Send>, box receiver as Box<CompositorReceiver>) } fn hidpi_factor(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32> { ScaleFactor::new(self.window.hidpi_factor()) } fn set_page_title(&self, title: Option<String>) { let title = match title { Some(ref title) if title.len() > 0 => &**title, _ => "untitled", }; let title = format!("{} - Servo", title); self.window.set_title(&title); } fn set_page_url(&self, _: Url) { } fn load_start(&self, _: bool, _: bool) { } fn load_end(&self, _: bool, _: bool) { } fn load_error(&self, _: NetError, _: String) { } fn head_parsed(&self) { } /// Has no effect on Android. fn set_cursor(&self, c: Cursor) { use glutin::MouseCursor; let glutin_cursor = match c { Cursor::NoCursor => MouseCursor::NoneCursor, Cursor::DefaultCursor => MouseCursor::Default, Cursor::PointerCursor => MouseCursor::Hand, Cursor::ContextMenuCursor => MouseCursor::ContextMenu, Cursor::HelpCursor => MouseCursor::Help, Cursor::ProgressCursor => MouseCursor::Progress, Cursor::WaitCursor => MouseCursor::Wait, Cursor::CellCursor => MouseCursor::Cell, Cursor::CrosshairCursor => MouseCursor::Crosshair, Cursor::TextCursor => MouseCursor::Text, Cursor::VerticalTextCursor => MouseCursor::VerticalText, Cursor::AliasCursor => MouseCursor::Alias, Cursor::CopyCursor => MouseCursor::Copy, Cursor::MoveCursor => MouseCursor::Move, Cursor::NoDropCursor => MouseCursor::NoDrop, Cursor::NotAllowedCursor => MouseCursor::NotAllowed, Cursor::GrabCursor => MouseCursor::Grab, Cursor::GrabbingCursor => MouseCursor::Grabbing, Cursor::EResizeCursor => MouseCursor::EResize, Cursor::NResizeCursor => MouseCursor::NResize, Cursor::NeResizeCursor => MouseCursor::NeResize, Cursor::NwResizeCursor => MouseCursor::NwResize, Cursor::SResizeCursor => MouseCursor::SResize, Cursor::SeResizeCursor => MouseCursor::SeResize, Cursor::SwResizeCursor => MouseCursor::SwResize, Cursor::WResizeCursor => MouseCursor::WResize, Cursor::EwResizeCursor => MouseCursor::EwResize, Cursor::NsResizeCursor => MouseCursor::NsResize, Cursor::NeswResizeCursor => MouseCursor::NeswResize, Cursor::NwseResizeCursor => MouseCursor::NwseResize, Cursor::ColResizeCursor => MouseCursor::ColResize, Cursor::RowResizeCursor => MouseCursor::RowResize, Cursor::AllScrollCursor => MouseCursor::AllScroll, Cursor::ZoomInCursor => MouseCursor::ZoomIn, Cursor::ZoomOutCursor => MouseCursor::ZoomOut, }; self.window.set_cursor(glutin_cursor); } fn set_favicon(&self, _: Url) { } fn prepare_for_composite(&self, _width: usize, _height: usize) -> bool { true } #[cfg(target_os="linux")] fn native_metadata(&self) -> NativeGraphicsMetadata { use x11::xlib; NativeGraphicsMetadata { display: unsafe { self.window.platform_display() as *mut xlib::Display } } } #[cfg(target_os="macos")] fn native_metadata(&self) -> NativeGraphicsMetadata { use cgl::{CGLGetCurrentContext, CGLGetPixelFormat}; unsafe { NativeGraphicsMetadata { pixel_format: CGLGetPixelFormat(CGLGetCurrentContext()), } } } #[cfg(target_os="android")] fn native_metadata(&self) -> NativeGraphicsMetadata { use egl::egl::GetCurrentDisplay; NativeGraphicsMetadata { display: GetCurrentDisplay(), } } /// Helper function to handle keyboard events. fn handle_key(&self, key: Key, mods: constellation_msg::KeyModifiers) { match key { Key::Equal if mods.contains(CONTROL) => { // Ctrl-+ self.event_queue.borrow_mut().push(WindowEvent::Zoom(1.1)); } Key::Minus if mods.contains(CONTROL) => { // Ctrl-- self.event_queue.borrow_mut().push(WindowEvent::Zoom(1.0/1.1)); } Key::Backspace if mods.contains(SHIFT) => { // Shift-Backspace self.event_queue.borrow_mut().push(WindowEvent::Navigation(WindowNavigateMsg::Forward)); } Key::Backspace => { // Backspace self.event_queue.borrow_mut().push(WindowEvent::Navigation(WindowNavigateMsg::Back)); } Key::PageDown => { self.scroll_window(0.0, -self.framebuffer_size().as_f32().to_untyped().height); } Key::PageUp => { self.scroll_window(0.0, self.framebuffer_size().as_f32().to_untyped().height); } _ => {} } } fn supports_clipboard(&self) -> bool { true } } /// The type of a window. #[cfg(feature = "headless")] pub struct Window { #[allow(dead_code)] context: glutin::HeadlessContext, width: u32, height: u32, } #[cfg(feature = "headless")] impl Window { pub fn new(_is_foreground: bool, window_size: TypedSize2D<DevicePixel, u32>, _parent: glutin::WindowID) -> Rc<Window> { let window_size = window_size.to_untyped(); let headless_builder = glutin::HeadlessRendererBuilder::new(window_size.width, window_size.height); let headless_context = headless_builder.build().unwrap(); unsafe { headless_context.make_current() }; gl::load_with(|s| headless_context.get_proc_address(s)); let window = Window { context: headless_context, width: window_size.width, height: window_size.height, }; Rc::new(window) } pub fn wait_events(&self) -> Vec<WindowEvent> { vec![WindowEvent::Idle] } pub unsafe fn set_nested_event_loop_listener( &self, _listener: *mut (NestedEventLoopListener + 'static)) { } pub unsafe fn remove_nested_event_loop_listener(&self) { } } #[cfg(feature = "headless")] impl WindowMethods for Window { fn framebuffer_size(&self) -> TypedSize2D<DevicePixel, u32> { Size2D::typed(self.width, self.height) } fn size(&self) -> TypedSize2D<ScreenPx, f32> { Size2D::typed(self.width as f32, self.height as f32) } fn present(&self) { } fn create_compositor_channel(_: &Option<Rc<Window>>) -> (Box<CompositorProxy+Send>, Box<CompositorReceiver>) { let (sender, receiver) = channel(); (box GlutinCompositorProxy { sender: sender, window_proxy: None, } as Box<CompositorProxy+Send>, box receiver as Box<CompositorReceiver>) } fn hidpi_factor(&self) -> ScaleFactor<ScreenPx, DevicePixel, f32> { ScaleFactor::new(1.0) } fn set_page_title(&self, _: Option<String>) { } fn set_page_url(&self, _: Url) { } fn load_start(&self, _: bool, _: bool) { } fn load_end(&self, _: bool, _: bool) { } fn load_error(&self, _: NetError, _: String) { } fn head_parsed(&self) { } fn set_cursor(&self, _: Cursor) { } fn set_favicon(&self, _: Url) { } fn prepare_for_composite(&self, _width: usize, _height: usize) -> bool { true } #[cfg(target_os="linux")] fn native_metadata(&self) -> NativeGraphicsMetadata { NativeGraphicsMetadata {<|fim▁hole|> /// Helper function to handle keyboard events. fn handle_key(&self, _: Key, _: constellation_msg::KeyModifiers) { } fn supports_clipboard(&self) -> bool { false } } struct GlutinCompositorProxy { sender: Sender<compositor_task::Msg>, window_proxy: Option<glutin::WindowProxy>, } // TODO: Should this be implemented here or upstream in glutin::WindowProxy? unsafe impl Send for GlutinCompositorProxy {} impl CompositorProxy for GlutinCompositorProxy { fn send(&mut self, msg: compositor_task::Msg) { // Send a message and kick the OS event loop awake. self.sender.send(msg).unwrap(); if let Some(ref window_proxy) = self.window_proxy { window_proxy.wakeup_event_loop() } } fn clone_compositor_proxy(&self) -> Box<CompositorProxy+Send> { box GlutinCompositorProxy { sender: self.sender.clone(), window_proxy: self.window_proxy.clone(), } as Box<CompositorProxy+Send> } } // These functions aren't actually called. They are here as a link // hack because Skia references them. #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn glBindVertexArrayOES(_array: usize) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn glDeleteVertexArraysOES(_n: isize, _arrays: *const ()) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn glGenVertexArraysOES(_n: isize, _arrays: *const ()) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn glRenderbufferStorageMultisampleIMG(_: isize, _: isize, _: isize, _: isize, _: isize) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn glFramebufferTexture2DMultisampleIMG(_: isize, _: isize, _: isize, _: isize, _: isize, _: isize) { unimplemented!() } #[allow(non_snake_case)] #[no_mangle] pub extern "C" fn glDiscardFramebufferEXT(_: isize, _: isize, _: *const ()) { unimplemented!() }<|fim▁end|>
display: ptr::null_mut() } }
<|file_name|>numword_en_gb.py<|end_file_name|><|fim▁begin|># coding: utf-8 #This file is part of numword. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. ''' numword for EN_GB ''' from numword_en import NumWordEN class NumWordENGB(NumWordEN): ''' NumWord EN_GB ''' def currency(self, val, longval=True): ''' Convert to currency ''' return self._split(val, hightxt=u"pound/s", lowtxt=u"pence", jointxt=u"and", longval=longval) _NW = NumWordENGB() def cardinal(value): ''' Convert to cardinal ''' return _NW.cardinal(value) def ordinal(value): ''' Convert to ordinal '''<|fim▁hole|> ''' Convert to ordinal number ''' return _NW.ordinal_number(value) def currency(value, longval=True): ''' Convert to currency ''' return _NW.currency(value, longval=longval) def year(value, longval=True): ''' Convert to year ''' return _NW.year(value, longval=longval) def main(): ''' Main ''' for val in [ 1, 11, 12, 21, 31, 33, 71, 80, 81, 91, 99, 100, 101, 102, 120, 155, 180, 300, 308, 832, 1000, 1001, 1061, 1100, 1120, 1500, 1701, 1800, 2000, 2010, 2099, 2171, 3000, 8280, 8291, 150000, 500000, 1000000, 2000000, 2000001, -21212121211221211111, -2.121212, -1.0000100, 1325325436067876801768700107601001012212132143210473207540327057320957032975032975093275093275093270957329057320975093272950730]: _NW.test(val) if __name__ == "__main__": main()<|fim▁end|>
return _NW.ordinal(value) def ordinal_number(value):
<|file_name|>faMapMarkedAlt.js<|end_file_name|><|fim▁begin|>'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'fas'; var iconName = 'map-marked-alt'; var width = 576; var height = 512; var ligatures = []; var unicode = 'f5a0'; var svgPathData = 'M288 0c-69.59 0-126 56.41-126 126 0 56.26 82.35 158.8 113.9 196.02 6.39 7.54 17.82 7.54 24.2 0C331.65 284.8 414 182.26 414 126 414 56.41 357.59 0 288 0zm0 168c-23.2 0-42-18.8-42-42s18.8-42 42-42 42 18.8 42 42-18.8 42-42 42zM20.12 215.95A32.006 32.006 0 0 0 0 245.66v250.32c0 11.32 11.43 19.06 21.94 14.86L160 448V214.92c-8.84-15.98-16.07-31.54-21.25-46.42L20.12 215.95zM288 359.67c-14.07 0-27.38-6.18-36.51-16.96-19.66-23.2-40.57-49.62-59.49-76.72v182l192 64V266c-18.92 27.09-39.82 53.52-59.49 76.72-9.13 10.77-22.44 16.95-36.51 16.95zm266.06-198.51L416 224v288l139.88-55.95A31.996 31.996 0 0 0 576 426.34V176.02c0-11.32-11.43-19.06-21.94-14.86z'; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode,<|fim▁hole|>exports.faMapMarkedAlt = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;<|fim▁end|>
svgPathData ]};