code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
#!/usr/bin/python import os import sys pre = '' for (path,dirs,files) in os.walk(sys.argv[1]) : depth_from_root = len(path.split('/')) #print 'DEPTH FROM ROOT %s' %depth_from_root print '-'*(depth_from_root*4 + 8) + ' [ ' + path.split('/')[-1] + ']' for file in files: print '-'*(depth_from_root*4 +12) + ' ' +file
arielravi/python-SPSE
src/directory-traversal.py
Python
agpl-3.0
329
/* * Encog(tm) Core v3.2 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2013 Heaton Research, 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package syncleus.dann.logic.epl; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import syncleus.dann.evolve.exception.EACompileError; /** * A function factory maps the opcodes contained in the EncogOpcodeRegistry into * an EncogProgram. You rarely want to train with every available opcode. For * example, if you are only looking to produce an equation, you should not make * use of the if-statement and logical operators. */ public class FunctionFactory implements Serializable { /** * The serial id. */ private static final long serialVersionUID = 1L; /** * A map for quick lookup. */ private final Map<String, ProgramExtensionTemplate> templateMap = new HashMap<>(); /** * The opcodes. */ private final List<ProgramExtensionTemplate> opcodes = new ArrayList<>(); /** * Default constructor. */ public FunctionFactory() { } /** * Add an opcode to the function factory. The opcode must exist in the * opcode registry. * * @param ext The opcode to add. */ public void addExtension(final ProgramExtensionTemplate ext) { addExtension(ext.getName(), ext.getChildNodeCount()); } /** * Add an opcode to the function factory from the opcode registry. * * @param name The name of the opcode. * @param args The number of arguments. */ public void addExtension(final String name, final int args) { final String key = EncogOpcodeRegistry.createKey(name, args); if (!this.templateMap.containsKey(key)) { final ProgramExtensionTemplate temp = EncogOpcodeRegistry.INSTANCE .findOpcode(name, args); if (temp == null) { throw new EACompileError("Unknown extension " + name + " with " + args + " arguments."); } this.opcodes.add(temp); this.templateMap.put(key, temp); } } /** * Factor a new program node, based in a template object. * * @param temp The opcode. * @param program The program. * @param args The arguments for this node. * @return The newly created ProgramNode. */ public static ProgramNode factorProgramNode(final ProgramExtensionTemplate temp, final EncogProgram program, final ProgramNode[] args) { return new ProgramNode(program, temp, args); } /** * Factor a new program node, based on an opcode name and arguments. * * @param name The name of the opcode. * @param program The program to factor for. * @param args The arguements. * @return The newly created ProgramNode. */ public ProgramNode factorProgramNode(final String name, final EncogProgram program, final ProgramNode[] args) { final String key = EncogOpcodeRegistry.createKey(name, args.length); if (!this.templateMap.containsKey(key)) { throw new EACompileError("Undefined function/operator: " + name + " with " + args.length + " args."); } final ProgramExtensionTemplate temp = this.templateMap.get(key); return new ProgramNode(program, temp, args); } /** * Find a function with the specified name. * * @param name The name of the function. * @return The function opcode. */ public ProgramExtensionTemplate findFunction(final String name) { for (final ProgramExtensionTemplate opcode : this.opcodes) { // only consider functions if (opcode.getNodeType() == NodeType.Function) { if (opcode.getName().equals(name)) { return opcode; } } } return null; } /** * Find all opcodes that match the search criteria. * * @param types The return types to consider. * @param context The program context. * @param includeTerminal True, to include the terminals. * @param includeFunction True, to include the functions. * @return The opcodes found. */ public List<ProgramExtensionTemplate> findOpcodes( final List<ValueType> types, final EncogProgramContext context, final boolean includeTerminal, final boolean includeFunction) { final List<ProgramExtensionTemplate> result = new ArrayList<>(); this.opcodes.stream().forEach((temp) -> types.stream().filter((rtn) -> (temp.isPossibleReturnType(context, rtn))).forEach((_item) -> { if (temp.getChildNodeCount() == 0 && includeTerminal) { result.add(temp); } else if (includeFunction) { result.add(temp); } })); return result; } /** * This method is used when parsing an expression. Consider x>=2. The parser * first sees the > symbol. But it must also consider the =. So we first * look for a 2-char operator, in this case there is one. * * @param ch1 The first character of the potential operator. * @param ch2 The second character of the potential operator. Zero if none. * @return The expression template for the operator found. */ public ProgramExtensionTemplate findOperator(final char ch1, final char ch2) { ProgramExtensionTemplate result = null; // if ch2==0 then we are only looking for a single char operator. // this is rare, but supported. if (ch2 == 0) { return findOperatorExact(String.valueOf(ch1)); } // first, see if we can match an operator with both ch1 and ch2 result = findOperatorExact(String.valueOf(ch1) + ch2); if (result == null) { // okay no 2-char operators matched, so see if we can find a single // char result = findOperatorExact(String.valueOf(ch1)); } // return the operator if we have one. return result; } /** * Find an exact match on opcode. * * @param str The string to match. * @return The opcode found. */ private ProgramExtensionTemplate findOperatorExact(final String str) { for (final ProgramExtensionTemplate opcode : this.opcodes) { // only consider non-unary operators if (opcode.getNodeType() == NodeType.OperatorLeft || opcode.getNodeType() == NodeType.OperatorRight) { if (opcode.getName().equals(str)) { return opcode; } } } return null; } /** * Get the specified opcode. * * @param theOpCode The opcode index. * @return The opcode. */ public ProgramExtensionTemplate getOpCode(final int theOpCode) { return this.opcodes.get(theOpCode); } /** * @return The opcode list. */ public List<ProgramExtensionTemplate> getOpCodes() { return this.opcodes; } /** * @return the templateMap */ public Map<String, ProgramExtensionTemplate> getTemplateMap() { return this.templateMap; } /** * Determine if an opcode is in the function factory. * * @param name The name of the opcode. * @param l The argument count for the opcode. * @return True if the opcode exists. */ public boolean isDefined(final String name, final int l) { final String key = EncogOpcodeRegistry.createKey(name, l); return this.templateMap.containsKey(key); } /** * @return The number of opcodes. */ public int size() { return this.opcodes.size(); } }
automenta/java_dann
src/syncleus/dann/logic/epl/FunctionFactory.java
Java
agpl-3.0
8,711
<?php /* Copyright (c) 2015-2016 Ritho-web team (look at AUTHORS file). This file is part of ritho-web. ritho-web is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ritho-web 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ /** File ritho.php. * * @category General * @package Ritho-web\Classes\Utils * @since 0.1 * @license http://opensource.org/licenses/AGPL-3.0 GNU Affero General Public License * @version GIT: <git_id> * @link http://ritho.net */ /** Ritho application class. */ class Ritho extends Base { /** Class constructor. */ public function __construct() { parent::__construct(); $this->request = empty($_SERVER['REQUEST_URI']) ? false : $_SERVER['REQUEST_URI']; $this->pathRequested = (!empty($_SERVER['QUERY_STRING'])) ? substr($this->request, 0, strpos($this->request, $_SERVER['QUERY_STRING']) - 1) : $this->request; $this->_getController(); $this->controller->run(); } /** Method to create the controller related with an entry path. * * @return void */ private function _getController() { $this->_loadPaths(); $controllerName = ''; $firstParam = ''; $params = null; $this->_cleanPath(); $path = $this->pathRequested; if (empty($path)) { $controllerName = 'CIndex'; $firstParam = ''; } else if (array_key_exists($path, $this->paths)) { $controllerName = $this->paths[$path]['controller']; $firstParam = $this->paths[$path]['param']; } else { $pathKeys = array_keys($this->paths); $pathSelected = ''; foreach ($pathKeys as $curPath) { if (strlen($curPath) > strlen($pathSelected)) { $pattern = preg_replace('/\//', '\\/', preg_quote($curPath)); if (preg_match('/' . $pattern . '/', $path) === 1) $pathSelected = $curPath; } } $controllerName = $this->paths[$pathSelected]['controller']; if ($controllerName === 'CIndex') $controllerName = ''; $firstParam = $this->paths[$pathSelected]['param']; $params = preg_split('/\//', substr($path, strlen($pathSelected))); if (!empty($params[0])) $controllerName = ''; array_shift($params); } if (empty($controllerName)) $this->controller = new C404($firstParam, array('path' => substr($path, 1))); else $this->controller = new $controllerName($firstParam, $params); } /** Method to load the relation between paths and controllers from db. * * @throws Exception Throws an exception when it can't load the paths from db. * @return void */ private function _loadPaths() { if (!isset($this->paths)) $this->paths = array(); if (empty($this->paths)) { $res = $this->db->select('paths'); if ($res === false) throw new Exception('Error loading the paths fromm the database.'); $rows = $this->db->fetchAll($res); if ($rows && count($rows) > 0) { foreach ($rows as $row) { $this->paths[$row['c_path']]['controller'] = $row['controller']; $this->paths[$row['c_path']]['param'] = $row['param']; } } } } /** Method to clean the path of spaces (trim) and the final slash (/). * * @return void */ private function _cleanPath() { if (!is_string($this->pathRequested)) $this->pathRequested = ''; $this->pathRequested = trim(urldecode($this->pathRequested)); if (!empty($this->pathRequested) && strrpos($this->pathRequested, '/') == (strlen($this->pathRequested) - 1)) $this->pathRequested = substr($this->pathRequested, 0, strlen($this->pathRequested) - 1); } }
i02sopop/ritho-web
www/classes/ritho.php
PHP
agpl-3.0
4,034
class Challenge { constructor(model = {}) { this.skills = model.skills || []; } addSkill(skill) { this.skills.push(skill); } hasSkill(searchedSkill) { return this.skills.filter((skill) => skill.name === searchedSkill.name).length > 0; } isPublished() { return ['validé', 'validé sans test', 'pré-validé'].includes(this.status); } } module.exports = Challenge;
sgmap/pix
api/lib/domain/models/Challenge.js
JavaScript
agpl-3.0
402
/** * Session Configuration * (sails.config.session) * * Sails session integration leans heavily on the great work already done by * Express, but also unifies Socket.io with the Connect session store. It uses * Connect's cookie parser to normalize configuration differences between Express * and Socket.io and hooks into Sails' middleware interpreter to allow you to access * and auto-save to `req.session` with Socket.io the same way you would with Express. * * For more information on configuring the session, check out: * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.session.html */ module.exports.session = { /*************************************************************************** * * * Session secret is automatically generated when your new app is created * * Replace at your own risk in production-- you will invalidate the cookies * * of your users, forcing them to log in again. * * * ***************************************************************************/ secret: 'bcd7a4769ebde941674f6b76ed8222ff', /*************************************************************************** * * * Set the session cookie expire time The maxAge is set by milliseconds, * * the example below is for 24 hours * * * ***************************************************************************/ // cookie: { // maxAge: 24 * 60 * 60 * 1000 // } /*************************************************************************** * * * In production, uncomment the following lines to set up a shared redis * * session store that can be shared across multiple Sails.js servers * ***************************************************************************/ // adapter: 'redis', /*************************************************************************** * * * The following values are optional, if no options are set a redis * * instance running on localhost is expected. Read more about options at: * * https://github.com/visionmedia/connect-redis * * * * * ***************************************************************************/ // host: 'localhost', // port: 6379, // ttl: <redis session TTL in seconds>, // db: 0, // pass: <redis auth password> // prefix: 'sess:' /*************************************************************************** * * * Uncomment the following lines to use your Mongo adapter as a session * * store * * * ***************************************************************************/ // adapter: 'mongo', // host: 'localhost', // port: 27017, // db: 'sails', // collection: 'sessions', /*************************************************************************** * * * Optional Values: * * * * # Note: url will override other connection settings url: * * 'mongodb://user:pass@host:port/database/collection', * * * ***************************************************************************/ // username: '', // password: '', // auto_reconnect: false, // ssl: false, // stringify: true };
asm-products/hereapp
config/session.js
JavaScript
agpl-3.0
4,320
<div id="hps-templates"></div> <h1>Standard Player Templates</h1> <div class="entry-content"> <p class="header">There are more then a dozen player templates pre-configured inside the BMC (in the Studio Tab). Once a template is selected, build out your player with simple point-and-click selections of colors, buttons, player sizes, ad configurations, etc.</p> <div class="blurb-full"> <h2>Players with Hovering Controllers</h2> <div class="wpcol-one-half"> <h3>Template: New Player &#8211; Hovering Controllers</h3> <div id="borhan_player_1352425229" style="width:430px;height:322px"></div> <script> bWidget.embed({ 'targetId':'borhan_player_1352425229', 'wid': '_1062871', 'uiconf_id': '10489411', 'entry_id':'1_u05a0sn3' }) </script> <h3>Template: Basic Template &#8211; Hovering Controllers</h3> <div id="borhan_player_1352426711" style="width:430px;height:322px"></div> <script> bWidget.embed({ 'targetId':'borhan_player_1352426711', 'wid': '_1062871', 'uiconf_id': '10489811', 'entry_id':'1_u05a0sn3' }) </script> <h2>Players with Vertical Playlists</h2> <div id="borhan_player" style="width:400px;height:658px"></div> <script> bWidget.embed({ 'targetId':'borhan_player', 'wid': '_1062871', 'uiconf_id': '10491141', 'entry_id':'1_u05a0sn3', 'flashvars':{ 'playlistAPI':{ 'autoInsert':true, 'kpl0Name':'Vertical Playlist Player Demo', 'kpl0Url': 'http://www.borhan.com/index.php/partnerservices2/executeplaylist?partner_id=1062871&subp_id=106287100&format=8&playlist_id=1_h1ocrzz4' } } }) </script> <h3>Template: New Player &#8211; Vertical Playlist</h3> <div id="borhan_player2" style="width:400px;height:658px"></div> <script> bWidget.embed({ 'targetId':'borhan_player2', 'wid': '_1062871', 'uiconf_id': '10489531', 'entry_id':'1_u05a0sn3', 'flashvars':{ 'playlistAPI':{ 'autoInsert':true, 'kpl0Name':'Vertical Playlist Player Demo', 'kpl0Url': 'http://www.borhan.com/index.php/partnerservices2/executeplaylist?partner_id=1062871&subp_id=106287100&format=8&playlist_id=1_h1ocrzz4' } } }) </script> <h3>Template: Basic Template &#8211; Vertical Playlist</h3> <div id="borhan_player3" style="width:400px;height:658px"></div> <script> bWidget.embed({ 'targetId':'borhan_player3', 'wid': '_1062871', 'uiconf_id': '10489531', 'entry_id':'1_u05a0sn3', 'flashvars':{ 'playlistAPI':{ 'autoInsert':true, 'kpl0Name':'Vertical Playlist Player Demo', 'kpl0Url': 'http://www.borhan.com/index.php/partnerservices2/executeplaylist?partner_id=1062871&subp_id=106287100&format=8&playlist_id=1_h1ocrzz4' } } }) </script> <h2>Players with Horizontal Playlists</h2> <div> <h3 style="padding:20px 0 0 0;">Template: New Template &#8211; Horizontal Playlist</h3> <div id="borhan_player4" style="width:740px;height:330px"></div> <script> bWidget.embed({ 'targetId':'borhan_player4', 'wid': '_1062871', 'uiconf_id': '11187681', 'entry_id':'1_u05a0sn3', 'flashvars':{ 'playlistAPI':{ 'autoInsert':true, 'kpl0Name':'Vertical Playlist Player Demo', 'kpl0Url': 'http://www.borhan.com/index.php/partnerservices2/executeplaylist?partner_id=1062871&subp_id=106287100&format=8&playlist_id=1_h1ocrzz4' } } }) </script> </div> <h3 style="padding:20px 0 0 0;">Template: Basic Template &#8211; Horizontal Playlist</h3> <div id="borhan_player5" style="width:740px;height:330px"></div> <script> bWidget.embed({ 'targetId':'borhan_player5', 'wid': '_1062871', 'uiconf_id': '11187551', 'entry_id':'1_u05a0sn3', 'flashvars':{ 'playlistAPI':{ 'autoInsert':true, 'kpl0Name':'Vertical Playlist Player Demo', 'kpl0Url': 'http://www.borhan.com/index.php/partnerservices2/executeplaylist?partner_id=1062871&subp_id=106287100&format=8&playlist_id=1_h1ocrzz4' } } }); </script> <div class="clear"></div> </div> <!-- end .entry-content -->
bordar/mwEmbed
docs/content_marketing_templates.php
PHP
agpl-3.0
3,799
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace Submission_TOC_Builder.Builders { /// <summary> /// Builds a NeeS Table of Contents for the supplied directory /// </summary> public class NeesToc : ABuilder { public override int FoundFiles { get { if (this.ValidDir) { return GetSourcePdfsInDirectory(_dir, _dir, SearchOption.AllDirectories).Count(); } return 0; } } /// <summary> /// Performs a build of a Nees Toc /// </summary> /// <returns></returns> public override Boolean Build() { if (this.ValidDir) { foreach (var subdir in _dir.GetDirectories()) { BuildPdfForDir(subdir, false); } BuildPdfForDir(_dir, true); return true; } return false; } /// <summary> /// Gets the valid pdf's with the given directory /// </summary> /// <param name="dir"></param> /// <param name="searchOption"></param> /// <returns></returns> private List<FileInfo> GetSourcePdfsInDirectory(DirectoryInfo dir, DirectoryInfo rootDir, SearchOption searchOption) { var returnLst = new List<FileInfo>(); // Check we have a directory and that it exists if (dir.Exists && rootDir.Exists) { // Loop each pdf file in the directory foreach (var file in dir.GetFiles("*.pdf", searchOption)) { // Get the depth var depth = Helpers.Paths.GetDepthFromDir(file, rootDir); // Set the maximum depth we should skip toc files var maxDepth = 0; // If dir and rootDir are the same we're looking at the ctd, step 1 level deeper if (dir.FullName == rootDir.FullName) { maxDepth = 1; } // If the file depth is less that <= 1 and it contains toc then it is a toc. We obviously don't want to include // that again if (depth <= maxDepth && file.Name.IndexOf("toc.pdf", StringComparison.OrdinalIgnoreCase) > -1) continue; returnLst.Add(file); } } return returnLst; } /// <summary> /// Builds a PDF for the given dir. /// </summary> /// <param name="dir"></param> /// <param name="coreTechnicalDocument">Is this the root CTD?</param> private void BuildPdfForDir(DirectoryInfo dir, Boolean coreTechnicalDocument) { if (this.ValidDir) { var doc = new XmlDocument(); var htmlNode = doc.CreateElement("html"); doc.AppendChild(htmlNode); var headNode = doc.CreateElement("head"); htmlNode.AppendChild(headNode); // If the pdf-styles.css file exists then use it to build the pdf // If companies want branding, they can do it here if (File.Exists("Style/pdf-style.css")) { var styleNode = doc.CreateElement("style"); headNode.AppendChild(styleNode); var stylesNode = doc.CreateComment(File.ReadAllText("Style/pdf-style.css")); styleNode.AppendChild(stylesNode); } var bodyNode = doc.CreateElement("body"); htmlNode.AppendChild(bodyNode); var ul = bodyNode.OwnerDocument.CreateElement("ul"); bodyNode.AppendChild(ul); // Builds the file list for the supplied directory BuildForDir(dir, dir, ul, coreTechnicalDocument); // Create a sensible file name var filename = String.Format("{0}-toc", coreTechnicalDocument ? "ctd" : dir.Name.ToLowerInvariant()); // doc.Save(Path.Combine(dir.FullName, filename + ".html")); // Save to PDF Helpers.Pdf.HtmlToPdf(doc, Path.Combine(dir.FullName, filename + ".pdf")); } } /// <summary> /// Builds a list for the supplied directory /// </summary> /// <param name="dir"></param> /// <param name="rootDir"></param> /// <param name="node"></param> /// <param name="coreTechnicalDocument"></param> private void BuildForDir(DirectoryInfo dir, DirectoryInfo rootDir, XmlNode node, Boolean coreTechnicalDocument) { // A ctd has a slightly different structure, go straight into sub directories if (coreTechnicalDocument) { foreach (var subDir in dir.GetDirectories()) { BuildFileListItemsForDir(subDir, rootDir, node); } } else { // Build all dirs BuildDirListItemsForDir(dir, rootDir, node); } } /// <summary> /// Builds the list items for a specific directory /// </summary> /// <param name="dir"></param> /// <param name="rootDir"></param> /// <param name="node"></param> private void BuildDirListItemsForDir(DirectoryInfo dir, DirectoryInfo rootDir, XmlNode node) { foreach (var subDir in dir.GetDirectories()) { // Create a label for the dir var li = node.OwnerDocument.CreateElement("li"); node.AppendChild(li); var span = node.OwnerDocument.CreateElement("span"); span.InnerText = subDir.Name; li.AppendChild(span); var ul = node.OwnerDocument.CreateElement("ul"); li.AppendChild(ul); BuildDirListItemsForDir(subDir, rootDir, ul); } BuildFileListItemsForDir(dir, rootDir, node); } /// <summary> /// Builds the list items for a specific directory /// </summary> /// <param name="dir"></param> /// <param name="rootDir"></param> /// <param name="node"></param> private void BuildFileListItemsForDir(DirectoryInfo dir, DirectoryInfo rootDir, XmlNode node) { foreach (var file in GetSourcePdfsInDirectory(dir, rootDir, SearchOption.TopDirectoryOnly)) { BuildListItemForFile(file, rootDir, node); } } /// <summary> /// Builds the individual list item for a file /// </summary> /// <param name="file"></param> /// <param name="rootDir"></param> /// <param name="node"></param> private void BuildListItemForFile(FileInfo file, DirectoryInfo rootDir, XmlNode node) { var li = node.OwnerDocument.CreateElement("li"); node.AppendChild(li); var a = node.OwnerDocument.CreateElement("a"); a.SetAttribute("href", Helpers.Paths.GetRelativePathFromDir(file, rootDir)); a.InnerText = file.Name; li.AppendChild(a); } } }
phawxby/TOC-Builder
Submission TOC Builder/Builders/NeesToc.cs
C#
agpl-3.0
7,608
/* * * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * * $$PROACTIVE_INITIAL_DEV$$ */ package functionalTests.activeobject.service; /** * CustomException * * @author The ProActive Team */ public class CustomException extends RuntimeException { private static final long serialVersionUID = 54L; }
nmpgaspar/PainlessProActive
src/Tests/functionalTests/activeobject/service/CustomException.java
Java
agpl-3.0
1,526
<?php /** * _ __ __ _____ _____ ___ ____ _____ * | | / // // ___//_ _// || __||_ _| * | |/ // /(__ ) / / / /| || | | | * |___//_//____/ /_/ /_/ |_||_| |_| * @link https://vistart.me/ * @copyright Copyright (c) 2016 - 2017 vistart * @license https://vistart.me/license/ */ namespace rhosocial\user\tests\models; use rhosocial\user\tests\data\User; use rhosocial\user\tests\TestCase; /** * Class UsernameTest * @package rhosocial\user\tests\models * @version 1.0 * @author vistart <i@vistart.me> */ class UsernameTest extends TestCase { /** * @var User */ protected $user; /** * @var string */ protected $username = 'vistart'; /** * */ protected function setUp() { parent::setUp(); $this->user = new User(['password' => '123456']); $result = $this->user->register([$this->user->createUsername($this->username)]); if (!is_bool($result)) { echo $result->getMessage(); $this->fail(); } $this->assertTrue($result); $this->assertTrue(is_numeric($this->user->getID())); } protected function tearDown() { User::deleteAll(); parent::tearDown(); } /** * @group username */ public function testNormal() { $this->assertEquals($this->username, $this->user->username->content); $this->assertEquals($this->username, (string)$this->user->username); } /** * @group username */ public function testSet() { $this->user->username = $this->username . '1'; $this->assertEquals($this->username . '1', (string)$this->user->getUsername()->one()); } /** * @group username */ public function testRemove() { $this->assertTrue($this->user->removeUsername()); $this->assertNull($this->user->getUsername()->one()); $this->assertTrue($this->user->hasEnabledUsername()); } /** * @group username */ public function testUnique() { $this->assertEquals($this->username, (string)$this->user->username); $user = new User(['password' => '123456']); try { $result = $user->register([$user->createUsername($this->username)]); if ($result instanceof \Exception) { throw $result; } $this->fail('Registration should be failed.'); } catch (\Exception $ex) { $this->assertNotEmpty($ex->getMessage()); } $user = new User(['password' => '123456']); $this->assertTrue($user->register([$user->createUsername($this->username . '1')])); } }
rhosocial/yii2-user
tests/models/UsernameTest.php
PHP
agpl-3.0
2,695
const mongoose = require('mongoose'); const config = require('../../config/config'); const _ = require('underscore'); const urlLib = require('url'); function getSellerFromURL(url) { if (!url) { return null; } const sellers = _.keys(config.sellers); return _.find(sellers, function(seller) { if (url.indexOf(config.sellers[seller].url) >=0 ) { return seller; } }); } function getVideoSiteFromURL(url) { const videoSites = _.keys(config.videoSites); const youtubeDLSites = config.youtubeDLSites; const locallyProcessedSite = _.find(videoSites, function(site) { return (url.indexOf(config.videoSites[site].url) >=0); }); if (locallyProcessedSite) { return locallyProcessedSite; } const purlObject = urlLib.parse(url); const host = purlObject.host; return _.find(youtubeDLSites, function(youtubeDLSite) { return host.indexOf(youtubeDLSite) >= 0; }); } function getDeepLinkURL(seller, url) { if (seller === 'amazon') { // extract ASIN from the url // http://stackoverflow.com/questions/1764605/scrape-asin-from-amazon-url-using-javascript const asin = url.match('/([a-zA-Z0-9]{10})(?:[/?]|$)'); if (asin && asin[1]) { return ('http://www.amazon.in/dp/'+ asin[1]); } return url; } else if (seller === 'flipkart') { // http://nodejs.org/api/url.html // signature: url.parse(urlStr, [parseQueryString], [slashesDenoteHost]) const parsedURL = urlLib.parse(url, true); const pidQueryString = (parsedURL.query.pid && (parsedURL.query.pid !== undefined)) ? ('?pid=' + parsedURL.query.pid) : ''; const affiliateHost = parsedURL.host; if (parsedURL.pathname.indexOf('/dl') !== 0) { parsedURL.pathname = '/dl' + parsedURL.pathname; } affiliateHost = affiliateHost.replace('www.flipkart.com', 'dl.flipkart.com'); const normalizedURL = parsedURL.protocol + '//' + affiliateHost + parsedURL.pathname + pidQueryString; return normalizedURL; } else if (seller === 'snapdeal') { //snapdeal has a few junk chars in `hash` //"#bcrumbSearch:AF-S%20Nikkor%2050mm%20f/1.8G" //so lets ignore the hash altogether and return url until pathname const pUrl = urlLib.parse(url, true); return (pUrl.protocol + '//' + pUrl.host + pUrl.pathname); } return url; } function getURLWithAffiliateId(url) { const urlSymbol = url.indexOf('?') > 0 ? '&': '?'; const seller = getSellerFromURL(url); const sellerKey = config.sellers[seller].key, sellerValue = config.sellers[seller].value, sellerExtraParams = config.sellers[seller].extraParams; if (sellerKey && sellerValue) { const stringToMatch = sellerKey + '=' + sellerValue; let urlWithAffiliate; if (url.indexOf(stringToMatch) > 0) { urlWithAffiliate = url; } else { urlWithAffiliate = url + urlSymbol + stringToMatch; } //for snapdeal, they have a offer id param as well //in the config file, I've put it as a query string //so simply appending it here would work if (sellerExtraParams) { return urlWithAffiliate + sellerExtraParams; } else { return urlWithAffiliate; } } return url; } function increaseCounter(counterName) { const counterModel = mongoose.model('Counter'); counterModel.findOne().lean().exec(function(err, doc) { if (!doc) { return; } const updateQuery = {_id: doc._id}; const updateObject = {}; const updateOptions = {}; updateObject[counterName] = doc[counterName] + 1; counterModel.update(updateQuery, updateObject, updateOptions, function() {}); }); } module.exports = { getSellerFromURL: getSellerFromURL, getDeepLinkURL: getDeepLinkURL, getVideoSiteFromURL: getVideoSiteFromURL, increaseCounter: increaseCounter, getURLWithAffiliateId: getURLWithAffiliateId, getSellerJobModelInstance: function(seller) { const jobSellerModelName = seller + '_job'; return mongoose.model(jobSellerModelName); }, getSellerProductPriceHistoryModelInstance: function (seller) { return mongoose.model(seller + '_product_price_history'); }, getProcessingMode: function(url) { //2 modes. 'seller' or 'site' if (getVideoSiteFromURL(url)) { return 'site'; } return 'seller'; }, isLegitSeller: function(seller) { if (!seller) { return false; } const sellers = _.keys(config.sellers); return !!_.find(sellers, function(legitSeller) { return seller.trim().toLowerCase() === legitSeller; }); } };
Cheapass/cheapass
src/utils/seller.js
JavaScript
agpl-3.0
4,500
<?php namespace Application\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ class Version20150402225211 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema) { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE adherents ADD departement INT NOT NULL'); } /** * @param Schema $schema */ public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE adherents DROP departement'); } }
LePartiDeGauche/congres
app/DoctrineMigrations/Version20150402225211.php
PHP
agpl-3.0
1,037
/** * Created by helge on 24.08.16. */ import React from 'react'; import PropTypes from 'prop-types'; import FlagAmountBet from './FlagAmountBet'; import FlagAmountCall from './FlagAmountCall'; import FlagButton from './FlagButton'; import ControlBetRaise from './ControlBetRaise'; import ControlCheckCall from './ControlCheckCall'; import ControlFold from './ControlFold'; import Slider from '../Slider'; import { ActionBarWrapper, ControlPanel, ControlWrapper, FlagContainer, } from './styles'; const ActionBar = (props) => { const { active, disabled, sliderOpen, visible, } = props; if (visible) { return ( <ActionBarWrapper active={active} disabled={disabled} name="action-bar-wrapper" > <FlagAmountCall {...props} /> <FlagAmountBet {...props} /> <FlagContainer active={active} name="flag-container"> <FlagButton type={0.25} {...props} /> <FlagButton type={0.50} {...props} /> <FlagButton type={1.00} {...props} /> </FlagContainer> <ControlPanel name="control-panel-visible"> <ControlWrapper sliderOpen={sliderOpen} > <ControlFold {...props} /> <ControlCheckCall {...props} /> <ControlBetRaise {...props} /> {sliderOpen && <Slider {...props} /> } </ControlWrapper> </ControlPanel> </ActionBarWrapper> ); } return null; }; ActionBar.propTypes = { visible: PropTypes.bool, active: PropTypes.bool, disabled: PropTypes.bool, sliderOpen: PropTypes.bool, }; export default ActionBar;
VonIobro/ab-web
app/components/ActionBar/index.js
JavaScript
agpl-3.0
1,656
<?php /** * ownCloud - ftpquota * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Pellaeon Lin <pellaeon@cnmc.tw> * @copyright Pellaeon Lin 2015 */ namespace OCA\FtpQuota\Controller; use OCP\IRequest; use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Http\DataResponse; use OCP\AppFramework\Controller; class PageController extends Controller { private $userId; public function __construct($AppName, IRequest $request, $UserId){ parent::__construct($AppName, $request); $this->userId = $UserId; } /** * CAUTION: the @Stuff turns off security checks; for this page no admin is * required and no CSRF check. If you don't know what CSRF is, read * it up in the docs or you might create a security hole. This is * basically the only required method to add this exemption, don't * add it to any other method if you don't exactly know what it does * * @NoAdminRequired * @NoCSRFRequired */ public function index() { $params = ['user' => $this->userId]; return new TemplateResponse('ftpquota', 'main', $params); // templates/main.php } /** * Simply method that posts back the payload of the request * @NoAdminRequired */ public function doEcho($echo) { return new DataResponse(['echo' => $echo]); } }
pellaeon/owncloud-ftpquota
controller/pagecontroller.php
PHP
agpl-3.0
1,378
// Copyright (C) MongoDB, Inc. 2017-present. // // 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 package command import ( "context" "github.com/mongodb/mongo-go-driver/bson" "github.com/mongodb/mongo-go-driver/core/description" "github.com/mongodb/mongo-go-driver/core/option" "github.com/mongodb/mongo-go-driver/core/session" "github.com/mongodb/mongo-go-driver/core/wiremessage" ) // GetMore represents the getMore command. // // The getMore command retrieves additional documents from a cursor. type GetMore struct { ID int64 NS Namespace Opts []option.CursorOptioner Clock *session.ClusterClock Session *session.Client result bson.Reader err error } // Encode will encode this command into a wire message for the given server description. func (gm *GetMore) Encode(desc description.SelectedServer) (wiremessage.WireMessage, error) { cmd, err := gm.encode(desc) if err != nil { return nil, err } return cmd.Encode(desc) } func (gm *GetMore) encode(desc description.SelectedServer) (*Read, error) { cmd := bson.NewDocument( bson.EC.Int64("getMore", gm.ID), bson.EC.String("collection", gm.NS.Collection), ) var err error for _, opt := range gm.Opts { switch t := opt.(type) { case option.OptMaxAwaitTime: err = option.OptMaxTime(t).Option(cmd) default: err = opt.Option(cmd) } if err != nil { return nil, err } } return &Read{ Clock: gm.Clock, DB: gm.NS.DB, Command: cmd, Session: gm.Session, }, nil } // Decode will decode the wire message using the provided server description. Errors during decoding // are deferred until either the Result or Err methods are called. func (gm *GetMore) Decode(desc description.SelectedServer, wm wiremessage.WireMessage) *GetMore { rdr, err := (&Read{}).Decode(desc, wm).Result() if err != nil { gm.err = err return gm } return gm.decode(desc, rdr) } func (gm *GetMore) decode(desc description.SelectedServer, rdr bson.Reader) *GetMore { gm.result = rdr return gm } // Result returns the result of a decoded wire message and server description. func (gm *GetMore) Result() (bson.Reader, error) { if gm.err != nil { return nil, gm.err } return gm.result, nil } // Err returns the error set on this command. func (gm *GetMore) Err() error { return gm.err } // RoundTrip handles the execution of this command using the provided wiremessage.ReadWriter. func (gm *GetMore) RoundTrip(ctx context.Context, desc description.SelectedServer, rw wiremessage.ReadWriter) (bson.Reader, error) { cmd, err := gm.encode(desc) if err != nil { return nil, err } rdr, err := cmd.RoundTrip(ctx, desc, rw) if err != nil { return nil, err } return gm.decode(desc, rdr).Result() }
DamienFontaine/lunarc
vendor/github.com/mongodb/mongo-go-driver/core/command/get_more.go
GO
agpl-3.0
2,898
/** * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * * Copyright (c) 2016 LIBSCAPI (http://crypto.biu.ac.il/SCAPI) * This file is part of the SCAPI project. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * 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. * * We request that any publication and/or code referring to and/or based on SCAPI contain an appropriate citation to SCAPI, including a reference to * http://crypto.biu.ac.il/SCAPI. * * Libscapi uses several open source libraries. Please see these projects for any further licensing issues. * For more information , See https://github.com/cryptobiu/libscapi/blob/master/LICENSE.MD * * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * */ #pragma once #include "Prf.hpp" #include "PrfOpenSSL.hpp" #include <mutex> /** * Abstract class of key derivation function. Every class in this family should derive this class. * A key derivation function (or KDF) is used to derive (close to) uniformly distributed string/s from a secret value * with high entropy (but no other guarantee regarding its distribution). */ class KeyDerivationFunction { public: /** * Generates a new secret key from the given entropy and iv. * @param entropySource the byte vector that is the seed for the key generation * @param inOff the offset within the entropySource to take the bytes from * @param inLen the length of the seed * @param outLen the required output key length * @param iv info for the key generation * @return SecretKey the derivated key. */ virtual SecretKey deriveKey(const vector<byte> & entropySource, int inOff, int inLen, int outLen, const vector<byte>& iv = vector<byte>()) = 0; }; /** * Concrete class of key derivation function for HKDF. * This is a key derivation function that has a rigorous justification as to its security. * Note that all deriveKey functions in this implementation are thread safe. */ class HKDF : public KeyDerivationFunction { private: shared_ptr<Hmac> hmac; // The underlying hmac mutex _mutex; // For synchronizing /** * Does round 2 to t of HKDF algorithm. The pseudo code: * FOR i = 2 TO t * K(i) = HMAC(PRK,(K(i-1),CTXinfo,i)) [key=PRK, data=(K(i-1),CTXinfo,i)] * @param outLen the required output key length * @param iv The iv : ctxInfo * @param hmacLength the size of the output of the hmac. * @param outBytes the result of the overall computation * @param intermediateOutBytes round result K(i) in the pseudocode */ void nextRounds(int outLen, const vector<byte> & iv, int hmacLength, vector<byte> & outBytes, vector<byte> & intermediateOutBytes); /** * First round of HKDF algorithm. The pseudo code: * K(1) = HMAC(PRK,(CTXinfo,1)) [key=PRK, data=(CTXinfo,1)] * @param iv ctxInfo * @param intermediateOutBytes round result K(1) in the pseudocode * @param outLength the size of the output of the hmac. * @param outBytes the result of the overall computation */ void firstRound(vector<byte>& outBytes, const vector<byte> & iv, vector<byte> & intermediateOutBytes, int outLength); public: HKDF(const shared_ptr<Hmac> & hmac = make_shared<OpenSSLHMAC>()) { this->hmac = hmac; }; /** * This function derives a new key from the source key material key. * The pseudo-code of this function is as follows: * * COMPUTE PRK = HMAC(XTS, SKM) [key=XTS, data=SKM] * Let t be the smallest number so that t * |H|>L where |H| is the HMAC output length * K(1) = HMAC(PRK,(CTXinfo,1)) [key=PRK, data=(CTXinfo,1)] * FOR i = 2 TO t * K(i) = HMAC(PRK,(K(i-1),CTXinfo,i)) [key=PRK, data=(K(i-1),CTXinfo,i)] * OUTPUT the first L bits of K(1),�,K(t) * * @param iv - CTXInfo * * Note that this function is thread safe! */ SecretKey deriveKey(const vector<byte> & entropySource, int inOff, int inLen, int outLen, const vector<byte>& iv = vector<byte>()) override; };
cris-iisc/mpc-primitives
crislib/libscapi/include/primitives/Kdf.hpp
C++
agpl-3.0
4,982
import unittest from coala_quickstart.info_extractors import Utilities class UtititiesTest(unittest.TestCase): def setUp(self): self.simple_dict = { 'key1': 'value1', 'key2': 'value2' } self.nested_dict = { 'key1': { 'key1.1': 'value1.1' } } self.nested_dict_with_list = { 'key1': { 'key1.1': [ { 'key_a': 'value_a' }, { 'key_b': [ { 'key_b_1': 'value_b_1' }] }] } } self.nested_list_with_dict = [ { 'key1': 'value1', 'key2': 'value2' }, { 'key3': 'value3', 'key4': 'value4' } ] self.dict_with_repeated_structure = { 'key1': { 'key1.1': 'value1.1' }, 'key2': { 'key1.1': 'value1.1', 'key2.1': 'value2.1' } } def test_search_object_recursively(self): uut = Utilities.search_object_recursively def assert_value_and_path(search_obj, search_key, search_value, expected_results, expected_paths): search_results = uut(search_obj, search_key, search_value) for obj, path in zip(expected_results, expected_paths): expected_result = { 'object': obj, 'path': path } self.assertIn(expected_result, search_results) assert_value_and_path( self.simple_dict, 'key1', None, ['value1'], [('key1',)]) assert_value_and_path(self.simple_dict, 'key1', 'value1', [{ 'key1': 'value1', 'key2': 'value2' }], [('key1',)]) assert_value_and_path(self.nested_dict, 'key1.1', None, ['value1.1'], [('key1', 'key1.1')]) assert_value_and_path(self.nested_dict, 'key1.1', 'value1.1', [{ 'key1.1': 'value1.1' }], [('key1', 'key1.1')]) assert_value_and_path(self.nested_dict_with_list, 'key_b_1', None, ['value_b_1'], [('key1', 'key1.1', 1, 'key_b', 0, 'key_b_1')]) assert_value_and_path(self.nested_dict_with_list, 'key_b_1', 'value_b_1', [{ 'key_b_1': 'value_b_1' }], [('key1', 'key1.1', 1, 'key_b', 0, 'key_b_1')]) assert_value_and_path(self.nested_list_with_dict, 'key3', None, ['value3'], [(1, 'key3')]) assert_value_and_path(self.nested_list_with_dict, 'key3', 'value3', [{ 'key3': 'value3', 'key4': 'value4' }], [(1, 'key3')]) assert_value_and_path(self.dict_with_repeated_structure, 'key1.1', None, ['value1.1', 'value1.1'], [('key1', 'key1.1'), ('key2', 'key1.1')]) assert_value_and_path(self.dict_with_repeated_structure, 'key1.1', 'value1.1', [ { 'key1.1': 'value1.1', 'key2.1': 'value2.1' }, { 'key1.1': 'value1.1', } ], [('key2', 'key1.1'), ('key1', 'key1.1')])
MalkmusT/coala-quickstart
tests/info_extractors/UtilitiesTest.py
Python
agpl-3.0
4,899
import _, { messages } from 'intl' import ActionButton from 'action-button' import decorate from 'apply-decorators' import Icon from 'icon' import React from 'react' import { addSubscriptions, resolveId } from 'utils' import { alert, confirm } from 'modal' import { createRemote, editRemote, subscribeRemotes } from 'xo' import { error } from 'notification' import { format } from 'xo-remote-parser' import { generateId, linkState } from 'reaclette-utils' import { injectState, provideState } from 'reaclette' import { map, some, trimStart } from 'lodash' import { Password, Number } from 'form' import { SelectProxy } from 'select-objects' const remoteTypes = { file: 'remoteTypeLocal', nfs: 'remoteTypeNfs', smb: 'remoteTypeSmb', s3: 'remoteTypeS3', } export default decorate([ addSubscriptions({ remotes: subscribeRemotes, }), provideState({ initialState: () => ({ domain: undefined, host: undefined, name: undefined, options: undefined, password: undefined, path: undefined, port: undefined, proxyId: undefined, type: undefined, username: undefined, directory: undefined, bucket: undefined, }), effects: { linkState, setPort: (_, port) => state => ({ port: port === undefined && state.remote !== undefined ? '' : port, }), setProxy(_, proxy) { this.state.proxyId = resolveId(proxy) }, editRemote: ({ reset }) => state => { const { remote, domain = remote.domain || '', host = remote.host, name, options = remote.options || '', password = remote.password, port = remote.port, proxyId = remote.proxy, type = remote.type, username = remote.username, } = state let { path = remote.path } = state if (type === 's3') { const { parsedPath, bucket = parsedPath.split('/')[0], directory = parsedPath.split('/')[1] } = state path = bucket + '/' + directory } return editRemote(remote, { name, url: format({ domain, host, password, path, port: port || undefined, type, username, }), options: options !== '' ? options : null, proxy: proxyId, }).then(reset) }, createRemote: ({ reset }) => async (state, { remotes }) => { if (some(remotes, { name: state.name })) { return alert( <span> <Icon icon='error' /> {_('remoteTestName')} </span>, <p>{_('remoteTestNameFailure')}</p> ) } const { domain = 'WORKGROUP', host, name, options, password, path, port, proxyId, type = 'nfs', username, } = state const urlParams = { host, path, port, type, } if (type === 's3') { const { bucket, directory } = state urlParams.path = bucket + '/' + directory } username && (urlParams.username = username) password && (urlParams.password = password) domain && (urlParams.domain = domain) if (type === 'file') { await confirm({ title: _('localRemoteWarningTitle'), body: _('localRemoteWarningMessage'), }) } const url = format(urlParams) return createRemote(name, url, options !== '' ? options : undefined, proxyId === null ? undefined : proxyId) .then(reset) .catch(err => error('Create Remote', err.message || String(err))) }, setSecretKey(_, { target: { value } }) { this.state.password = value }, }, computed: { formId: generateId, inputTypeId: generateId, parsedPath: ({ remote }) => remote && trimStart(remote.path, '/'), }, }), injectState, ({ state, effects, formatMessage }) => { const { remote = {}, domain = remote.domain || 'WORKGROUP', host = remote.host || '', name = remote.name || '', options = remote.options || '', password = remote.password || '', parsedPath, path = parsedPath || '', parsedBucket = parsedPath != null && parsedPath.split('/')[0], bucket = parsedBucket || '', parsedDirectory = parsedPath != null && parsedPath.split('/')[1], directory = parsedDirectory || '', port = remote.port, proxyId = remote.proxy, type = remote.type || 'nfs', username = remote.username || '', } = state return ( <div> <h2>{_('newRemote')}</h2> <form id={state.formId}> <div className='form-group'> <label htmlFor={state.inputTypeId}>{_('remoteType')}</label> <select className='form-control' id={state.inputTypeId} name='type' onChange={effects.linkState} required value={type} > {map(remoteTypes, (label, key) => _({ key }, label, message => <option value={key}>{message}</option>))} </select> {type === 'smb' && <em className='text-warning'>{_('remoteSmbWarningMessage')}</em>} {type === 's3' && <em className='text-warning'>Backup to Amazon S3 is a BETA feature</em>} </div> <div className='form-group'> <input className='form-control' name='name' onChange={effects.linkState} placeholder={formatMessage(messages.remoteMyNamePlaceHolder)} required type='text' value={name} /> </div> <div className='form-group'> <SelectProxy onChange={effects.setProxy} value={proxyId} /> </div> {type === 'file' && ( <fieldset className='form-group'> <div className='input-group'> <span className='input-group-addon'>/</span> <input className='form-control' name='path' onChange={effects.linkState} pattern='^(([^/]+)+(/[^/]+)*)?$' placeholder={formatMessage(messages.remoteLocalPlaceHolderPath)} required type='text' value={path} /> </div> </fieldset> )} {type === 'nfs' && ( <fieldset> <div className='form-group'> <input className='form-control' name='host' onChange={effects.linkState} placeholder={formatMessage(messages.remoteNfsPlaceHolderHost)} required type='text' value={host} /> <br /> <Number onChange={effects.setPort} placeholder={formatMessage(messages.remoteNfsPlaceHolderPort)} value={port} /> </div> <div className='input-group form-group'> <span className='input-group-addon'>/</span> <input className='form-control' name='path' onChange={effects.linkState} pattern='^(([^/]+)+(/[^/]+)*)?$' placeholder={formatMessage(messages.remoteNfsPlaceHolderPath)} required type='text' value={path} /> </div> <div className='input-group form-group'> <span className='input-group-addon'>-o</span> <input className='form-control' name='options' onChange={effects.linkState} placeholder={formatMessage(messages.remoteNfsPlaceHolderOptions)} type='text' value={options} /> </div> </fieldset> )} {type === 'smb' && ( <fieldset> <div className='input-group form-group'> <span className='input-group-addon'>\\</span> <input className='form-control' name='host' onChange={effects.linkState} pattern='^[^\\/]+\\[^\\/]+$' placeholder={formatMessage(messages.remoteSmbPlaceHolderAddressShare)} required type='text' value={host} /> <span className='input-group-addon'>\</span> <input className='form-control' name='path' onChange={effects.linkState} pattern='^([^\\/]+(\\[^\\/]+)*)?$' placeholder={formatMessage(messages.remoteSmbPlaceHolderRemotePath)} type='text' value={path} /> </div> <div className='form-group'> <input className='form-control' name='username' onChange={effects.linkState} placeholder={formatMessage(messages.remoteSmbPlaceHolderUsername)} required type='text' value={username} /> </div> <div className='form-group'> <Password name='password' onChange={effects.linkState} placeholder={formatMessage(messages.remoteSmbPlaceHolderPassword)} required value={password} /> </div> <div className='form-group'> <input className='form-control' onChange={effects.linkState} name='domain' placeholder={formatMessage(messages.remoteSmbPlaceHolderDomain)} required type='text' value={domain} /> </div> <div className='input-group form-group'> <span className='input-group-addon'>-o</span> <input className='form-control' name='options' onChange={effects.linkState} placeholder={formatMessage(messages.remoteSmbPlaceHolderOptions)} type='text' value={options} /> </div> </fieldset> )} {type === 's3' && ( <fieldset className='form-group form-group'> <div className='input-group '> <input className='form-control' name='host' onChange={effects.linkState} // pattern='^[^\\/]+\\[^\\/]+$' placeholder='AWS S3 endpoint (ex: s3.us-east-2.amazonaws.com)' required type='text' value={host} /> </div> <div className='input-group '> <input className='form-control' name='bucket' onChange={effects.linkState} // https://stackoverflow.com/a/58248645/72637 pattern='(?!^(\d{1,3}\.){3}\d{1,3}$)(^[a-z0-9]([a-z0-9-]*(\.[a-z0-9])?)*$)' placeholder={formatMessage(messages.remoteS3PlaceHolderBucket)} required type='text' value={bucket} /> </div> <div className='input-group form-group'> <input className='form-control' name='directory' onChange={effects.linkState} pattern='^(([^/]+)+(/[^/]+)*)?$' placeholder={formatMessage(messages.remoteS3PlaceHolderDirectory)} required type='text' value={directory} /> </div> <div className='input-group'> <input className='form-control' name='username' onChange={effects.linkState} placeholder='Access key ID' required type='text' value={username} /> </div> <div className='input-group'> <input className='form-control' name='password' onChange={effects.setSecretKey} placeholder='Paste secret here to change it' autoComplete='off' required type='text' /> </div> </fieldset> )} <div className='form-group'> <ActionButton btnStyle='primary' form={state.formId} handler={state.remote === undefined ? effects.createRemote : effects.editRemote} icon='save' type='submit' > {_('savePluginConfiguration')} </ActionButton> <ActionButton className='pull-right' handler={effects.reset} icon='reset' type='reset'> {_('formReset')} </ActionButton> </div> </form> </div> ) }, ])
vatesfr/xo-web
packages/xo-web/src/xo-app/settings/remotes/remote.js
JavaScript
agpl-3.0
13,904
<?php // $Id$ require_once(dirname(__FILE__) . '/../../../autorun.php'); require_once(dirname(__FILE__) . '/../../dom_tester.php'); class TestOfLiveCssSelectors extends DomTestCase { function setUp() { $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); } function testGet() { $url = 'file://'.dirname(__FILE__).'/support/dom_tester.html'; $this->assertTrue($this->get($url)); $this->assertElementsBySelector('h1', array('Test page')); $this->assertElementsBySelector('ul#list li a[href]', array('link')); $this->assertElementsBySelector('body h1', array('Test page')); $this->assertElementsBySelector('#mybar', array('myfoo bis')); } } class TestOfCssSelectors extends UnitTestCase { function __construct() { parent::__construct(); $html = file_get_contents(dirname(__FILE__) . '/support/dom_tester.html'); $this->dom = new DomDocument('1.0', 'utf-8'); $this->dom->validateOnParse = true; $this->dom->loadHTML($html); } function testBasicSelector() { $expectation = new CssSelectorExpectation($this->dom, 'h1'); $this->assertTrue($expectation->test(array('Test page'))); $expectation = new CssSelectorExpectation($this->dom, 'h2'); $this->assertTrue($expectation->test(array('Title 1', 'Title 2'))); $expectation = new CssSelectorExpectation($this->dom, '#footer'); $this->assertTrue($expectation->test(array('footer'))); $expectation = new CssSelectorExpectation($this->dom, 'div#footer'); $this->assertTrue($expectation->test(array('footer'))); $expectation = new CssSelectorExpectation($this->dom, '.header'); $this->assertTrue($expectation->test(array('header'))); $expectation = new CssSelectorExpectation($this->dom, 'p.header'); $this->assertTrue($expectation->test(array('header'))); $expectation = new CssSelectorExpectation($this->dom, 'div.header'); $this->assertTrue($expectation->test(array())); $expectation = new CssSelectorExpectation($this->dom, 'ul#mylist ul li'); $this->assertTrue($expectation->test(array('element 3', 'element 4'))); $expectation = new CssSelectorExpectation($this->dom, '#nonexistant'); $this->assertTrue($expectation->test(array())); } function testAttributeSelectors() { $expectation = new CssSelectorExpectation($this->dom, 'ul#list li a[href]'); $this->assertTrue($expectation->test(array('link'))); $expectation = new CssSelectorExpectation($this->dom, 'ul#list li a[class~="foo1"]'); $this->assertTrue($expectation->test(array('link'))); $expectation = new CssSelectorExpectation($this->dom, 'ul#list li a[class~="bar1"]'); $this->assertTrue($expectation->test(array('link'))); $expectation = new CssSelectorExpectation($this->dom, 'ul#list li a[class~="foobar1"]'); $this->assertTrue($expectation->test(array('link'))); $expectation = new CssSelectorExpectation($this->dom, 'ul#list li a[class^="foo1"]'); $this->assertTrue($expectation->test(array('link'))); $expectation = new CssSelectorExpectation($this->dom, 'ul#list li a[class$="foobar1"]'); $this->assertTrue($expectation->test(array('link'))); $expectation = new CssSelectorExpectation($this->dom, 'ul#list li a[class*="oba"]'); $this->assertTrue($expectation->test(array('link'))); $expectation = new CssSelectorExpectation($this->dom, 'ul#list li a[href="http://www.google.com/"]'); $this->assertTrue($expectation->test(array('link'))); $expectation = new CssSelectorExpectation($this->dom, 'ul#anotherlist li a[class|="bar1"]'); $this->assertTrue($expectation->test(array('another link'))); $expectation = new CssSelectorExpectation($this->dom, 'ul#list li a[class*="oba"][class*="ba"]'); $this->assertTrue($expectation->test(array('link'))); $expectation = new CssSelectorExpectation($this->dom, 'p[class="myfoo"][id="mybar"]'); $this->assertTrue($expectation->test(array('myfoo bis'))); $expectation = new CssSelectorExpectation($this->dom, 'p[onclick*="a . and a #"]'); $this->assertTrue($expectation->test(array('works great'))); } function testCombinators() { $expectation = new CssSelectorExpectation($this->dom, 'body h1'); $this->assertTrue($expectation->test(array('Test page'))); $expectation = new CssSelectorExpectation($this->dom, 'div#combinators > ul > li'); $this->assertTrue($expectation->test(array('test 1', 'test 2'))); $expectation = new CssSelectorExpectation($this->dom, 'div#combinators>ul>li'); $this->assertTrue($expectation->test(array('test 1', 'test 2'))); $expectation = new CssSelectorExpectation($this->dom, 'div#combinators li + li'); $this->assertTrue($expectation->test(array('test 2', 'test 4'))); $expectation = new CssSelectorExpectation($this->dom, 'div#combinators li+li'); $this->assertTrue($expectation->test(array('test 2', 'test 4'))); $expectation = new CssSelectorExpectation($this->dom, 'h1, h2'); $this->assertTrue($expectation->test(array('Test page', 'Title 1', 'Title 2'))); $expectation = new CssSelectorExpectation($this->dom, 'h1,h2'); $this->assertTrue($expectation->test(array('Test page', 'Title 1', 'Title 2'))); $expectation = new CssSelectorExpectation($this->dom, 'h1 , h2'); $this->assertTrue($expectation->test(array('Test page', 'Title 1', 'Title 2'))); $expectation = new CssSelectorExpectation($this->dom, 'h1, h1,h1'); $this->assertTrue($expectation->test(array('Test page'))); $expectation = new CssSelectorExpectation($this->dom, 'h1,h2,h1'); $this->assertTrue($expectation->test(array('Test page', 'Title 1', 'Title 2'))); $expectation = new CssSelectorExpectation($this->dom, 'p[onclick*="a . and a #"], div#combinators > ul li + li'); $this->assertTrue($expectation->test(array('works great', 'test 2', 'test 4'))); } function testChildSelectors() { $expectation = new CssSelectorExpectation($this->dom, '.myfoo:contains("bis")'); $this->assertTrue($expectation->test(array('myfoo bis'))); $expectation = new CssSelectorExpectation($this->dom, '.myfoo:eq(1)'); $this->assertTrue($expectation->test(array('myfoo bis'))); $expectation = new CssSelectorExpectation($this->dom, '.myfoo:last'); $this->assertTrue($expectation->test(array('myfoo bis'))); $expectation = new CssSelectorExpectation($this->dom, '.myfoo:first'); $this->assertTrue($expectation->test(array('myfoo'))); $expectation = new CssSelectorExpectation($this->dom, 'h2:first'); $this->assertTrue($expectation->test(array('Title 1'))); $expectation = new CssSelectorExpectation($this->dom, 'h2:first'); $this->assertTrue($expectation->test(array('Title 1'))); $expectation = new CssSelectorExpectation($this->dom, 'p.myfoo:first'); $this->assertTrue($expectation->test(array('myfoo'))); $expectation = new CssSelectorExpectation($this->dom, 'p:lt(2)'); $this->assertTrue($expectation->test(array('header', 'multi-classes'))); $expectation = new CssSelectorExpectation($this->dom, 'p:gt(2)'); $this->assertTrue($expectation->test(array('myfoo bis', 'works great', 'First paragraph', 'Second paragraph', 'Third paragraph'))); $expectation = new CssSelectorExpectation($this->dom, 'p:odd'); $this->assertTrue($expectation->test(array('multi-classes', 'myfoo bis', 'First paragraph', 'Third paragraph'))); $expectation = new CssSelectorExpectation($this->dom, 'p:even'); $this->assertTrue($expectation->test(array('header', 'myfoo', 'works great', 'Second paragraph'))); $expectation = new CssSelectorExpectation($this->dom, '#simplelist li:first-child'); $this->assertTrue($expectation->test(array('First', 'First'))); $expectation = new CssSelectorExpectation($this->dom, '#simplelist li:nth-child(1)'); $this->assertTrue($expectation->test(array('First', 'First'))); $expectation = new CssSelectorExpectation($this->dom, '#simplelist li:nth-child(2)'); $this->assertTrue($expectation->test(array('Second with a link', 'Second'))); $expectation = new CssSelectorExpectation($this->dom, '#simplelist li:nth-child(3)'); $this->assertTrue($expectation->test(array('Third with another link'))); $expectation = new CssSelectorExpectation($this->dom, '#simplelist li:last-child'); $this->assertTrue($expectation->test(array('Second with a link', 'Third with another link'))); } } class TestsOfChildAndAdjacentSelectors extends DomTestCase { function __construct() { parent::__construct(); $html = file_get_contents(dirname(__FILE__) . '/support/child_adjacent.html'); $this->dom = new DomDocument('1.0', 'utf-8'); $this->dom->validateOnParse = true; $this->dom->loadHTML($html); } function testFirstChild() { $expectation = new CssSelectorExpectation($this->dom, 'p:first-child'); $this->assertTrue($expectation->test(array('First paragraph'))); $expectation = new CssSelectorExpectation($this->dom, 'body > p:first-child'); $this->assertTrue($expectation->test(array('First paragraph'))); $expectation = new CssSelectorExpectation($this->dom, 'body > p > a:first-child'); $this->assertTrue($expectation->test(array('paragraph'))); } function testChildren() { $expectation = new CssSelectorExpectation($this->dom, 'body > p'); $this->assertTrue($expectation->test(array('First paragraph', 'Second paragraph', 'Third paragraph'))); $expectation = new CssSelectorExpectation($this->dom, 'body > p > a'); $this->assertTrue($expectation->test(array('paragraph'))); } function testAdjacents() { $expectation = new CssSelectorExpectation($this->dom, 'p + p'); $this->assertTrue($expectation->test(array('Second paragraph', 'Third paragraph'))); $expectation = new CssSelectorExpectation($this->dom, 'body > p + p'); $this->assertTrue($expectation->test(array('Second paragraph', 'Third paragraph'))); $expectation = new CssSelectorExpectation($this->dom, 'body > p + p > a'); $this->assertTrue($expectation->test(array('paragraph'))); } }
GerHobbelt/simpletest
extensions/dom_tester/test/dom_tester_test.php
PHP
lgpl-2.1
10,540
// GtkSharp.Generation.Ctor.cs - The Constructor Generation Class. // // Author: Mike Kestner <mkestner@novell.com> // // Copyright (c) 2001-2003 Mike Kestner // Copyright (c) 2004-2005 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the GNU General Public // License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace GtkSharp.Generation { using System; using System.Collections; using System.IO; using System.Xml; public class Ctor : MethodBase { private bool preferred; private string name; private bool needs_chaining = false; private bool mini_object = false; public Ctor (XmlElement elem, ClassBase implementor) : base (elem, implementor) { if (elem.HasAttribute ("preferred")) preferred = true; if (implementor is ObjectGen || implementor is MiniObjectGen) needs_chaining = true; name = implementor.Name; mini_object = implementor is MiniObjectGen; } public bool Preferred { get { return preferred; } set { preferred = value; } } public string StaticName { get { if (!IsStatic) return String.Empty; if (Name != null && Name != String.Empty) return Name; string[] toks = CName.Substring(CName.IndexOf("new")).Split ('_'); string result = String.Empty; foreach (string tok in toks) result += tok.Substring(0,1).ToUpper() + tok.Substring(1); return result; } } void GenerateImport (StreamWriter sw) { sw.WriteLine("\t\t[DllImport(\"" + LibraryName + "\", CallingConvention = CallingConvention.Cdecl)]"); sw.WriteLine("\t\tstatic extern " + Safety + "IntPtr " + CName + "(" + Parameters.ImportSignature + ");"); sw.WriteLine(); } void GenerateStatic (GenerationInfo gen_info) { StreamWriter sw = gen_info.Writer; sw.WriteLine("\t\t" + Protection + " static " + Safety + Modifiers + name + " " + StaticName + "(" + Signature + ")"); sw.WriteLine("\t\t{"); Body.Initialize(gen_info, false, false, ""); sw.Write("\t\t\t" + name + " result = "); if (container_type is StructBase) sw.Write ("{0}.New (", name); else sw.Write ("new {0} (", name); sw.WriteLine (CName + "(" + Body.GetCallString (false) + "));"); Body.Finish (sw, ""); Body.HandleException (sw, ""); sw.WriteLine ("\t\t\treturn result;"); } public void Generate (GenerationInfo gen_info) { StreamWriter sw = gen_info.Writer; gen_info.CurrentMember = CName; GenerateImport (sw); if (IsStatic) GenerateStatic (gen_info); else { sw.WriteLine("\t\t{0} {1}{2} ({3}) {4}", Protection, Safety, name, Signature.ToString(), needs_chaining ? ": base (IntPtr.Zero)" : ""); sw.WriteLine("\t\t{"); if (needs_chaining) { sw.WriteLine ("\t\t\tif (GetType () != typeof (" + name + ")) {"); if (Parameters.Count == 0) { if (mini_object) sw.WriteLine ("\t\t\t\tCreateNativeObject ();"); else sw.WriteLine ("\t\t\t\tCreateNativeObject (new string [0], new GLib.Value[0]);"); sw.WriteLine ("\t\t\t\treturn;"); } else { ArrayList names = new ArrayList (); ArrayList values = new ArrayList (); for (int i = 0; i < Parameters.Count; i++) { Parameter p = Parameters[i]; if (container_type.GetPropertyRecursively (p.StudlyName) != null) { names.Add (p.Name); values.Add (p.Name); } else if (p.PropertyName != String.Empty) { names.Add (p.PropertyName); values.Add (p.Name); } } if (names.Count == Parameters.Count) { sw.WriteLine ("\t\t\t\tArrayList vals = new ArrayList();"); sw.WriteLine ("\t\t\t\tArrayList names = new ArrayList();"); for (int i = 0; i < names.Count; i++) { Parameter p = Parameters [i]; string indent = "\t\t\t\t"; if (p.Generatable is ClassBase && !(p.Generatable is StructBase)) { sw.WriteLine (indent + "if (" + p.Name + " != null) {"); indent += "\t"; } sw.WriteLine (indent + "names.Add (\"" + names [i] + "\");"); sw.WriteLine (indent + "vals.Add (new GLib.Value (" + values[i] + "));"); if (p.Generatable is ClassBase && !(p.Generatable is StructBase)) sw.WriteLine ("\t\t\t\t}"); } sw.WriteLine ("\t\t\t\tCreateNativeObject ((string[])names.ToArray (typeof (string)), (GLib.Value[])vals.ToArray (typeof (GLib.Value)));"); sw.WriteLine ("\t\t\t\treturn;"); } else sw.WriteLine ("\t\t\t\tthrow new InvalidOperationException (\"Can't override this constructor.\");"); } sw.WriteLine ("\t\t\t}"); } Body.Initialize(gen_info, false, false, ""); sw.WriteLine("\t\t\t{0} = {1}({2});", container_type.AssignToName, CName, Body.GetCallString (false)); Body.Finish (sw, ""); Body.HandleException (sw, ""); } sw.WriteLine("\t\t}"); sw.WriteLine(); Statistics.CtorCount++; } } }
Forage/gstreamer-sharp
generator/Ctor.cs
C#
lgpl-2.1
5,621
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2013 Live Networks, Inc. All rights reserved. // A sink that generates an AVI file from a composite media session // Implementation #include "AVIFileSink.hh" #include "InputFile.hh" #include "OutputFile.hh" #include "GroupsockHelper.hh" #define fourChar(x,y,z,w) ( ((w)<<24)|((z)<<16)|((y)<<8)|(x) )/*little-endian*/ ////////// AVISubsessionIOState /////////// // A structure used to represent the I/O state of each input 'subsession': class SubsessionBuffer { public: SubsessionBuffer(unsigned bufferSize) : fBufferSize(bufferSize) { reset(); fData = new unsigned char[bufferSize]; } virtual ~SubsessionBuffer() { delete[] fData; } void reset() { fBytesInUse = 0; } void addBytes(unsigned numBytes) { fBytesInUse += numBytes; } unsigned char* dataStart() { return &fData[0]; } unsigned char* dataEnd() { return &fData[fBytesInUse]; } unsigned bytesInUse() const { return fBytesInUse; } unsigned bytesAvailable() const { return fBufferSize - fBytesInUse; } void setPresentationTime(struct timeval const& presentationTime) { fPresentationTime = presentationTime; } struct timeval const& presentationTime() const {return fPresentationTime;} private: unsigned fBufferSize; struct timeval fPresentationTime; unsigned char* fData; unsigned fBytesInUse; }; class AVISubsessionIOState { public: AVISubsessionIOState(AVIFileSink& sink, MediaSubsession& subsession); virtual ~AVISubsessionIOState(); void setAVIstate(unsigned subsessionIndex); void setFinalAVIstate(); void afterGettingFrame(unsigned packetDataSize, struct timeval presentationTime); void onSourceClosure(); UsageEnvironment& envir() const { return fOurSink.envir(); } public: SubsessionBuffer *fBuffer, *fPrevBuffer; AVIFileSink& fOurSink; MediaSubsession& fOurSubsession; unsigned short fLastPacketRTPSeqNum; Boolean fOurSourceIsActive; struct timeval fPrevPresentationTime; unsigned fMaxBytesPerSecond; Boolean fIsVideo, fIsAudio, fIsByteSwappedAudio; unsigned fAVISubsessionTag; unsigned fAVICodecHandlerType; unsigned fAVISamplingFrequency; // for audio u_int16_t fWAVCodecTag; // for audio unsigned fAVIScale; unsigned fAVIRate; unsigned fAVISize; unsigned fNumFrames; unsigned fSTRHFrameCountPosition; private: void useFrame(SubsessionBuffer& buffer); }; ///////// AVIIndexRecord definition & implementation ////////// class AVIIndexRecord { public: AVIIndexRecord(unsigned chunkId, unsigned flags, unsigned offset, unsigned size) : fNext(NULL), fChunkId(chunkId), fFlags(flags), fOffset(offset), fSize(size) { } AVIIndexRecord*& next() { return fNext; } unsigned chunkId() const { return fChunkId; } unsigned flags() const { return fFlags; } unsigned offset() const { return fOffset; } unsigned size() const { return fSize; } private: AVIIndexRecord* fNext; unsigned fChunkId; unsigned fFlags; unsigned fOffset; unsigned fSize; }; ////////// AVIFileSink implementation ////////// AVIFileSink::AVIFileSink(UsageEnvironment& env, MediaSession& inputSession, char const* outputFileName, unsigned bufferSize, unsigned short movieWidth, unsigned short movieHeight, unsigned movieFPS, Boolean packetLossCompensate) : Medium(env), fInputSession(inputSession), fIndexRecordsHead(NULL), fIndexRecordsTail(NULL), fNumIndexRecords(0), fBufferSize(bufferSize), fPacketLossCompensate(packetLossCompensate), fAreCurrentlyBeingPlayed(False), fNumSubsessions(0), fNumBytesWritten(0), fHaveCompletedOutputFile(False), fMovieWidth(movieWidth), fMovieHeight(movieHeight), fMovieFPS(movieFPS) { fOutFid = OpenOutputFile(env, outputFileName); if (fOutFid == NULL) return; // Set up I/O state for each input subsession: MediaSubsessionIterator iter(fInputSession); MediaSubsession* subsession; while ((subsession = iter.next()) != NULL) { // Ignore subsessions without a data source: FramedSource* subsessionSource = subsession->readSource(); if (subsessionSource == NULL) continue; // If "subsession's" SDP description specified screen dimension // or frame rate parameters, then use these. if (subsession->videoWidth() != 0) { fMovieWidth = subsession->videoWidth(); } if (subsession->videoHeight() != 0) { fMovieHeight = subsession->videoHeight(); } if (subsession->videoFPS() != 0) { fMovieFPS = subsession->videoFPS(); } AVISubsessionIOState* ioState = new AVISubsessionIOState(*this, *subsession); subsession->miscPtr = (void*)ioState; // Also set a 'BYE' handler for this subsession's RTCP instance: if (subsession->rtcpInstance() != NULL) { subsession->rtcpInstance()->setByeHandler(onRTCPBye, ioState); } ++fNumSubsessions; } // Begin by writing an AVI header: addFileHeader_AVI(); } AVIFileSink::~AVIFileSink() { completeOutputFile(); // Then, stop streaming and delete each active "AVISubsessionIOState": MediaSubsessionIterator iter(fInputSession); MediaSubsession* subsession; while ((subsession = iter.next()) != NULL) { subsession->readSource()->stopGettingFrames(); AVISubsessionIOState* ioState = (AVISubsessionIOState*)(subsession->miscPtr); if (ioState == NULL) continue; delete ioState; } // Then, delete the index records: AVIIndexRecord* cur = fIndexRecordsHead; while (cur != NULL) { AVIIndexRecord* next = cur->next(); delete cur; cur = next; } // Finally, close our output file: CloseOutputFile(fOutFid); } AVIFileSink* AVIFileSink ::createNew(UsageEnvironment& env, MediaSession& inputSession, char const* outputFileName, unsigned bufferSize, unsigned short movieWidth, unsigned short movieHeight, unsigned movieFPS, Boolean packetLossCompensate) { AVIFileSink* newSink = new AVIFileSink(env, inputSession, outputFileName, bufferSize, movieWidth, movieHeight, movieFPS, packetLossCompensate); if (newSink == NULL || newSink->fOutFid == NULL) { Medium::close(newSink); return NULL; } return newSink; } Boolean AVIFileSink::startPlaying(afterPlayingFunc* afterFunc, void* afterClientData) { // Make sure we're not already being played: if (fAreCurrentlyBeingPlayed) { envir().setResultMsg("This sink has already been played"); return False; } fAreCurrentlyBeingPlayed = True; fAfterFunc = afterFunc; fAfterClientData = afterClientData; return continuePlaying(); } Boolean AVIFileSink::continuePlaying() { // Run through each of our input session's 'subsessions', // asking for a frame from each one: Boolean haveActiveSubsessions = False; MediaSubsessionIterator iter(fInputSession); MediaSubsession* subsession; while ((subsession = iter.next()) != NULL) { FramedSource* subsessionSource = subsession->readSource(); if (subsessionSource == NULL) continue; if (subsessionSource->isCurrentlyAwaitingData()) continue; AVISubsessionIOState* ioState = (AVISubsessionIOState*)(subsession->miscPtr); if (ioState == NULL) continue; haveActiveSubsessions = True; unsigned char* toPtr = ioState->fBuffer->dataEnd(); unsigned toSize = ioState->fBuffer->bytesAvailable(); subsessionSource->getNextFrame(toPtr, toSize, afterGettingFrame, ioState, onSourceClosure, ioState); } if (!haveActiveSubsessions) { envir().setResultMsg("No subsessions are currently active"); return False; } return True; } void AVIFileSink ::afterGettingFrame(void* clientData, unsigned packetDataSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned /*durationInMicroseconds*/) { AVISubsessionIOState* ioState = (AVISubsessionIOState*)clientData; if (numTruncatedBytes > 0) { ioState->envir() << "AVIFileSink::afterGettingFrame(): The input frame data was too large for our buffer. " << numTruncatedBytes << " bytes of trailing data was dropped! Correct this by increasing the \"bufferSize\" parameter in the \"createNew()\" call.\n"; } ioState->afterGettingFrame(packetDataSize, presentationTime); } void AVIFileSink::onSourceClosure(void* clientData) { AVISubsessionIOState* ioState = (AVISubsessionIOState*)clientData; ioState->onSourceClosure(); } void AVIFileSink::onSourceClosure1() { // Check whether *all* of the subsession sources have closed. // If not, do nothing for now: MediaSubsessionIterator iter(fInputSession); MediaSubsession* subsession; while ((subsession = iter.next()) != NULL) { AVISubsessionIOState* ioState = (AVISubsessionIOState*)(subsession->miscPtr); if (ioState == NULL) continue; if (ioState->fOurSourceIsActive) return; // this source hasn't closed } completeOutputFile(); // Call our specified 'after' function: if (fAfterFunc != NULL) { (*fAfterFunc)(fAfterClientData); } } void AVIFileSink::onRTCPBye(void* clientData) { AVISubsessionIOState* ioState = (AVISubsessionIOState*)clientData; struct timeval timeNow; gettimeofday(&timeNow, NULL); unsigned secsDiff = timeNow.tv_sec - ioState->fOurSink.fStartTime.tv_sec; MediaSubsession& subsession = ioState->fOurSubsession; ioState->envir() << "Received RTCP \"BYE\" on \"" << subsession.mediumName() << "/" << subsession.codecName() << "\" subsession (after " << secsDiff << " seconds)\n"; // Handle the reception of a RTCP "BYE" as if the source had closed: ioState->onSourceClosure(); } void AVIFileSink::addIndexRecord(AVIIndexRecord* newIndexRecord) { if (fIndexRecordsHead == NULL) { fIndexRecordsHead = newIndexRecord; } else { fIndexRecordsTail->next() = newIndexRecord; } fIndexRecordsTail = newIndexRecord; ++fNumIndexRecords; } void AVIFileSink::completeOutputFile() { if (fHaveCompletedOutputFile || fOutFid == NULL) return; // Update various AVI 'size' fields to take account of the codec data that // we've now written to the file: unsigned maxBytesPerSecond = 0; unsigned numVideoFrames = 0; unsigned numAudioFrames = 0; //// Subsession-specific fields: MediaSubsessionIterator iter(fInputSession); MediaSubsession* subsession; while ((subsession = iter.next()) != NULL) { AVISubsessionIOState* ioState = (AVISubsessionIOState*)(subsession->miscPtr); if (ioState == NULL) continue; maxBytesPerSecond += ioState->fMaxBytesPerSecond; setWord(ioState->fSTRHFrameCountPosition, ioState->fNumFrames); if (ioState->fIsVideo) numVideoFrames = ioState->fNumFrames; else if (ioState->fIsAudio) numAudioFrames = ioState->fNumFrames; } //// Global fields: add4ByteString("idx1"); addWord(fNumIndexRecords*4*4); // the size of all of the index records, which come next: for (AVIIndexRecord* indexRecord = fIndexRecordsHead; indexRecord != NULL; indexRecord = indexRecord->next()) { addWord(indexRecord->chunkId()); addWord(indexRecord->flags()); addWord(indexRecord->offset()); addWord(indexRecord->size()); } fRIFFSizeValue += fNumBytesWritten; setWord(fRIFFSizePosition, fRIFFSizeValue); setWord(fAVIHMaxBytesPerSecondPosition, maxBytesPerSecond); setWord(fAVIHFrameCountPosition, numVideoFrames > 0 ? numVideoFrames : numAudioFrames); fMoviSizeValue += fNumBytesWritten; setWord(fMoviSizePosition, fMoviSizeValue); // We're done: fHaveCompletedOutputFile = True; } ////////// AVISubsessionIOState implementation /////////// AVISubsessionIOState::AVISubsessionIOState(AVIFileSink& sink, MediaSubsession& subsession) : fOurSink(sink), fOurSubsession(subsession), fMaxBytesPerSecond(0), fIsVideo(False), fIsAudio(False), fIsByteSwappedAudio(False), fNumFrames(0) { fBuffer = new SubsessionBuffer(fOurSink.fBufferSize); fPrevBuffer = sink.fPacketLossCompensate ? new SubsessionBuffer(fOurSink.fBufferSize) : NULL; FramedSource* subsessionSource = subsession.readSource(); fOurSourceIsActive = subsessionSource != NULL; fPrevPresentationTime.tv_sec = 0; fPrevPresentationTime.tv_usec = 0; } AVISubsessionIOState::~AVISubsessionIOState() { delete fBuffer; delete fPrevBuffer; } void AVISubsessionIOState::setAVIstate(unsigned subsessionIndex) { fIsVideo = strcmp(fOurSubsession.mediumName(), "video") == 0; fIsAudio = strcmp(fOurSubsession.mediumName(), "audio") == 0; if (fIsVideo) { fAVISubsessionTag = fourChar('0'+subsessionIndex/10,'0'+subsessionIndex%10,'d','c'); if (strcmp(fOurSubsession.codecName(), "JPEG") == 0) { fAVICodecHandlerType = fourChar('m','j','p','g'); } else if (strcmp(fOurSubsession.codecName(), "MP4V-ES") == 0) { fAVICodecHandlerType = fourChar('D','I','V','X'); } else if (strcmp(fOurSubsession.codecName(), "MPV") == 0) { fAVICodecHandlerType = fourChar('m','p','g','1'); // what about MPEG-2? } else if (strcmp(fOurSubsession.codecName(), "H263-1998") == 0 || strcmp(fOurSubsession.codecName(), "H263-2000") == 0) { fAVICodecHandlerType = fourChar('H','2','6','3'); } else if (strcmp(fOurSubsession.codecName(), "H264") == 0) { fAVICodecHandlerType = fourChar('H','2','6','4'); } else { fAVICodecHandlerType = fourChar('?','?','?','?'); } fAVIScale = 1; // ??? ##### fAVIRate = fOurSink.fMovieFPS; // ??? ##### fAVISize = fOurSink.fMovieWidth*fOurSink.fMovieHeight*3; // ??? ##### } else if (fIsAudio) { fIsByteSwappedAudio = False; // by default fAVISubsessionTag = fourChar('0'+subsessionIndex/10,'0'+subsessionIndex%10,'w','b'); fAVICodecHandlerType = 1; // ??? #### unsigned numChannels = fOurSubsession.numChannels(); fAVISamplingFrequency = fOurSubsession.rtpTimestampFrequency(); // default if (strcmp(fOurSubsession.codecName(), "L16") == 0) { fIsByteSwappedAudio = True; // need to byte-swap data before writing it fWAVCodecTag = 0x0001; fAVIScale = fAVISize = 2*numChannels; // 2 bytes/sample fAVIRate = fAVISize*fAVISamplingFrequency; } else if (strcmp(fOurSubsession.codecName(), "L8") == 0) { fWAVCodecTag = 0x0001; fAVIScale = fAVISize = numChannels; // 1 byte/sample fAVIRate = fAVISize*fAVISamplingFrequency; } else if (strcmp(fOurSubsession.codecName(), "PCMA") == 0) { fWAVCodecTag = 0x0006; fAVIScale = fAVISize = numChannels; // 1 byte/sample fAVIRate = fAVISize*fAVISamplingFrequency; } else if (strcmp(fOurSubsession.codecName(), "PCMU") == 0) { fWAVCodecTag = 0x0007; fAVIScale = fAVISize = numChannels; // 1 byte/sample fAVIRate = fAVISize*fAVISamplingFrequency; } else if (strcmp(fOurSubsession.codecName(), "MPA") == 0) { fWAVCodecTag = 0x0050; fAVIScale = fAVISize = 1; fAVIRate = 0; // ??? ##### } else { fWAVCodecTag = 0x0001; // ??? ##### fAVIScale = fAVISize = 1; fAVIRate = 0; // ??? ##### } } else { // unknown medium fAVISubsessionTag = fourChar('0'+subsessionIndex/10,'0'+subsessionIndex%10,'?','?'); fAVICodecHandlerType = 0; fAVIScale = fAVISize = 1; fAVIRate = 0; // ??? ##### } } void AVISubsessionIOState::afterGettingFrame(unsigned packetDataSize, struct timeval presentationTime) { // Begin by checking whether there was a gap in the RTP stream. // If so, try to compensate for this (if desired): unsigned short rtpSeqNum = fOurSubsession.rtpSource()->curPacketRTPSeqNum(); if (fOurSink.fPacketLossCompensate && fPrevBuffer->bytesInUse() > 0) { short seqNumGap = rtpSeqNum - fLastPacketRTPSeqNum; for (short i = 1; i < seqNumGap; ++i) { // Insert a copy of the previous frame, to compensate for the loss: useFrame(*fPrevBuffer); } } fLastPacketRTPSeqNum = rtpSeqNum; // Now, continue working with the frame that we just got if (fBuffer->bytesInUse() == 0) { fBuffer->setPresentationTime(presentationTime); } fBuffer->addBytes(packetDataSize); useFrame(*fBuffer); if (fOurSink.fPacketLossCompensate) { // Save this frame, in case we need it for recovery: SubsessionBuffer* tmp = fPrevBuffer; // assert: != NULL fPrevBuffer = fBuffer; fBuffer = tmp; } fBuffer->reset(); // for the next input // Now, try getting more frames: fOurSink.continuePlaying(); } void AVISubsessionIOState::useFrame(SubsessionBuffer& buffer) { unsigned char* const frameSource = buffer.dataStart(); unsigned const frameSize = buffer.bytesInUse(); struct timeval const& presentationTime = buffer.presentationTime(); if (fPrevPresentationTime.tv_usec != 0||fPrevPresentationTime.tv_sec != 0) { int uSecondsDiff = (presentationTime.tv_sec - fPrevPresentationTime.tv_sec)*1000000 + (presentationTime.tv_usec - fPrevPresentationTime.tv_usec); if (uSecondsDiff > 0) { unsigned bytesPerSecond = (unsigned)((frameSize*1000000.0)/uSecondsDiff); if (bytesPerSecond > fMaxBytesPerSecond) { fMaxBytesPerSecond = bytesPerSecond; } } } fPrevPresentationTime = presentationTime; if (fIsByteSwappedAudio) { // We need to swap the 16-bit audio samples from big-endian // to little-endian order, before writing them to a file: for (unsigned i = 0; i < frameSize; i += 2) { unsigned char tmp = frameSource[i]; frameSource[i] = frameSource[i+1]; frameSource[i+1] = tmp; } } // Add an index record for this frame: AVIIndexRecord* newIndexRecord = new AVIIndexRecord(fAVISubsessionTag, // chunk id frameSource[0] == 0x67 ? 0x10 : 0, // flags fOurSink.fMoviSizePosition + 8 + fOurSink.fNumBytesWritten, // offset (note: 8 == size + 'movi') frameSize + 4); // size fOurSink.addIndexRecord(newIndexRecord); // Write the data into the file: fOurSink.fNumBytesWritten += fOurSink.addWord(fAVISubsessionTag); if (strcmp(fOurSubsession.codecName(), "H264") == 0) { // Insert a 'start code' (0x00 0x00 0x00 0x01) in front of the frame: fOurSink.fNumBytesWritten += fOurSink.addWord(4+frameSize); fOurSink.fNumBytesWritten += fOurSink.addWord(fourChar(0x00, 0x00, 0x00, 0x01));//add start code } else { fOurSink.fNumBytesWritten += fOurSink.addWord(frameSize); } fwrite(frameSource, 1, frameSize, fOurSink.fOutFid); fOurSink.fNumBytesWritten += frameSize; // Pad to an even length: if (frameSize%2 != 0) fOurSink.fNumBytesWritten += fOurSink.addByte(0); ++fNumFrames; } void AVISubsessionIOState::onSourceClosure() { fOurSourceIsActive = False; fOurSink.onSourceClosure1(); } ////////// AVI-specific implementation ////////// unsigned AVIFileSink::addWord(unsigned word) { // Add "word" to the file in little-endian order: addByte(word); addByte(word>>8); addByte(word>>16); addByte(word>>24); return 4; } unsigned AVIFileSink::addHalfWord(unsigned short halfWord) { // Add "halfWord" to the file in little-endian order: addByte((unsigned char)halfWord); addByte((unsigned char)(halfWord>>8)); return 2; } unsigned AVIFileSink::addZeroWords(unsigned numWords) { for (unsigned i = 0; i < numWords; ++i) { addWord(0); } return numWords*4; } unsigned AVIFileSink::add4ByteString(char const* str) { addByte(str[0]); addByte(str[1]); addByte(str[2]); addByte(str[3] == '\0' ? ' ' : str[3]); // e.g., for "AVI " return 4; } void AVIFileSink::setWord(unsigned filePosn, unsigned size) { do { if (SeekFile64(fOutFid, filePosn, SEEK_SET) < 0) break; addWord(size); if (SeekFile64(fOutFid, 0, SEEK_END) < 0) break; // go back to where we were return; } while (0); // One of the SeekFile64()s failed, probable because we're not a seekable file envir() << "AVIFileSink::setWord(): SeekFile64 failed (err " << envir().getErrno() << ")\n"; } // Methods for writing particular file headers. Note the following macros: #define addFileHeader(tag,name) \ unsigned AVIFileSink::addFileHeader_##name() { \ add4ByteString("" #tag ""); \ unsigned headerSizePosn = (unsigned)TellFile64(fOutFid); addWord(0); \ add4ByteString("" #name ""); \ unsigned ignoredSize = 8;/*don't include size of tag or size fields*/ \ unsigned size = 12 #define addFileHeader1(name) \ unsigned AVIFileSink::addFileHeader_##name() { \ add4ByteString("" #name ""); \ unsigned headerSizePosn = (unsigned)TellFile64(fOutFid); addWord(0); \ unsigned ignoredSize = 8;/*don't include size of name or size fields*/ \ unsigned size = 8 #define addFileHeaderEnd \ setWord(headerSizePosn, size-ignoredSize); \ return size; \ } addFileHeader(RIFF,AVI); size += addFileHeader_hdrl(); size += addFileHeader_movi(); fRIFFSizePosition = headerSizePosn; fRIFFSizeValue = size-ignoredSize; addFileHeaderEnd; addFileHeader(LIST,hdrl); size += addFileHeader_avih(); // Then, add a "strl" header for each subsession (stream): // (Make the video subsession (if any) come before the audio subsession.) unsigned subsessionCount = 0; MediaSubsessionIterator iter(fInputSession); MediaSubsession* subsession; while ((subsession = iter.next()) != NULL) { fCurrentIOState = (AVISubsessionIOState*)(subsession->miscPtr); if (fCurrentIOState == NULL) continue; if (strcmp(subsession->mediumName(), "video") != 0) continue; fCurrentIOState->setAVIstate(subsessionCount++); size += addFileHeader_strl(); } iter.reset(); while ((subsession = iter.next()) != NULL) { fCurrentIOState = (AVISubsessionIOState*)(subsession->miscPtr); if (fCurrentIOState == NULL) continue; if (strcmp(subsession->mediumName(), "video") == 0) continue; fCurrentIOState->setAVIstate(subsessionCount++); size += addFileHeader_strl(); } // Then add another JUNK entry ++fJunkNumber; size += addFileHeader_JUNK(); addFileHeaderEnd; #define AVIF_HASINDEX 0x00000010 // Index at end of file? #define AVIF_MUSTUSEINDEX 0x00000020 #define AVIF_ISINTERLEAVED 0x00000100 #define AVIF_TRUSTCKTYPE 0x00000800 // Use CKType to find key frames? #define AVIF_WASCAPTUREFILE 0x00010000 #define AVIF_COPYRIGHTED 0x00020000 addFileHeader1(avih); unsigned usecPerFrame = fMovieFPS == 0 ? 0 : 1000000/fMovieFPS; size += addWord(usecPerFrame); // dwMicroSecPerFrame fAVIHMaxBytesPerSecondPosition = (unsigned)TellFile64(fOutFid); size += addWord(0); // dwMaxBytesPerSec (fill in later) size += addWord(0); // dwPaddingGranularity size += addWord(AVIF_TRUSTCKTYPE|AVIF_HASINDEX|AVIF_ISINTERLEAVED); // dwFlags fAVIHFrameCountPosition = (unsigned)TellFile64(fOutFid); size += addWord(0); // dwTotalFrames (fill in later) size += addWord(0); // dwInitialFrame size += addWord(fNumSubsessions); // dwStreams size += addWord(fBufferSize); // dwSuggestedBufferSize size += addWord(fMovieWidth); // dwWidth size += addWord(fMovieHeight); // dwHeight size += addZeroWords(4); // dwReserved addFileHeaderEnd; addFileHeader(LIST,strl); size += addFileHeader_strh(); size += addFileHeader_strf(); fJunkNumber = 0; size += addFileHeader_JUNK(); addFileHeaderEnd; addFileHeader1(strh); size += add4ByteString(fCurrentIOState->fIsVideo ? "vids" : fCurrentIOState->fIsAudio ? "auds" : "????"); // fccType size += addWord(fCurrentIOState->fAVICodecHandlerType); // fccHandler size += addWord(0); // dwFlags size += addWord(0); // wPriority + wLanguage size += addWord(0); // dwInitialFrames size += addWord(fCurrentIOState->fAVIScale); // dwScale size += addWord(fCurrentIOState->fAVIRate); // dwRate size += addWord(0); // dwStart fCurrentIOState->fSTRHFrameCountPosition = (unsigned)TellFile64(fOutFid); size += addWord(0); // dwLength (fill in later) size += addWord(fBufferSize); // dwSuggestedBufferSize size += addWord((unsigned)-1); // dwQuality size += addWord(fCurrentIOState->fAVISize); // dwSampleSize size += addWord(0); // rcFrame (start) if (fCurrentIOState->fIsVideo) { size += addHalfWord(fMovieWidth); size += addHalfWord(fMovieHeight); } else { size += addWord(0); } addFileHeaderEnd; addFileHeader1(strf); if (fCurrentIOState->fIsVideo) { // Add a BITMAPINFO header: unsigned extraDataSize = 0; size += addWord(10*4 + extraDataSize); // size size += addWord(fMovieWidth); size += addWord(fMovieHeight); size += addHalfWord(1); // planes size += addHalfWord(24); // bits-per-sample ##### size += addWord(fCurrentIOState->fAVICodecHandlerType); // compr. type size += addWord(fCurrentIOState->fAVISize); size += addZeroWords(4); // ??? ##### // Later, add extra data here (if any) ##### } else if (fCurrentIOState->fIsAudio) { // Add a WAVFORMATEX header: size += addHalfWord(fCurrentIOState->fWAVCodecTag); unsigned numChannels = fCurrentIOState->fOurSubsession.numChannels(); size += addHalfWord(numChannels); size += addWord(fCurrentIOState->fAVISamplingFrequency); size += addWord(fCurrentIOState->fAVIRate); // bytes per second size += addHalfWord(fCurrentIOState->fAVISize); // block alignment unsigned bitsPerSample = (fCurrentIOState->fAVISize*8)/numChannels; size += addHalfWord(bitsPerSample); if (strcmp(fCurrentIOState->fOurSubsession.codecName(), "MPA") == 0) { // Assume MPEG layer II audio (not MP3): ##### size += addHalfWord(22); // wav_extra_size size += addHalfWord(2); // fwHeadLayer size += addWord(8*fCurrentIOState->fAVIRate); // dwHeadBitrate ##### size += addHalfWord(numChannels == 2 ? 1: 8); // fwHeadMode size += addHalfWord(0); // fwHeadModeExt size += addHalfWord(1); // wHeadEmphasis size += addHalfWord(16); // fwHeadFlags size += addWord(0); // dwPTSLow size += addWord(0); // dwPTSHigh } } addFileHeaderEnd; #define AVI_MASTER_INDEX_SIZE 256 addFileHeader1(JUNK); if (fJunkNumber == 0) { size += addHalfWord(4); // wLongsPerEntry size += addHalfWord(0); // bIndexSubType + bIndexType size += addWord(0); // nEntriesInUse ##### size += addWord(fCurrentIOState->fAVISubsessionTag); // dwChunkId size += addZeroWords(2); // dwReserved size += addZeroWords(AVI_MASTER_INDEX_SIZE*4); } else { size += add4ByteString("odml"); size += add4ByteString("dmlh"); unsigned wtfCount = 248; size += addWord(wtfCount); // ??? ##### size += addZeroWords(wtfCount/4); } addFileHeaderEnd; addFileHeader(LIST,movi); fMoviSizePosition = headerSizePosn; fMoviSizeValue = size-ignoredSize; addFileHeaderEnd;
ph1ee/liveMedia
liveMedia/AVIFileSink.cpp
C++
lgpl-2.1
27,532
/** * Helios, OpenSource Monitoring * Brought to you by the Helios Development Group * * Copyright 2014, Helios Development Group and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package org.helios.rindle.store.chronicle; import java.nio.charset.Charset; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import cern.colt.Arrays; import com.higherfrequencytrading.chronicle.Excerpt; import com.higherfrequencytrading.chronicle.ExcerptMarshallable; import com.higherfrequencytrading.chronicle.impl.IndexedChronicle; import com.higherfrequencytrading.chronicle.tools.ChronicleTools; /** * <p>Title: ChronicleCacheEntry</p> * <p>Description: A marshallable cache entry pojo representing a metric</p> * <p>Company: Helios Development Group LLC</p> * @author Whitehead (nwhitehead AT heliosdev DOT org) * <p><code>org.helios.rindle.store.ChronicleCacheEntry</code></p> */ public class ChronicleCacheEntry implements ExcerptMarshallable { /** The metric global ID */ protected long globalId = -1L; /** The metric fully qualified name */ protected String metricName = null; /** The metric opaque key */ protected byte[] opaqueKey = null; /** The timestamp the metric was created */ protected long timestamp = -1L; /** Static class logger */ protected static final Logger LOG = LogManager.getLogger(ChronicleCacheEntry.class); /** The chronicle cache instance */ protected static final ChronicleCache cache = ChronicleCache.getInstance(); /** The default charset */ public static final Charset CHARSET = Charset.defaultCharset(); /** The cache no entry value, meaning a non-existent value not in the cache */ public static final long NO_ENTRY_VALUE = -1L; /** A const null entry */ private static final ChronicleCacheEntry NULL_ENTRY = new ChronicleCacheEntry(NO_ENTRY_VALUE); /** * Creates a new ChronicleCacheEntry and saves it to the chronicle cache, populating the new global id in the process * @param metricName The optional metric name * @param opaqueKey The optional opaque key * @return the saved ChronicleCacheEntry */ public static ChronicleCacheEntry newEntry(String metricName, byte[] opaqueKey) { ChronicleCacheEntry entry = new ChronicleCacheEntry(-1L, metricName, opaqueKey); long _gid = NO_ENTRY_VALUE; if(metricName!=null) { _gid = cache.getNameCache().get(metricName); } if(opaqueKey!=null && _gid == NO_ENTRY_VALUE) { _gid = cache.getOpaqueCache().get(opaqueKey); } if(_gid != NO_ENTRY_VALUE) { return ChronicleCacheEntry.load(_gid, null); } return cache.getWriter().writeEntry(entry); } /** * Loads a ChronicleCacheEntry * @param globalId the global id * @param exc The optional chronicle excerpt. If null, a new excerpt will be created and closed on load completion. * @return the loaded ChronicleCacheEntry */ public static ChronicleCacheEntry load(long globalId, Excerpt exc) { if(globalId==NO_ENTRY_VALUE) return NULL_ENTRY; final boolean newExcerpt = exc==null; if(newExcerpt) exc = cache.newExcerpt(); try { ChronicleCacheEntry entry = new ChronicleCacheEntry(globalId); exc.index(globalId); entry.readMarshallable(exc); return entry; } finally { if(newExcerpt) try { exc.close(); } catch (Exception ex) {/* No Op */} } } /** * Loads a ChronicleCacheEntry * @param metricName The fully qualified metric name * @param exc The optional chronicle excerpt. If null, a new excerpt will be created and closed on load completion. * @return the loaded ChronicleCacheEntry */ public static ChronicleCacheEntry load(String metricName, Excerpt exc) { if(metricName==null) throw new IllegalArgumentException("The passed metric name was null"); long _gid = cache.getNameCache().get(metricName); return load(_gid, exc); } /** * Loads a ChronicleCacheEntry * @param opaqueKey The metric's opaque key * @param exc The optional chronicle excerpt. If null, a new excerpt will be created and closed on load completion. * @return the loaded ChronicleCacheEntry */ public static ChronicleCacheEntry load(byte[] opaqueKey, Excerpt exc) { if(opaqueKey==null) throw new IllegalArgumentException("The passed metric opaque key was null"); long _gid = cache.getOpaqueCache().get(opaqueKey); return load(_gid, exc); } /** * Creates a new ChronicleCacheEntry and saves it to the chronicle cache, populating the new global id in the process * @param metricName The optional metric name * @return the saved ChronicleCacheEntry global id */ public static long newEntry(String metricName) { return cache.getWriter().newMetricEntry(metricName); } /** * Creates a new ID only ChronicleCacheEntry and saves it to the chronicle cache, populating the new global id in the process * @param opaqueKey The optional opaqueKey * @return the saved ChronicleCacheEntry global id */ public static long newEntry(byte[] opaqueKey) { return cache.getWriter().newMetricEntry(opaqueKey); } /** * Creates a new ChronicleCacheEntry and saves it to the chronicle cache, populating the new global id in the process * @return the saved ChronicleCacheEntry global id */ public static long newEntry() { return cache.getWriter().newMetricEntry(); } /** * Creates an unsaved stub with a no-entry value global id * @param metricName The optional metric name * @param opaqueKey The optional metric opaque key * @return the ChronicleCacheEntry stub */ public static ChronicleCacheEntry stub(String metricName, byte[] opaqueKey) { return new ChronicleCacheEntry(IKeyCache.NO_ENTRY_VALUE, metricName, opaqueKey); } /** * Creates an unsaved stub * @param globalId The global id * @param metricName The optional metric name * @param opaqueKey The optional metric opaque key * @return the ChronicleCacheEntry stub */ public static ChronicleCacheEntry stub(long globalId, String metricName, byte[] opaqueKey) { return new ChronicleCacheEntry(globalId, metricName, opaqueKey); } /** * Creates a new ChronicleCacheEntry * @param gid The assigned global id * @param metricName The optional metric name * @param opaqueKey The optional metric opaque key */ private ChronicleCacheEntry(long gid, String metricName, byte[] opaqueKey) { globalId = gid; this.metricName = metricName; this.opaqueKey = opaqueKey; } private ChronicleCacheEntry(long globalId) { this.globalId = globalId; } /** * {@inheritDoc} * @see com.higherfrequencytrading.chronicle.ExcerptMarshallable#readMarshallable(com.higherfrequencytrading.chronicle.Excerpt) */ @Override public void readMarshallable(Excerpt in) throws IllegalStateException { in.position(0); try { if(in.readByte()==0) { globalId = -1L; metricName = null; opaqueKey = null; timestamp = -1L; } else { globalId = in.index(); timestamp = in.readLong(); int stringSize = in.readInt(); int byteSize = in.readInt(); byte[] bytes = null; if(stringSize>0) { bytes = new byte[stringSize]; in.read(bytes); metricName = new String(bytes); bytes = null; } else { metricName = null; } if(byteSize>0) { opaqueKey = new byte[byteSize]; in.read(opaqueKey); } else { opaqueKey = null; } } } catch (Exception ex) { try { LOG.error("Failed to read from excerpt. id: {}, size: {}, cap: {}", in.index(), in.size(), in.capacity()); } catch (Exception x) {/* No Op */} throw new RuntimeException("Failed to read from excerpt", ex); } } /** * {@inheritDoc} * @see com.higherfrequencytrading.chronicle.ExcerptMarshallable#writeMarshallable(com.higherfrequencytrading.chronicle.Excerpt) */ @Override public void writeMarshallable(Excerpt out) { globalId = cache.getWriter().newMetricEntry(metricName, opaqueKey); } /** * Indicates if this entry is null * @return true if this entry is null, false otherwise */ public boolean isNull() { return globalId==-1L; } /** * Returns the metric global ID * @return the globalId */ public long getGlobalId() { return globalId; } /** * Returns the metric name * @return the metricName */ public String getMetricName() { return metricName; } /** * Returns the opaque key * @return the opaqueKey */ public byte[] getOpaqueKey() { return opaqueKey; } /** * {@inheritDoc} * @see java.lang.Object#toString() */ public String toString() { StringBuilder b = new StringBuilder("Metric [gid:").append(globalId).append(","); if(metricName!=null) b.append("name:").append(metricName).append(","); if(opaqueKey!=null) b.append("okey:").append(Arrays.toString(opaqueKey)).append(","); return b.deleteCharAt(b.length()-1).append("]").toString(); } /** * {@inheritDoc} * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (globalId ^ (globalId >>> 32)); result = prime * result + ((metricName == null) ? 0 : metricName.hashCode()); result = prime * result + java.util.Arrays.hashCode(opaqueKey); return result; } /** * {@inheritDoc} * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ChronicleCacheEntry other = (ChronicleCacheEntry) obj; if(globalId != IKeyCache.NO_ENTRY_VALUE && other.globalId != IKeyCache.NO_ENTRY_VALUE) { if (globalId != other.globalId) return false; } if (metricName == null) { if (other.metricName != null) return false; } else if (!metricName.equals(other.metricName)) return false; if (!java.util.Arrays.equals(opaqueKey, other.opaqueKey)) return false; return true; } }
nickman/Rindle
pag-core/src/main/java/org/helios/rindle/store/chronicle/ChronicleCacheEntry.java
Java
lgpl-2.1
10,737
// The libMesh Finite Element Library. // Copyright (C) 2002-2020 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh/checkpoint_io.h" // Local includes #include "libmesh/boundary_info.h" #include "libmesh/distributed_mesh.h" #include "libmesh/elem.h" #include "libmesh/enum_xdr_mode.h" #include "libmesh/libmesh_logging.h" #include "libmesh/mesh_base.h" #include "libmesh/mesh_communication.h" #include "libmesh/mesh_tools.h" #include "libmesh/node.h" #include "libmesh/parallel.h" #include "libmesh/partitioner.h" #include "libmesh/metis_partitioner.h" #include "libmesh/remote_elem.h" #include "libmesh/xdr_io.h" #include "libmesh/xdr_cxx.h" #include "libmesh/utility.h" #include "libmesh/int_range.h" // C++ includes #include <iostream> #include <iomanip> #include <cstdio> #include <unistd.h> #include <vector> #include <string> #include <cstring> #include <fstream> #include <sstream> // for ostringstream #include <unordered_map> #include <unordered_set> namespace { // chunking computes the number of chunks and first-chunk-offset when splitting a mesh // into nsplits pieces using size procs for the given MPI rank. The number of chunks and offset // are stored in nchunks and first_chunk respectively. void chunking(libMesh::processor_id_type size, libMesh::processor_id_type rank, libMesh::processor_id_type nsplits, libMesh::processor_id_type & nchunks, libMesh::processor_id_type & first_chunk) { if (nsplits % size == 0) // the chunks divide evenly over the processors { nchunks = nsplits / size; first_chunk = libMesh::cast_int<libMesh::processor_id_type>(nchunks * rank); return; } libMesh::processor_id_type nextra = nsplits % size; if (rank < nextra) // leftover chunks cause an extra chunk to be added to this processor { nchunks = libMesh::cast_int<libMesh::processor_id_type>(nsplits / size + 1); first_chunk = libMesh::cast_int<libMesh::processor_id_type>(nchunks * rank); } else // no extra chunks, but first chunk is offset by extras on earlier ranks { nchunks = nsplits / size; // account for the case where nchunks is zero where we want max int first_chunk = libMesh::cast_int<libMesh::processor_id_type> (std::max((int)((nchunks + 1) * (nsplits % size) + nchunks * (rank - nsplits % size)), (1 - (int)nchunks) * std::numeric_limits<int>::max())); } } std::string extension(const std::string & s) { auto pos = s.rfind("."); if (pos == std::string::npos) return ""; return s.substr(pos, s.size() - pos); } std::string split_dir(const std::string & input_name, libMesh::processor_id_type n_procs) { return input_name + "/" + std::to_string(n_procs); } std::string header_file(const std::string & input_name, libMesh::processor_id_type n_procs) { return split_dir(input_name, n_procs) + "/header" + extension(input_name); } std::string split_file(const std::string & input_name, libMesh::processor_id_type n_procs, libMesh::processor_id_type proc_id) { return split_dir(input_name, n_procs) + "/split-" + std::to_string(n_procs) + "-" + std::to_string(proc_id) + extension(input_name); } void make_dir(const std::string & input_name, libMesh::processor_id_type n_procs) { auto ret = libMesh::Utility::mkdir(input_name.c_str()); // error only if we failed to create dir - don't care if it was already there if (ret != 0 && ret != -1) libmesh_error_msg( "Failed to create mesh split directory '" << input_name << "': " << std::strerror(ret)); auto dir_name = split_dir(input_name, n_procs); ret = libMesh::Utility::mkdir(dir_name.c_str()); if (ret == -1) libmesh_warning("In CheckpointIO::write, directory '" << dir_name << "' already exists, overwriting contents."); else if (ret != 0) libmesh_error_msg( "Failed to create mesh split directory '" << dir_name << "': " << std::strerror(ret)); } } // namespace namespace libMesh { std::unique_ptr<CheckpointIO> split_mesh(MeshBase & mesh, processor_id_type nsplits) { // There is currently an issue with DofObjects not being properly // reset if the mesh is not first repartitioned onto 1 processor // *before* being repartitioned onto the desired number of // processors. So, this is a workaround, but not a particularly // onerous one. mesh.partition(1); mesh.partition(nsplits); processor_id_type my_num_chunks = 0; processor_id_type my_first_chunk = 0; chunking(mesh.comm().size(), mesh.comm().rank(), nsplits, my_num_chunks, my_first_chunk); auto cpr = libmesh_make_unique<CheckpointIO>(mesh); cpr->current_processor_ids().clear(); for (processor_id_type i = my_first_chunk; i < my_first_chunk + my_num_chunks; i++) cpr->current_processor_ids().push_back(i); cpr->current_n_processors() = nsplits; cpr->parallel() = true; return cpr; } // ------------------------------------------------------------ // CheckpointIO members CheckpointIO::CheckpointIO (MeshBase & mesh, const bool binary_in) : MeshInput<MeshBase> (mesh,/* is_parallel_format = */ true), MeshOutput<MeshBase>(mesh,/* is_parallel_format = */ true), ParallelObject (mesh), _binary (binary_in), _parallel (false), _version ("checkpoint-1.5"), _my_processor_ids (1, processor_id()), _my_n_processors (mesh.is_replicated() ? 1 : n_processors()) { } CheckpointIO::CheckpointIO (const MeshBase & mesh, const bool binary_in) : MeshOutput<MeshBase>(mesh,/* is_parallel_format = */ true), ParallelObject (mesh), _binary (binary_in), _parallel (false), _my_processor_ids (1, processor_id()), _my_n_processors (mesh.is_replicated() ? 1 : n_processors()) { } CheckpointIO::~CheckpointIO () { } processor_id_type CheckpointIO::select_split_config(const std::string & input_name, header_id_type & data_size) { std::string header_name; // We'll read a header file from processor 0 and broadcast. if (this->processor_id() == 0) { header_name = header_file(input_name, _my_n_processors); { // look for header+splits with nprocs equal to _my_n_processors std::ifstream in (header_name.c_str()); if (!in.good()) { // otherwise fall back to a serial/single-split mesh auto orig_header_name = header_name; header_name = header_file(input_name, 1); std::ifstream in2 (header_name.c_str()); if (!in2.good()) { libmesh_error_msg("ERROR: Neither one of the following files can be located:\n\t'" << orig_header_name << "' nor\n\t'" << input_name << "'\n" << "If you are running a parallel job, double check that you've " << "created a split for " << _my_n_processors << " ranks.\n" << "Note: One of paths above may refer to a valid directory on your " << "system, however we are attempting to read a valid header file."); } } } Xdr io (header_name, this->binary() ? DECODE : READ); // read the version, but don't care about it std::string input_version; io.data(input_version); // read the data type io.data (data_size); } this->comm().broadcast(data_size); this->comm().broadcast(header_name); // How many per-processor files are here? largest_id_type input_n_procs; switch (data_size) { case 2: input_n_procs = this->read_header<uint16_t>(header_name); break; case 4: input_n_procs = this->read_header<uint32_t>(header_name); break; case 8: input_n_procs = this->read_header<uint64_t>(header_name); break; default: libmesh_error(); } if (!input_n_procs) input_n_procs = 1; return cast_int<processor_id_type>(input_n_procs); } void CheckpointIO::cleanup(const std::string & input_name, processor_id_type n_procs) { auto header = header_file(input_name, n_procs); auto ret = std::remove(header.c_str()); if (ret != 0) libmesh_warning("Failed to clean up checkpoint header '" << header << "': " << std::strerror(ret)); for (processor_id_type i = 0; i < n_procs; i++) { auto split = split_file(input_name, n_procs, i); ret = std::remove(split.c_str()); if (ret != 0) libmesh_warning("Failed to clean up checkpoint split file '" << split << "': " << std::strerror(ret)); } auto dir = split_dir(input_name, n_procs); ret = rmdir(dir.c_str()); if (ret != 0) libmesh_warning("Failed to clean up checkpoint split dir '" << dir << "': " << std::strerror(ret)); // We expect that this may fail if there are other split configurations still present in this // directory - so don't bother to check/warn for failure. rmdir(input_name.c_str()); } bool CheckpointIO::version_at_least_1_5() const { return (this->version().find("1.5") != std::string::npos); } void CheckpointIO::write (const std::string & name) { LOG_SCOPE("write()", "CheckpointIO"); // convenient reference to our mesh const MeshBase & mesh = MeshOutput<MeshBase>::mesh(); // FIXME: For backwards compatibility, we'll assume for now that we // only want to write distributed meshes in parallel. Later we can // do a gather_to_zero() and support that case too. _parallel = _parallel || !mesh.is_serial(); processor_id_type use_n_procs = 1; if (_parallel) use_n_procs = _my_n_processors; std::string header_file_name = header_file(name, use_n_procs); make_dir(name, use_n_procs); // We'll write a header file from processor 0 to make it easier to do unambiguous // restarts later: if (this->processor_id() == 0) { Xdr io (header_file_name, this->binary() ? ENCODE : WRITE); // write the version io.data(_version, "# version"); // write what kind of data type we're using header_id_type data_size = sizeof(largest_id_type); io.data(data_size, "# integer size"); // Write out the max mesh dimension for backwards compatibility // with code that sets it independently of element dimensions { uint16_t mesh_dimension = cast_int<uint16_t>(mesh.mesh_dimension()); io.data(mesh_dimension, "# dimensions"); } // Write out whether or not this is serial output { uint16_t parallel = _parallel; io.data(parallel, "# parallel"); } // If we're writing out a parallel mesh then we need to write the number of processors // so we can check it upon reading the file if (_parallel) { largest_id_type n_procs = _my_n_processors; io.data(n_procs, "# n_procs"); } // write subdomain names this->write_subdomain_names(io); // write boundary id names const BoundaryInfo & boundary_info = mesh.get_boundary_info(); write_bc_names(io, boundary_info, true); // sideset names write_bc_names(io, boundary_info, false); // nodeset names // write extra integer names const bool write_extra_integers = this->version_at_least_1_5(); if (write_extra_integers) { largest_id_type n_node_integers = mesh.n_node_integers(); io.data(n_node_integers, "# n_extra_integers per node"); std::vector<std::string> node_integer_names; for (unsigned int i=0; i != n_node_integers; ++i) node_integer_names.push_back(mesh.get_node_integer_name(i)); io.data(node_integer_names); largest_id_type n_elem_integers = mesh.n_elem_integers(); io.data(n_elem_integers, "# n_extra_integers per elem"); std::vector<std::string> elem_integer_names; for (unsigned int i=0; i != n_elem_integers; ++i) elem_integer_names.push_back(mesh.get_elem_integer_name(i)); io.data(elem_integer_names); } } // If this is a serial mesh written to a serial file then we're only // going to write local data from processor 0. If this is a mesh being // written in parallel then we're going to write from every // processor. std::vector<processor_id_type> ids_to_write; // We're going to sort elements by pid in one pass, to avoid sending // predicated iterators through the whole mesh N_p times std::unordered_map<processor_id_type, std::vector<Elem *>> elements_on_pid; if (_parallel) { ids_to_write = _my_processor_ids; for (processor_id_type p : ids_to_write) elements_on_pid[p].clear(); auto eop_end = elements_on_pid.end(); for (auto & elem : mesh.element_ptr_range()) { const processor_id_type p = elem->processor_id(); auto eop_it = elements_on_pid.find(p); if (eop_it != eop_end) eop_it->second.push_back(elem); } } else if (mesh.is_serial()) { if (mesh.processor_id() == 0) { // placeholder ids_to_write.push_back(0); } } else { libmesh_error_msg("Cannot write serial checkpoint from distributed mesh"); } // Call build_side_list() and build_node_list() just *once* to avoid // redundant expensive sorts during mesh splitting. const BoundaryInfo & boundary_info = mesh.get_boundary_info(); std::vector<std::tuple<dof_id_type, unsigned short int, boundary_id_type>> bc_triples = boundary_info.build_side_list(); std::vector<std::tuple<dof_id_type, boundary_id_type>> bc_tuples = boundary_info.build_node_list(); for (const auto & my_pid : ids_to_write) { auto file_name = split_file(name, use_n_procs, my_pid); Xdr io (file_name, this->binary() ? ENCODE : WRITE); std::set<const Elem *, CompareElemIdsByLevel> elements; // For serial files or for already-distributed meshs, we write // everything we can see. if (!_parallel || !mesh.is_serial()) elements.insert(mesh.elements_begin(), mesh.elements_end()); // For parallel files written from serial meshes we write what // we'd be required to keep if we were to be deleting remote // elements. This allows us to write proper parallel files even // from a ReplicateMesh. // // WARNING: If we have a DistributedMesh which used // "add_extra_ghost_elem" rather than ghosting functors to // preserve elements and which is *also* currently serialized // then we're not preserving those elements here. As a quick // workaround user code should delete_remote_elements() before // writing the checkpoint; as a long term workaround user code // should use ghosting functors instead of extra_ghost_elem // lists. else { for (processor_id_type p : {my_pid, DofObject::invalid_processor_id}) { const auto elements_vec_it = elements_on_pid.find(p); if (elements_vec_it != elements_on_pid.end()) { const auto & p_elements = elements_vec_it->second; Elem * const * elempp = p_elements.data(); Elem * const * elemend = elempp + p_elements.size(); const MeshBase::const_element_iterator pid_elements_begin = MeshBase::const_element_iterator (elempp, elemend, Predicates::NotNull<Elem * const *>()), pid_elements_end = MeshBase::const_element_iterator (elemend, elemend, Predicates::NotNull<Elem * const *>()), active_pid_elements_begin = MeshBase::const_element_iterator (elempp, elemend, Predicates::Active<Elem * const *>()), active_pid_elements_end = MeshBase::const_element_iterator (elemend, elemend, Predicates::Active<Elem * const *>()); query_ghosting_functors (mesh, p, active_pid_elements_begin, active_pid_elements_end, elements); connect_children(mesh, pid_elements_begin, pid_elements_end, elements); } connect_families(elements); } } std::set<const Node *> connected_nodes; reconnect_nodes(elements, connected_nodes); // write the nodal locations this->write_nodes (io, connected_nodes); // write connectivity this->write_connectivity (io, elements); // write remote_elem connectivity this->write_remote_elem (io, elements); // write the boundary condition information this->write_bcs (io, elements, bc_triples); // write the nodeset information this->write_nodesets (io, connected_nodes, bc_tuples); // close it up io.close(); } // this->comm().barrier(); } void CheckpointIO::write_subdomain_names(Xdr & io) const { { const MeshBase & mesh = MeshOutput<MeshBase>::mesh(); const std::map<subdomain_id_type, std::string> & subdomain_map = mesh.get_subdomain_name_map(); std::vector<largest_id_type> subdomain_ids; subdomain_ids.reserve(subdomain_map.size()); std::vector<std::string> subdomain_names; subdomain_names.reserve(subdomain_map.size()); // We need to loop over the map and make sure that there aren't any invalid entries. Since we // return writable references in mesh_base, it's possible for the user to leave some entity names // blank. We can't write those to the XDA file. largest_id_type n_subdomain_names = 0; for (const auto & pr : subdomain_map) if (!pr.second.empty()) { n_subdomain_names++; subdomain_ids.push_back(pr.first); subdomain_names.push_back(pr.second); } io.data(n_subdomain_names, "# subdomain id to name map"); // Write out the ids and names in two vectors if (n_subdomain_names) { io.data(subdomain_ids); io.data(subdomain_names); } } } void CheckpointIO::write_nodes (Xdr & io, const std::set<const Node *> & nodeset) const { largest_id_type n_nodes_here = nodeset.size(); io.data(n_nodes_here, "# n_nodes on proc"); const bool write_extra_integers = this->version_at_least_1_5(); const unsigned int n_extra_integers = write_extra_integers ? MeshOutput<MeshBase>::mesh().n_node_integers() : 0; // Will hold the node id and pid and extra integers std::vector<largest_id_type> id_pid(2 + n_extra_integers); // For the coordinates std::vector<Real> coords(LIBMESH_DIM); for (const auto & node : nodeset) { id_pid[0] = node->id(); id_pid[1] = node->processor_id(); libmesh_assert_equal_to(n_extra_integers, node->n_extra_integers()); for (unsigned int i=0; i != n_extra_integers; ++i) id_pid[2+i] = node->get_extra_integer(i); io.data_stream(id_pid.data(), 2 + n_extra_integers, 2 + n_extra_integers); #ifdef LIBMESH_ENABLE_UNIQUE_ID largest_id_type unique_id = node->unique_id(); io.data(unique_id, "# unique id"); #endif coords[0] = (*node)(0); #if LIBMESH_DIM > 1 coords[1] = (*node)(1); #endif #if LIBMESH_DIM > 2 coords[2] = (*node)(2); #endif io.data_stream(coords.data(), LIBMESH_DIM, 3); } } void CheckpointIO::write_connectivity (Xdr & io, const std::set<const Elem *, CompareElemIdsByLevel> & elements) const { libmesh_assert (io.writing()); const bool write_extra_integers = this->version_at_least_1_5(); const unsigned int n_extra_integers = write_extra_integers ? MeshOutput<MeshBase>::mesh().n_elem_integers() : 0; // Put these out here to reduce memory churn // id type pid subdomain_id parent_id extra_integer_0 ... std::vector<largest_id_type> elem_data(6 + n_extra_integers); std::vector<largest_id_type> conn_data; largest_id_type n_elems_here = elements.size(); io.data(n_elems_here, "# number of elements"); for (const auto & elem : elements) { unsigned int n_nodes = elem->n_nodes(); elem_data[0] = elem->id(); elem_data[1] = elem->type(); elem_data[2] = elem->processor_id(); elem_data[3] = elem->subdomain_id(); #ifdef LIBMESH_ENABLE_AMR if (elem->parent() != nullptr) { elem_data[4] = elem->parent()->id(); elem_data[5] = elem->parent()->which_child_am_i(elem); } else #endif { elem_data[4] = static_cast<largest_id_type>(-1); elem_data[5] = static_cast<largest_id_type>(-1); } for (unsigned int i=0; i != n_extra_integers; ++i) elem_data[6+i] = elem->get_extra_integer(i); conn_data.resize(n_nodes); for (unsigned int i=0; i<n_nodes; i++) conn_data[i] = elem->node_id(i); io.data_stream(elem_data.data(), cast_int<unsigned int>(elem_data.size()), cast_int<unsigned int>(elem_data.size())); #ifdef LIBMESH_ENABLE_UNIQUE_ID largest_id_type unique_id = elem->unique_id(); io.data(unique_id, "# unique id"); #endif #ifdef LIBMESH_ENABLE_AMR uint16_t p_level = cast_int<uint16_t>(elem->p_level()); io.data(p_level, "# p_level"); uint16_t rflag = elem->refinement_flag(); io.data(rflag, "# rflag"); uint16_t pflag = elem->p_refinement_flag(); io.data(pflag, "# pflag"); #endif io.data_stream(conn_data.data(), cast_int<unsigned int>(conn_data.size()), cast_int<unsigned int>(conn_data.size())); } } void CheckpointIO::write_remote_elem (Xdr & io, const std::set<const Elem *, CompareElemIdsByLevel> & elements) const { libmesh_assert (io.writing()); // Find the remote_elem neighbor and child links std::vector<largest_id_type> elem_ids, parent_ids; std::vector<uint16_t> elem_sides, child_numbers; for (const auto & elem : elements) { for (auto n : elem->side_index_range()) { const Elem * neigh = elem->neighbor_ptr(n); if (neigh == remote_elem || (neigh && !elements.count(neigh))) { elem_ids.push_back(elem->id()); elem_sides.push_back(n); } } #ifdef LIBMESH_ENABLE_AMR if (elem->has_children()) { for (unsigned short c = 0, nc = cast_int<unsigned short>(elem->n_children()); c != nc; ++c) { const Elem * child = elem->child_ptr(c); if (child == remote_elem || (child && !elements.count(child))) { parent_ids.push_back(elem->id()); child_numbers.push_back(c); } } } #endif } io.data(elem_ids, "# remote neighbor elem_ids"); io.data(elem_sides, "# remote neighbor elem_sides"); io.data(parent_ids, "# remote child parent_ids"); io.data(child_numbers, "# remote child_numbers"); } void CheckpointIO::write_bcs (Xdr & io, const std::set<const Elem *, CompareElemIdsByLevel> & elements, const std::vector<std::tuple<dof_id_type, unsigned short int, boundary_id_type>> & bc_triples) const { libmesh_assert (io.writing()); // Build a list of (elem, side, bc) tuples. std::size_t bc_size = bc_triples.size(); std::vector<largest_id_type> element_id_list; std::vector<uint16_t> side_list; std::vector<largest_id_type> bc_id_list; element_id_list.reserve(bc_size); side_list.reserve(bc_size); bc_id_list.reserve(bc_size); std::unordered_set<dof_id_type> elems; for (auto & e : elements) elems.insert(e->id()); for (const auto & t : bc_triples) if (elems.count(std::get<0>(t))) { element_id_list.push_back(std::get<0>(t)); side_list.push_back(std::get<1>(t)); bc_id_list.push_back(std::get<2>(t)); } io.data(element_id_list, "# element ids for bcs"); io.data(side_list, "# sides of elements for bcs"); io.data(bc_id_list, "# bc ids"); } void CheckpointIO::write_nodesets (Xdr & io, const std::set<const Node *> & nodeset, const std::vector<std::tuple<dof_id_type, boundary_id_type>> & bc_tuples) const { libmesh_assert (io.writing()); // convenient reference to our mesh const MeshBase & mesh = MeshOutput<MeshBase>::mesh(); // Build a list of (node, bc) tuples std::size_t nodeset_size = bc_tuples.size(); std::vector<largest_id_type> node_id_list; std::vector<largest_id_type> bc_id_list; node_id_list.reserve(nodeset_size); bc_id_list.reserve(nodeset_size); for (const auto & t : bc_tuples) if (nodeset.count(mesh.node_ptr(std::get<0>(t)))) { node_id_list.push_back(std::get<0>(t)); bc_id_list.push_back(std::get<1>(t)); } io.data(node_id_list, "# node id list"); io.data(bc_id_list, "# nodeset bc id list"); } void CheckpointIO::write_bc_names (Xdr & io, const BoundaryInfo & info, bool is_sideset) const { const std::map<boundary_id_type, std::string> & boundary_map = is_sideset ? info.get_sideset_name_map() : info.get_nodeset_name_map(); std::vector<largest_id_type> boundary_ids; boundary_ids.reserve(boundary_map.size()); std::vector<std::string> boundary_names; boundary_names.reserve(boundary_map.size()); // We need to loop over the map and make sure that there aren't any invalid entries. Since we // return writable references in boundary_info, it's possible for the user to leave some entity names // blank. We can't write those to the XDA file. largest_id_type n_boundary_names = 0; for (const auto & pr : boundary_map) if (!pr.second.empty()) { n_boundary_names++; boundary_ids.push_back(pr.first); boundary_names.push_back(pr.second); } if (is_sideset) io.data(n_boundary_names, "# sideset id to name map"); else io.data(n_boundary_names, "# nodeset id to name map"); // Write out the ids and names in two vectors if (n_boundary_names) { io.data(boundary_ids); io.data(boundary_names); } } void CheckpointIO::read (const std::string & input_name) { LOG_SCOPE("read()","CheckpointIO"); MeshBase & mesh = MeshInput<MeshBase>::mesh(); libmesh_assert(!mesh.n_elem()); header_id_type data_size; processor_id_type input_n_procs = select_split_config(input_name, data_size); auto header_name = header_file(input_name, input_n_procs); bool input_parallel = input_n_procs > 0; // If this is a serial read then we're going to only read the mesh // on processor 0, then broadcast it if ((input_parallel && !mesh.is_replicated()) || mesh.processor_id() == 0) { // If we're trying to read a parallel checkpoint file on a // replicated mesh, we'll read every file on processor 0 so we // can broadcast it later. If we're on a distributed mesh then // we'll read every id to it's own processor and we'll "wrap // around" with any ids that exceed our processor count. const processor_id_type begin_proc_id = (input_parallel && !mesh.is_replicated()) ? mesh.processor_id() : 0; const processor_id_type stride = (input_parallel && !mesh.is_replicated()) ? mesh.n_processors() : 1; for (processor_id_type proc_id = begin_proc_id; proc_id < input_n_procs; proc_id = cast_int<processor_id_type>(proc_id + stride)) { auto file_name = split_file(input_name, input_n_procs, proc_id); { std::ifstream in (file_name.c_str()); if (!in.good()) libmesh_error_msg("ERROR: cannot locate specified file:\n\t" << file_name); } // Do we expect all our files' remote_elem entries to really // be remote? Only if we're not reading multiple input // files on the same processor. const bool expect_all_remote = (input_n_procs <= mesh.n_processors() && !mesh.is_replicated()); Xdr io (file_name, this->binary() ? DECODE : READ); switch (data_size) { case 2: this->read_subfile<uint16_t>(io, expect_all_remote); break; case 4: this->read_subfile<uint32_t>(io, expect_all_remote); break; case 8: this->read_subfile<uint64_t>(io, expect_all_remote); break; default: libmesh_error(); } io.close(); } } // If the mesh was only read on processor 0 then we need to broadcast it if (mesh.is_replicated()) MeshCommunication().broadcast(mesh); // If the mesh is really distributed then we need to make sure it // knows that else if (mesh.n_processors() > 1) mesh.set_distributed(); } template <typename file_id_type> file_id_type CheckpointIO::read_header (const std::string & name) { MeshBase & mesh = MeshInput<MeshBase>::mesh(); // Hack for codes which don't look at all elem dimensions uint16_t mesh_dimension; // Will this be a parallel input file? With how many processors? Stay tuned! uint16_t input_parallel; file_id_type input_n_procs; std::vector<std::string> node_integer_names, elem_integer_names; // We'll write a header file from processor 0 and broadcast. if (this->processor_id() == 0) { Xdr io (name, this->binary() ? DECODE : READ); // read the version, but don't care about it std::string input_version; io.data(input_version); // read the data type, don't care about it this time header_id_type data_size; io.data (data_size); // read the dimension io.data (mesh_dimension); // Read whether or not this is a parallel file io.data(input_parallel); // With how many processors? if (input_parallel) io.data(input_n_procs); // read subdomain names this->read_subdomain_names<file_id_type>(io); // read boundary names BoundaryInfo & boundary_info = mesh.get_boundary_info(); this->read_bc_names<file_id_type>(io, boundary_info, true); // sideset names this->read_bc_names<file_id_type>(io, boundary_info, false); // nodeset names // read extra integer names? std::swap(input_version, this->version()); const bool read_extra_integers = this->version_at_least_1_5(); std::swap(input_version, this->version()); if (read_extra_integers) this->read_integers_names<file_id_type> (io, node_integer_names, elem_integer_names); } // broadcast data from processor 0, set values everywhere this->comm().broadcast(mesh_dimension); mesh.set_mesh_dimension(cast_int<unsigned char>(mesh_dimension)); this->comm().broadcast(input_parallel); if (input_parallel) this->comm().broadcast(input_n_procs); else input_n_procs = 1; std::map<subdomain_id_type, std::string> & subdomain_map = mesh.set_subdomain_name_map(); this->comm().broadcast(subdomain_map); BoundaryInfo & boundary_info = mesh.get_boundary_info(); this->comm().broadcast(boundary_info.set_sideset_name_map()); this->comm().broadcast(boundary_info.set_nodeset_name_map()); this->comm().broadcast(node_integer_names); this->comm().broadcast(elem_integer_names); for (auto & int_name : node_integer_names) mesh.add_node_integer(int_name); for (auto & int_name : elem_integer_names) mesh.add_elem_integer(int_name); return input_parallel ? input_n_procs : 0; } template <typename file_id_type> void CheckpointIO::read_subfile (Xdr & io, bool expect_all_remote) { // read the nodal locations this->read_nodes<file_id_type> (io); // read connectivity this->read_connectivity<file_id_type> (io); // read remote_elem connectivity this->read_remote_elem<file_id_type> (io, expect_all_remote); // read the boundary conditions this->read_bcs<file_id_type> (io); // read the nodesets this->read_nodesets<file_id_type> (io); } template <typename file_id_type> void CheckpointIO::read_subdomain_names(Xdr & io) { MeshBase & mesh = MeshInput<MeshBase>::mesh(); std::map<subdomain_id_type, std::string> & subdomain_map = mesh.set_subdomain_name_map(); std::vector<file_id_type> subdomain_ids; subdomain_ids.reserve(subdomain_map.size()); std::vector<std::string> subdomain_names; subdomain_names.reserve(subdomain_map.size()); file_id_type n_subdomain_names = 0; io.data(n_subdomain_names, "# subdomain id to name map"); if (n_subdomain_names) { io.data(subdomain_ids); io.data(subdomain_names); for (auto i : index_range(subdomain_ids)) subdomain_map[cast_int<subdomain_id_type>(subdomain_ids[i])] = subdomain_names[i]; } } template <typename file_id_type> void CheckpointIO::read_nodes (Xdr & io) { // convenient reference to our mesh MeshBase & mesh = MeshInput<MeshBase>::mesh(); file_id_type n_nodes_here; io.data(n_nodes_here, "# n_nodes on proc"); const bool read_extra_integers = this->version_at_least_1_5(); const unsigned int n_extra_integers = read_extra_integers ? mesh.n_node_integers() : 0; // Will hold the node id and pid and extra integers std::vector<file_id_type> id_pid(2 + n_extra_integers); // For the coordinates std::vector<Real> coords(LIBMESH_DIM); for (unsigned int i=0; i<n_nodes_here; i++) { io.data_stream(id_pid.data(), 2 + n_extra_integers, 2 + n_extra_integers); #ifdef LIBMESH_ENABLE_UNIQUE_ID file_id_type unique_id = 0; io.data(unique_id, "# unique id"); #endif io.data_stream(coords.data(), LIBMESH_DIM, LIBMESH_DIM); Point p; p(0) = coords[0]; #if LIBMESH_DIM > 1 p(1) = coords[1]; #endif #if LIBMESH_DIM > 2 p(2) = coords[2]; #endif const dof_id_type id = cast_int<dof_id_type>(id_pid[0]); // "Wrap around" if we see more processors than we're using. processor_id_type pid = cast_int<processor_id_type>(id_pid[1] % mesh.n_processors()); // If we already have this node (e.g. from another file, when // reading multiple distributed CheckpointIO files into a // ReplicatedMesh) then we don't want to add it again (because // ReplicatedMesh can't handle that) but we do want to assert // consistency between what we're reading and what we have. const Node * old_node = mesh.query_node_ptr(id); if (old_node) { libmesh_assert_equal_to(pid, old_node->processor_id()); libmesh_assert_equal_to(n_extra_integers, old_node->n_extra_integers()); #ifndef NDEBUG for (unsigned int ei=0; ei != n_extra_integers; ++ei) { const dof_id_type extra_int = cast_int<dof_id_type>(id_pid[2+ei]); libmesh_assert_equal_to(extra_int, old_node->get_extra_integer(ei)); } #endif #ifdef LIBMESH_ENABLE_UNIQUE_ID libmesh_assert_equal_to(unique_id, old_node->unique_id()); #endif } else { Node * node = mesh.add_point(p, id, pid); #ifdef LIBMESH_ENABLE_UNIQUE_ID node->set_unique_id() = unique_id; #endif libmesh_assert_equal_to(n_extra_integers, node->n_extra_integers()); for (unsigned int ei=0; ei != n_extra_integers; ++ei) { const dof_id_type extra_int = cast_int<dof_id_type>(id_pid[2+ei]); node->set_extra_integer(ei, extra_int); } } } } template <typename file_id_type> void CheckpointIO::read_connectivity (Xdr & io) { // convenient reference to our mesh MeshBase & mesh = MeshInput<MeshBase>::mesh(); const bool read_extra_integers = this->version_at_least_1_5(); const unsigned int n_extra_integers = read_extra_integers ? mesh.n_elem_integers() : 0; file_id_type n_elems_here; io.data(n_elems_here); // Keep track of the highest dimensional element we've added to the mesh unsigned int highest_elem_dim = 1; // RHS: Originally we used invalid_processor_id as a "no parent" tag // number, because I'm an idiot. Let's try to support broken files // as much as possible. bool file_is_broken = false; for (unsigned int i=0; i<n_elems_here; i++) { // id type pid subdomain_id parent_id std::vector<file_id_type> elem_data(6 + n_extra_integers); io.data_stream (elem_data.data(), cast_int<unsigned int>(elem_data.size()), cast_int<unsigned int>(elem_data.size())); #ifdef LIBMESH_ENABLE_UNIQUE_ID file_id_type unique_id = 0; io.data(unique_id, "# unique id"); #endif #ifdef LIBMESH_ENABLE_AMR uint16_t p_level = 0; io.data(p_level, "# p_level"); uint16_t rflag, pflag; io.data(rflag, "# rflag"); io.data(pflag, "# pflag"); #endif unsigned int n_nodes = Elem::type_to_n_nodes_map[elem_data[1]]; // Snag the node ids this element was connected to std::vector<file_id_type> conn_data(n_nodes); io.data_stream (conn_data.data(), cast_int<unsigned int>(conn_data.size()), cast_int<unsigned int>(conn_data.size())); const dof_id_type id = cast_int<dof_id_type> (elem_data[0]); const ElemType elem_type = static_cast<ElemType> (elem_data[1]); const processor_id_type proc_id = cast_int<processor_id_type> (elem_data[2] % mesh.n_processors()); const subdomain_id_type subdomain_id = cast_int<subdomain_id_type>(elem_data[3]); // Old broken files used processsor_id_type(-1)... // But we *know* our first element will be level 0 if (i == 0 && elem_data[4] == 65535) file_is_broken = true; // On a broken file we can't tell whether a parent of 65535 is a // null parent or an actual parent of 65535. Assuming the // former will cause less breakage. Elem * parent = (elem_data[4] == static_cast<largest_id_type>(-1) || (file_is_broken && elem_data[4] == 65535)) ? nullptr : mesh.elem_ptr(cast_int<dof_id_type>(elem_data[4])); const unsigned short int child_num = (elem_data[5] == static_cast<largest_id_type>(-1) || (file_is_broken && elem_data[5] == 65535)) ? static_cast<unsigned short>(-1) : cast_int<unsigned short>(elem_data[5]); if (!parent) libmesh_assert_equal_to (child_num, static_cast<unsigned short>(-1)); Elem * old_elem = mesh.query_elem_ptr(id); // If we already have this element (e.g. from another file, // when reading multiple distributed CheckpointIO files into // a ReplicatedMesh) then we don't want to add it again // (because ReplicatedMesh can't handle that) but we do want // to assert consistency between what we're reading and what // we have. if (old_elem) { libmesh_assert_equal_to(elem_type, old_elem->type()); libmesh_assert_equal_to(proc_id, old_elem->processor_id()); libmesh_assert_equal_to(subdomain_id, old_elem->subdomain_id()); if (parent) libmesh_assert_equal_to(parent, old_elem->parent()); else libmesh_assert(!old_elem->parent()); libmesh_assert_equal_to(n_extra_integers, old_elem->n_extra_integers()); #ifndef NDEBUG for (unsigned int ei=0; ei != n_extra_integers; ++ei) { const dof_id_type extra_int = cast_int<dof_id_type>(elem_data[6+ei]); libmesh_assert_equal_to(extra_int, old_elem->get_extra_integer(ei)); } #endif libmesh_assert_equal_to(old_elem->n_nodes(), conn_data.size()); for (unsigned int n=0, n_conn = cast_int<unsigned int>(conn_data.size()); n != n_conn; n++) libmesh_assert_equal_to (old_elem->node_id(n), cast_int<dof_id_type>(conn_data[n])); } else { // Create the element auto elem = Elem::build(elem_type, parent); #ifdef LIBMESH_ENABLE_UNIQUE_ID elem->set_unique_id() = unique_id; #endif if (elem->dim() > highest_elem_dim) highest_elem_dim = elem->dim(); elem->set_id() = id; elem->processor_id() = proc_id; elem->subdomain_id() = subdomain_id; #ifdef LIBMESH_ENABLE_AMR elem->hack_p_level(p_level); elem->set_refinement_flag (cast_int<Elem::RefinementState>(rflag)); elem->set_p_refinement_flag(cast_int<Elem::RefinementState>(pflag)); // Set parent connections if (parent) { // We must specify a child_num, because we will have // skipped adding any preceding remote_elem children parent->add_child(elem.get(), child_num); } #else libmesh_ignore(child_num); #endif libmesh_assert(elem->n_nodes() == conn_data.size()); // Connect all the nodes to this element for (unsigned int n=0, n_conn = cast_int<unsigned int>(conn_data.size()); n != n_conn; n++) elem->set_node(n) = mesh.node_ptr(cast_int<dof_id_type>(conn_data[n])); Elem * added_elem = mesh.add_elem(std::move(elem)); libmesh_assert_equal_to(n_extra_integers, added_elem->n_extra_integers()); for (unsigned int ei=0; ei != n_extra_integers; ++ei) { const dof_id_type extra_int = cast_int<dof_id_type>(elem_data[6+ei]); added_elem->set_extra_integer(ei, extra_int); } } } mesh.set_mesh_dimension(cast_int<unsigned char>(highest_elem_dim)); } template <typename file_id_type> void CheckpointIO::read_remote_elem (Xdr & io, bool libmesh_dbg_var(expect_all_remote)) { // convenient reference to our mesh MeshBase & mesh = MeshInput<MeshBase>::mesh(); // Find the remote_elem neighbor links std::vector<file_id_type> elem_ids; std::vector<uint16_t> elem_sides; io.data(elem_ids, "# remote neighbor elem_ids"); io.data(elem_sides, "# remote neighbor elem_sides"); libmesh_assert_equal_to(elem_ids.size(), elem_sides.size()); for (auto i : index_range(elem_ids)) { Elem & elem = mesh.elem_ref(cast_int<dof_id_type>(elem_ids[i])); if (!elem.neighbor_ptr(elem_sides[i])) elem.set_neighbor(elem_sides[i], const_cast<RemoteElem *>(remote_elem)); else libmesh_assert(!expect_all_remote); } // Find the remote_elem children links std::vector<file_id_type> parent_ids; std::vector<uint16_t> child_numbers; io.data(parent_ids, "# remote child parent_ids"); io.data(child_numbers, "# remote child_numbers"); #ifdef LIBMESH_ENABLE_AMR for (auto i : index_range(parent_ids)) { Elem & elem = mesh.elem_ref(cast_int<dof_id_type>(parent_ids[i])); // We'd like to assert that no child pointer already exists to // be overwritten by remote_elem, but Elem doesn't actually have // an API that will return a child pointer without asserting // that it isn't nullptr. const Elem * child = elem.raw_child_ptr(child_numbers[i]); if (!child) elem.add_child(const_cast<RemoteElem *>(remote_elem), child_numbers[i]); else libmesh_assert(!expect_all_remote); } #endif } template <typename file_id_type> void CheckpointIO::read_bcs (Xdr & io) { // convenient reference to our mesh MeshBase & mesh = MeshInput<MeshBase>::mesh(); // and our boundary info object BoundaryInfo & boundary_info = mesh.get_boundary_info(); std::vector<file_id_type> element_id_list; std::vector<uint16_t> side_list; std::vector<file_id_type> bc_id_list; io.data(element_id_list, "# element ids for bcs"); io.data(side_list, "# sides of elements for bcs"); io.data(bc_id_list, "# bc ids"); for (auto i : index_range(element_id_list)) boundary_info.add_side (cast_int<dof_id_type>(element_id_list[i]), side_list[i], cast_int<boundary_id_type>(bc_id_list[i])); } template <typename file_id_type> void CheckpointIO::read_nodesets (Xdr & io) { // convenient reference to our mesh MeshBase & mesh = MeshInput<MeshBase>::mesh(); // and our boundary info object BoundaryInfo & boundary_info = mesh.get_boundary_info(); std::vector<file_id_type> node_id_list; std::vector<file_id_type> bc_id_list; io.data(node_id_list, "# node id list"); io.data(bc_id_list, "# nodeset bc id list"); for (auto i : index_range(node_id_list)) boundary_info.add_node (cast_int<dof_id_type>(node_id_list[i]), cast_int<boundary_id_type>(bc_id_list[i])); } template <typename file_id_type> void CheckpointIO::read_bc_names(Xdr & io, BoundaryInfo & info, bool is_sideset) { std::map<boundary_id_type, std::string> & boundary_map = is_sideset ? info.set_sideset_name_map() : info.set_nodeset_name_map(); std::vector<file_id_type> boundary_ids; std::vector<std::string> boundary_names; file_id_type n_boundary_names = 0; if (is_sideset) io.data(n_boundary_names, "# sideset id to name map"); else io.data(n_boundary_names, "# nodeset id to name map"); if (n_boundary_names) { io.data(boundary_ids); io.data(boundary_names); } // Add them back into the map for (auto i : index_range(boundary_ids)) boundary_map[cast_int<boundary_id_type>(boundary_ids[i])] = boundary_names[i]; } template <typename file_id_type> void CheckpointIO::read_integers_names (Xdr & io, std::vector<std::string> & node_integer_names, std::vector<std::string> & elem_integer_names) { file_id_type n_node_integers, n_elem_integers; io.data(n_node_integers, "# n_extra_integers per node"); io.data(node_integer_names); io.data(n_elem_integers, "# n_extra_integers per elem"); io.data(elem_integer_names); } unsigned int CheckpointIO::n_active_levels_in(MeshBase::const_element_iterator begin, MeshBase::const_element_iterator end) const { unsigned int max_level = 0; for (const auto & elem : as_range(begin, end)) max_level = std::max(elem->level(), max_level); return max_level + 1; } } // namespace libMesh
capitalaslash/libmesh
src/mesh/checkpoint_io.C
C++
lgpl-2.1
47,434
<?php /*"****************************************************************************************************** * (c) 2013-2016 by Kajona, www.kajona.de * * Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt * ********************************************************************************************************/ namespace Kajona\Workflows\System\Messageproviders; use Kajona\System\System\Carrier; use Kajona\System\System\Messageproviders\MessageproviderBase; /** * The summary message creates an overview of unread messages and sends them to the user. * In most cases this only makes sense if sent by mail. * * @author sidler@kajona.de * @package module_workflows * @since 4.5 */ class MessageproviderSummary extends MessageproviderBase { /** * Returns the name of the message-provider * * @return string */ public function getStrName() { return Carrier::getInstance()->getObjLang()->getLang("messageprovider_workflows_summary", "workflows"); } /** * @inheritDoc */ public function isAlwaysActive() { return false; } /** * @inheritDoc */ public function isAlwaysByMail() { return false; } /** * @inheritDoc */ public function isVisibleInConfigView() { return true; } }
artemeon/core
module_workflows/system/messageproviders/MessageproviderSummary.php
PHP
lgpl-2.1
1,448
package com.educode.nodes.base; import com.educode.visitors.AbstractVisitor; import java.util.ArrayList; /** * Created by zen on 3/23/17. */ public class ListNode extends NaryNode implements INodeWithChildren { public ListNode() { super(new ArrayList<>()); } public ListNode(ArrayList<Node> childNodes) { super(childNodes); } @Override public Object accept(AbstractVisitor visitor) { return visitor.visit(this); } }
andersjkbsn/EduCode
src/main/java/com/educode/nodes/base/ListNode.java
Java
lgpl-2.1
488
using ManiaNet.DedicatedServer.Annotations; using ManiaNet.DedicatedServer.XmlRpc.Structs; using System; using System.Collections.Generic; using System.Linq; using XmlRpc.Methods; using XmlRpc.Types; namespace ManiaNet.DedicatedServer.XmlRpc.Methods { /// <summary> /// Represents a call to the GetForcedSkins method. /// </summary> [UsedImplicitly] public sealed class GetForcedSkins : XmlRpcMethodCall<XmlRpcArray<XmlRpcStruct<ForcedSkinStruct>, ForcedSkinStruct>, XmlRpcStruct<ForcedSkinStruct>[]> { /// <summary> /// Gets the name of the method this call is for. /// </summary> public override string MethodName { get { return "GetForcedSkins"; } } } }
ManiaDotNet/DedicatedServer
ManiaNet.DedicatedServer/XmlRpc/Methods/GetForcedSkins.cs
C#
lgpl-2.1
748
using System; namespace Validations { /// <summary> /// Interface ISimpleOperation /// </summary> /// <typeparam name="TSource">The type of the t source.</typeparam> public interface ISimpleOperation<TSource> : IOperationInfo where TSource : class { /// <summary> /// Gets the verifier. /// </summary> /// <value>The verifier.</value> Func<TSource, bool> Verifier { get; } } }
TheHunter/Validations
Validations/ISimpleOperation.cs
C#
lgpl-2.1
466
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <mapnik/config.hpp> #include "boost_std_shared_shim.hpp" #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #pragma GCC diagnostic pop // mapnik #include <mapnik/symbolizer.hpp> #include <mapnik/symbolizer_hash.hpp> #include <mapnik/symbolizer_utils.hpp> #include <mapnik/symbolizer_keys.hpp> #include <mapnik/image_util.hpp> #include <mapnik/parse_path.hpp> #include <mapnik/path_expression.hpp> #include "mapnik_enumeration.hpp" #include "mapnik_svg.hpp" #include <mapnik/expression_node.hpp> #include <mapnik/value_error.hpp> #include <mapnik/marker_cache.hpp> // for known_svg_prefix_ #include <mapnik/util/variant.hpp> // stl #include <sstream> using mapnik::symbolizer; using mapnik::point_symbolizer; using mapnik::line_symbolizer; using mapnik::line_pattern_symbolizer; using mapnik::polygon_symbolizer; using mapnik::polygon_pattern_symbolizer; using mapnik::raster_symbolizer; using mapnik::shield_symbolizer; using mapnik::text_symbolizer; using mapnik::building_symbolizer; using mapnik::markers_symbolizer; using mapnik::debug_symbolizer; using mapnik::collision_symbolizer; using mapnik::symbolizer_base; using mapnik::color; using mapnik::path_processor_type; using mapnik::path_expression_ptr; using mapnik::guess_type; using mapnik::expression_ptr; using mapnik::parse_path; namespace { using namespace boost::python; void __setitem__(mapnik::symbolizer_base & sym, std::string const& name, mapnik::symbolizer_base::value_type const& val) { put(sym, mapnik::get_key(name), val); } std::shared_ptr<mapnik::symbolizer_base::value_type> numeric_wrapper(const object& arg) { std::shared_ptr<mapnik::symbolizer_base::value_type> result; if (PyBool_Check(arg.ptr())) { mapnik::value_bool val = extract<mapnik::value_bool>(arg); result.reset(new mapnik::symbolizer_base::value_type(val)); } else if (PyFloat_Check(arg.ptr())) { mapnik::value_double val = extract<mapnik::value_double>(arg); result.reset(new mapnik::symbolizer_base::value_type(val)); } else { mapnik::value_integer val = extract<mapnik::value_integer>(arg); result.reset(new mapnik::symbolizer_base::value_type(val)); } return result; } struct extract_python_object { using result_type = boost::python::object; template <typename T> auto operator() (T const& val) const -> result_type { return result_type(val); // wrap into python object } }; boost::python::object __getitem__(mapnik::symbolizer_base const& sym, std::string const& name) { using const_iterator = symbolizer_base::cont_type::const_iterator; mapnik::keys key = mapnik::get_key(name); const_iterator itr = sym.properties.find(key); if (itr != sym.properties.end()) { return mapnik::util::apply_visitor(extract_python_object(), itr->second); } //mapnik::property_meta_type const& meta = mapnik::get_meta(key); //return mapnik::util::apply_visitor(extract_python_object(), std::get<1>(meta)); return boost::python::object(); } /* std::string __str__(mapnik::symbolizer const& sym) { return mapnik::util::apply_visitor(mapnik::symbolizer_to_json(), sym); } */ std::string get_symbolizer_type(symbolizer const& sym) { return mapnik::symbolizer_name(sym); // FIXME - do we need this ? } std::size_t hash_impl(symbolizer const& sym) { return mapnik::util::apply_visitor(mapnik::symbolizer_hash_visitor(), sym); } template <typename T> std::size_t hash_impl_2(T const& sym) { return mapnik::symbolizer_hash::value<T>(sym); } struct extract_underlying_type_visitor { template <typename T> boost::python::object operator() (T & sym) const { using namespace boost::python; using converter = typename reference_existing_object::apply<T &>::type; return object(handle<>(converter()(sym))); } }; boost::python::object extract_underlying_type(symbolizer & sym) { return mapnik::util::apply_visitor(extract_underlying_type_visitor(), sym); } } void export_symbolizer() { using namespace boost::python; implicitly_convertible<mapnik::value_bool, mapnik::symbolizer_base::value_type>(); implicitly_convertible<mapnik::value_integer, mapnik::symbolizer_base::value_type>(); implicitly_convertible<mapnik::value_double, mapnik::symbolizer_base::value_type>(); implicitly_convertible<std::string, mapnik::symbolizer_base::value_type>(); implicitly_convertible<mapnik::color, mapnik::symbolizer_base::value_type>(); implicitly_convertible<mapnik::expression_ptr, mapnik::symbolizer_base::value_type>(); implicitly_convertible<mapnik::enumeration_wrapper, mapnik::symbolizer_base::value_type>(); enum_<mapnik::keys>("keys") .value("gamma", mapnik::keys::gamma) .value("gamma_method",mapnik::keys::gamma_method) ; class_<symbolizer>("Symbolizer",no_init) .def("type",get_symbolizer_type) .def("__hash__",hash_impl) .def("extract", extract_underlying_type) ; class_<symbolizer_base::value_type>("NumericWrapper") .def("__init__", make_constructor(numeric_wrapper)) ; class_<mapnik::enumeration_wrapper>("EnumerationWrapper", init<int>()) .def("__int__", &mapnik::enumeration_wrapper::operator int) ; class_<symbolizer_base>("SymbolizerBase",no_init) .def("__setitem__",&__setitem__) .def("__setattr__",&__setitem__) .def("__getitem__",&__getitem__) .def("__getattr__",&__getitem__) //.def("__str__", &__str__) .def(self == self) // __eq__ ; } void export_text_symbolizer() { using namespace boost::python; class_<text_symbolizer, bases<symbolizer_base>>("TextSymbolizer", init<>()) .def("__hash__",hash_impl_2<text_symbolizer>) ; } void export_shield_symbolizer() { using namespace boost::python; class_< shield_symbolizer, bases<text_symbolizer> >("ShieldSymbolizer", init<>("Default ctor")) .def("__hash__",hash_impl_2<shield_symbolizer>) ; } void export_polygon_symbolizer() { using namespace boost::python; class_<polygon_symbolizer, bases<symbolizer_base> >("PolygonSymbolizer", init<>("Default ctor")) .def("__hash__",hash_impl_2<polygon_symbolizer>) ; } void export_polygon_pattern_symbolizer() { using namespace boost::python; mapnik::enumeration_<mapnik::pattern_alignment_e>("pattern_alignment") .value("LOCAL",mapnik::LOCAL_ALIGNMENT) .value("GLOBAL",mapnik::GLOBAL_ALIGNMENT) ; class_<polygon_pattern_symbolizer, bases<symbolizer_base>>("PolygonPatternSymbolizer", init<>("Default ctor")) .def("__hash__",hash_impl_2<polygon_pattern_symbolizer>) ; } void export_raster_symbolizer() { using namespace boost::python; class_<raster_symbolizer, bases<symbolizer_base> >("RasterSymbolizer", init<>("Default ctor")) ; } void export_point_symbolizer() { using namespace boost::python; class_<point_symbolizer, bases<symbolizer_base> >("PointSymbolizer", init<>("Default Point Symbolizer - 4x4 black square")) .def("__hash__",hash_impl_2<point_symbolizer>) ; } void export_markers_symbolizer() { using namespace boost::python; mapnik::enumeration_<mapnik::multi_policy_e>("marker_multi_policy") .value("EACH",mapnik::EACH_MULTI) .value("WHOLE",mapnik::WHOLE_MULTI) .value("LARGEST",mapnik::LARGEST_MULTI) ; class_<markers_symbolizer, bases<symbolizer_base> >("MarkersSymbolizer", init<>("Default Markers Symbolizer - circle")) .def("__hash__",hash_impl_2<markers_symbolizer>) ; } void export_line_symbolizer() { using namespace boost::python; mapnik::enumeration_<mapnik::line_rasterizer_e>("line_rasterizer") .value("FULL",mapnik::RASTERIZER_FULL) .value("FAST",mapnik::RASTERIZER_FAST) ; mapnik::enumeration_<mapnik::line_cap_e>("stroke_linecap", "The possible values for a line cap used when drawing\n" "with a stroke.\n") .value("BUTT_CAP",mapnik::BUTT_CAP) .value("SQUARE_CAP",mapnik::SQUARE_CAP) .value("ROUND_CAP",mapnik::ROUND_CAP) ; mapnik::enumeration_<mapnik::line_join_e>("stroke_linejoin", "The possible values for the line joining mode\n" "when drawing with a stroke.\n") .value("MITER_JOIN",mapnik::MITER_JOIN) .value("MITER_REVERT_JOIN",mapnik::MITER_REVERT_JOIN) .value("ROUND_JOIN",mapnik::ROUND_JOIN) .value("BEVEL_JOIN",mapnik::BEVEL_JOIN) ; class_<line_symbolizer, bases<symbolizer_base> >("LineSymbolizer", init<>("Default LineSymbolizer - 1px solid black")) .def("__hash__",hash_impl_2<line_symbolizer>) ; } void export_line_pattern_symbolizer() { using namespace boost::python; class_<line_pattern_symbolizer, bases<symbolizer_base> >("LinePatternSymbolizer", init<> ("Default LinePatternSymbolizer")) .def("__hash__",hash_impl_2<line_pattern_symbolizer>) ; } void export_debug_symbolizer() { using namespace boost::python; mapnik::enumeration_<mapnik::debug_symbolizer_mode_e>("debug_symbolizer_mode") .value("COLLISION",mapnik::DEBUG_SYM_MODE_COLLISION) .value("VERTEX",mapnik::DEBUG_SYM_MODE_VERTEX) ; class_<debug_symbolizer, bases<symbolizer_base> >("DebugSymbolizer", init<>("Default debug Symbolizer")) .def("__hash__",hash_impl_2<debug_symbolizer>) ; } void export_building_symbolizer() { using namespace boost::python; class_<building_symbolizer, bases<symbolizer_base> >("BuildingSymbolizer", init<>("Default BuildingSymbolizer")) .def("__hash__",hash_impl_2<building_symbolizer>) ; } void export_collision_symbolizer() { using namespace boost::python; class_<collision_symbolizer, bases<symbolizer_base> >("CollisionSymbolizer", init<>("Default Collision Symbolizer")) .def("__hash__",hash_impl_2<collision_symbolizer>) ; } void export_enums() { using namespace boost::python; mapnik::enumeration_<mapnik::label_placement_e>("label_placement") .value("POINT", mapnik::POINT_PLACEMENT) .value("LINE", mapnik::LINE_PLACEMENT) .value("VERTEX", mapnik::VERTEX_PLACEMENT) .value("INTERIOR", mapnik::INTERIOR_PLACEMENT) .value("GRID", mapnik::GRID_PLACEMENT) .value("VERTEX_FIRST", mapnik::VERTEX_FIRST_PLACEMENT) .value("VERTEX_LAST", mapnik::VERTEX_LAST_PLACEMENT) .value("CENTROID", mapnik::CENTROID_PLACEMENT) .value("ALTERNATING_GRID", mapnik::ALTERNATING_GRID_PLACEMENT) ; enum_<mapnik::simplify_algorithm_e>("simplify_algorithm") .value("radial_distance", mapnik::radial_distance) .value("douglas_peucker", mapnik::douglas_peucker) .value("visvalingam_whyatt", mapnik::visvalingam_whyatt) .value("zhao_saalfeld", mapnik::zhao_saalfeld) ; }
mapycz/python-mapnik
src/mapnik_symbolizer.cpp
C++
lgpl-2.1
12,712
require 'test/unit' require 'coderay' class CommentFilterTest < Test::Unit::TestCase def test_filtering_comments tokens = CodeRay.scan <<-RUBY, :ruby #!/usr/bin/env ruby # a minimal Ruby program puts "Hello world!" RUBY assert_equal <<-RUBY_FILTERED, tokens.comment_filter.text #!/usr/bin/env ruby puts "Hello world!" RUBY_FILTERED end def test_filtering_docstrings tokens = CodeRay.scan <<-PYTHON, :python ''' Assuming this is file mymodule.py then this string, being the first statement in the file will become the mymodule modules docstring when the file is imported ''' class Myclass(): """ The class's docstring """ def mymethod(self): '''The method's docstring''' def myfunction(): """The function's docstring""" PYTHON assert_equal <<-PYTHON_FILTERED.chomp, tokens.comment_filter.text class Myclass(): def mymethod(self): def myfunction(): PYTHON_FILTERED end end
dslh/coderay
test/unit/comment_filter.rb
Ruby
lgpl-2.1
976
//===-- MipsAsmParser.cpp - Parse Mips assembly to MCInst instructions ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MCTargetDesc/MipsABIInfo.h" #include "MCTargetDesc/MipsMCExpr.h" #include "MCTargetDesc/MipsMCTargetDesc.h" #include "MipsRegisterInfo.h" #include "MipsTargetObjectFile.h" #include "MipsTargetStreamer.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstBuilder.h" #include "llvm/MC/MCParser/MCAsmLexer.h" #include "llvm/MC/MCParser/MCParsedAsmOperand.h" #include "llvm/MC/MCParser/MCTargetAsmParser.h" #include "llvm/MC/MCSectionELF.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ELF.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/raw_ostream.h" #include <memory> using namespace llvm; #define DEBUG_TYPE "mips-asm-parser" namespace llvm { class MCInstrInfo; } namespace { class MipsAssemblerOptions { public: MipsAssemblerOptions(const FeatureBitset &Features_) : ATReg(1), Reorder(true), Macro(true), Features(Features_) {} MipsAssemblerOptions(const MipsAssemblerOptions *Opts) { ATReg = Opts->getATRegIndex(); Reorder = Opts->isReorder(); Macro = Opts->isMacro(); Features = Opts->getFeatures(); } unsigned getATRegIndex() const { return ATReg; } bool setATRegIndex(unsigned Reg) { if (Reg > 31) return false; ATReg = Reg; return true; } bool isReorder() const { return Reorder; } void setReorder() { Reorder = true; } void setNoReorder() { Reorder = false; } bool isMacro() const { return Macro; } void setMacro() { Macro = true; } void setNoMacro() { Macro = false; } const FeatureBitset &getFeatures() const { return Features; } void setFeatures(const FeatureBitset &Features_) { Features = Features_; } // Set of features that are either architecture features or referenced // by them (e.g.: FeatureNaN2008 implied by FeatureMips32r6). // The full table can be found in MipsGenSubtargetInfo.inc (MipsFeatureKV[]). // The reason we need this mask is explained in the selectArch function. // FIXME: Ideally we would like TableGen to generate this information. static const FeatureBitset AllArchRelatedMask; private: unsigned ATReg; bool Reorder; bool Macro; FeatureBitset Features; }; } const FeatureBitset MipsAssemblerOptions::AllArchRelatedMask = { Mips::FeatureMips1, Mips::FeatureMips2, Mips::FeatureMips3, Mips::FeatureMips3_32, Mips::FeatureMips3_32r2, Mips::FeatureMips4, Mips::FeatureMips4_32, Mips::FeatureMips4_32r2, Mips::FeatureMips5, Mips::FeatureMips5_32r2, Mips::FeatureMips32, Mips::FeatureMips32r2, Mips::FeatureMips32r3, Mips::FeatureMips32r5, Mips::FeatureMips32r6, Mips::FeatureMips64, Mips::FeatureMips64r2, Mips::FeatureMips64r3, Mips::FeatureMips64r5, Mips::FeatureMips64r6, Mips::FeatureCnMips, Mips::FeatureFP64Bit, Mips::FeatureGP64Bit, Mips::FeatureNaN2008 }; namespace { class MipsAsmParser : public MCTargetAsmParser { MipsTargetStreamer &getTargetStreamer() { MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer(); return static_cast<MipsTargetStreamer &>(TS); } MipsABIInfo ABI; SmallVector<std::unique_ptr<MipsAssemblerOptions>, 2> AssemblerOptions; MCSymbol *CurrentFn; // Pointer to the function being parsed. It may be a // nullptr, which indicates that no function is currently // selected. This usually happens after an '.end func' // directive. bool IsLittleEndian; bool IsPicEnabled; bool IsCpRestoreSet; int CpRestoreOffset; unsigned CpSaveLocation; /// If true, then CpSaveLocation is a register, otherwise it's an offset. bool CpSaveLocationIsRegister; // Print a warning along with its fix-it message at the given range. void printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg, SMRange Range, bool ShowColors = true); #define GET_ASSEMBLER_HEADER #include "MipsGenAsmMatcher.inc" unsigned checkTargetMatchPredicate(MCInst &Inst) override; bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, OperandVector &Operands, MCStreamer &Out, uint64_t &ErrorInfo, bool MatchingInlineAsm) override; /// Parse a register as used in CFI directives bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override; bool parseParenSuffix(StringRef Name, OperandVector &Operands); bool parseBracketSuffix(StringRef Name, OperandVector &Operands); bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc, OperandVector &Operands) override; bool ParseDirective(AsmToken DirectiveID) override; OperandMatchResultTy parseMemOperand(OperandVector &Operands); OperandMatchResultTy matchAnyRegisterNameWithoutDollar(OperandVector &Operands, StringRef Identifier, SMLoc S); OperandMatchResultTy matchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S); OperandMatchResultTy parseAnyRegister(OperandVector &Operands); OperandMatchResultTy parseImm(OperandVector &Operands); OperandMatchResultTy parseJumpTarget(OperandVector &Operands); OperandMatchResultTy parseInvNum(OperandVector &Operands); OperandMatchResultTy parseLSAImm(OperandVector &Operands); OperandMatchResultTy parseRegisterPair(OperandVector &Operands); OperandMatchResultTy parseMovePRegPair(OperandVector &Operands); OperandMatchResultTy parseRegisterList(OperandVector &Operands); bool searchSymbolAlias(OperandVector &Operands); bool parseOperand(OperandVector &, StringRef Mnemonic); enum MacroExpanderResultTy { MER_NotAMacro, MER_Success, MER_Fail, }; // Expands assembly pseudo instructions. MacroExpanderResultTy tryExpandInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandJalWithRegs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool loadImmediate(int64_t ImmValue, unsigned DstReg, unsigned SrcReg, bool Is32BitImm, bool IsAddress, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool loadAndAddSymbolAddress(const MCExpr *SymExpr, unsigned DstReg, unsigned SrcReg, bool Is32BitSym, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandLoadAddress(unsigned DstReg, unsigned BaseReg, const MCOperand &Offset, bool Is32BitAddress, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); void expandMemInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI, bool IsLoad, bool IsImmOpnd); void expandLoadInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI, bool IsImmOpnd); void expandStoreInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI, bool IsImmOpnd); bool expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandAliasImmediate(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandBranchImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandCondBranches(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandDiv(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI, const bool IsMips64, const bool Signed); bool expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandUlw(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandDRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandDRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool expandAbs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); void createCpRestoreMemOp(bool IsLoad, int StackOffset, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); bool reportParseError(Twine ErrorMsg); bool reportParseError(SMLoc Loc, Twine ErrorMsg); bool parseMemOffset(const MCExpr *&Res, bool isParenExpr); bool parseRelocOperand(const MCExpr *&Res); const MCExpr *evaluateRelocExpr(const MCExpr *Expr, StringRef RelocStr); bool isEvaluated(const MCExpr *Expr); bool parseSetMips0Directive(); bool parseSetArchDirective(); bool parseSetFeature(uint64_t Feature); bool isPicAndNotNxxAbi(); // Used by .cpload, .cprestore, and .cpsetup. bool parseDirectiveCpLoad(SMLoc Loc); bool parseDirectiveCpRestore(SMLoc Loc); bool parseDirectiveCPSetup(); bool parseDirectiveCPReturn(); bool parseDirectiveNaN(); bool parseDirectiveSet(); bool parseDirectiveOption(); bool parseInsnDirective(); bool parseSSectionDirective(StringRef Section, unsigned Type); bool parseSetAtDirective(); bool parseSetNoAtDirective(); bool parseSetMacroDirective(); bool parseSetNoMacroDirective(); bool parseSetMsaDirective(); bool parseSetNoMsaDirective(); bool parseSetNoDspDirective(); bool parseSetReorderDirective(); bool parseSetNoReorderDirective(); bool parseSetMips16Directive(); bool parseSetNoMips16Directive(); bool parseSetFpDirective(); bool parseSetOddSPRegDirective(); bool parseSetNoOddSPRegDirective(); bool parseSetPopDirective(); bool parseSetPushDirective(); bool parseSetSoftFloatDirective(); bool parseSetHardFloatDirective(); bool parseSetAssignment(); bool parseDataDirective(unsigned Size, SMLoc L); bool parseDirectiveGpWord(); bool parseDirectiveGpDWord(); bool parseDirectiveModule(); bool parseDirectiveModuleFP(); bool parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI, StringRef Directive); bool parseInternalDirectiveReallowModule(); bool eatComma(StringRef ErrorStr); int matchCPURegisterName(StringRef Symbol); int matchHWRegsRegisterName(StringRef Symbol); int matchRegisterByNumber(unsigned RegNum, unsigned RegClass); int matchFPURegisterName(StringRef Name); int matchFCCRegisterName(StringRef Name); int matchACRegisterName(StringRef Name); int matchMSA128RegisterName(StringRef Name); int matchMSA128CtrlRegisterName(StringRef Name); unsigned getReg(int RC, int RegNo); unsigned getGPR(int RegNo); /// Returns the internal register number for the current AT. Also checks if /// the current AT is unavailable (set to $0) and gives an error if it is. /// This should be used in pseudo-instruction expansions which need AT. unsigned getATReg(SMLoc Loc); bool processInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI); // Helper function that checks if the value of a vector index is within the // boundaries of accepted values for each RegisterKind // Example: INSERT.B $w0[n], $1 => 16 > n >= 0 bool validateMSAIndex(int Val, int RegKind); // Selects a new architecture by updating the FeatureBits with the necessary // info including implied dependencies. // Internally, it clears all the feature bits related to *any* architecture // and selects the new one using the ToggleFeature functionality of the // MCSubtargetInfo object that handles implied dependencies. The reason we // clear all the arch related bits manually is because ToggleFeature only // clears the features that imply the feature being cleared and not the // features implied by the feature being cleared. This is easier to see // with an example: // -------------------------------------------------- // | Feature | Implies | // | -------------------------------------------------| // | FeatureMips1 | None | // | FeatureMips2 | FeatureMips1 | // | FeatureMips3 | FeatureMips2 | FeatureMipsGP64 | // | FeatureMips4 | FeatureMips3 | // | ... | | // -------------------------------------------------- // // Setting Mips3 is equivalent to set: (FeatureMips3 | FeatureMips2 | // FeatureMipsGP64 | FeatureMips1) // Clearing Mips3 is equivalent to clear (FeatureMips3 | FeatureMips4). void selectArch(StringRef ArchFeature) { MCSubtargetInfo &STI = copySTI(); FeatureBitset FeatureBits = STI.getFeatureBits(); FeatureBits &= ~MipsAssemblerOptions::AllArchRelatedMask; STI.setFeatureBits(FeatureBits); setAvailableFeatures( ComputeAvailableFeatures(STI.ToggleFeature(ArchFeature))); AssemblerOptions.back()->setFeatures(STI.getFeatureBits()); } void setFeatureBits(uint64_t Feature, StringRef FeatureString) { if (!(getSTI().getFeatureBits()[Feature])) { MCSubtargetInfo &STI = copySTI(); setAvailableFeatures( ComputeAvailableFeatures(STI.ToggleFeature(FeatureString))); AssemblerOptions.back()->setFeatures(STI.getFeatureBits()); } } void clearFeatureBits(uint64_t Feature, StringRef FeatureString) { if (getSTI().getFeatureBits()[Feature]) { MCSubtargetInfo &STI = copySTI(); setAvailableFeatures( ComputeAvailableFeatures(STI.ToggleFeature(FeatureString))); AssemblerOptions.back()->setFeatures(STI.getFeatureBits()); } } void setModuleFeatureBits(uint64_t Feature, StringRef FeatureString) { setFeatureBits(Feature, FeatureString); AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits()); } void clearModuleFeatureBits(uint64_t Feature, StringRef FeatureString) { clearFeatureBits(Feature, FeatureString); AssemblerOptions.front()->setFeatures(getSTI().getFeatureBits()); } public: enum MipsMatchResultTy { Match_RequiresDifferentSrcAndDst = FIRST_TARGET_MATCH_RESULT_TY, Match_RequiresDifferentOperands, Match_RequiresNoZeroRegister, #define GET_OPERAND_DIAGNOSTIC_TYPES #include "MipsGenAsmMatcher.inc" #undef GET_OPERAND_DIAGNOSTIC_TYPES }; MipsAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser, const MCInstrInfo &MII, const MCTargetOptions &Options) : MCTargetAsmParser(Options, sti), ABI(MipsABIInfo::computeTargetABI(Triple(sti.getTargetTriple()), sti.getCPU(), Options)) { MCAsmParserExtension::Initialize(parser); parser.addAliasForDirective(".asciiz", ".asciz"); // Initialize the set of available features. setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits())); // Remember the initial assembler options. The user can not modify these. AssemblerOptions.push_back( llvm::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits())); // Create an assembler options environment for the user to modify. AssemblerOptions.push_back( llvm::make_unique<MipsAssemblerOptions>(getSTI().getFeatureBits())); getTargetStreamer().updateABIInfo(*this); if (!isABI_O32() && !useOddSPReg() != 0) report_fatal_error("-mno-odd-spreg requires the O32 ABI"); CurrentFn = nullptr; IsPicEnabled = getContext().getObjectFileInfo()->isPositionIndependent(); IsCpRestoreSet = false; CpRestoreOffset = -1; const Triple &TheTriple = sti.getTargetTriple(); if ((TheTriple.getArch() == Triple::mips) || (TheTriple.getArch() == Triple::mips64)) IsLittleEndian = false; else IsLittleEndian = true; } /// True if all of $fcc0 - $fcc7 exist for the current ISA. bool hasEightFccRegisters() const { return hasMips4() || hasMips32(); } bool isGP64bit() const { return getSTI().getFeatureBits()[Mips::FeatureGP64Bit]; } bool isFP64bit() const { return getSTI().getFeatureBits()[Mips::FeatureFP64Bit]; } const MipsABIInfo &getABI() const { return ABI; } bool isABI_N32() const { return ABI.IsN32(); } bool isABI_N64() const { return ABI.IsN64(); } bool isABI_O32() const { return ABI.IsO32(); } bool isABI_FPXX() const { return getSTI().getFeatureBits()[Mips::FeatureFPXX]; } bool useOddSPReg() const { return !(getSTI().getFeatureBits()[Mips::FeatureNoOddSPReg]); } bool inMicroMipsMode() const { return getSTI().getFeatureBits()[Mips::FeatureMicroMips]; } bool hasMips1() const { return getSTI().getFeatureBits()[Mips::FeatureMips1]; } bool hasMips2() const { return getSTI().getFeatureBits()[Mips::FeatureMips2]; } bool hasMips3() const { return getSTI().getFeatureBits()[Mips::FeatureMips3]; } bool hasMips4() const { return getSTI().getFeatureBits()[Mips::FeatureMips4]; } bool hasMips5() const { return getSTI().getFeatureBits()[Mips::FeatureMips5]; } bool hasMips32() const { return getSTI().getFeatureBits()[Mips::FeatureMips32]; } bool hasMips64() const { return getSTI().getFeatureBits()[Mips::FeatureMips64]; } bool hasMips32r2() const { return getSTI().getFeatureBits()[Mips::FeatureMips32r2]; } bool hasMips64r2() const { return getSTI().getFeatureBits()[Mips::FeatureMips64r2]; } bool hasMips32r3() const { return (getSTI().getFeatureBits()[Mips::FeatureMips32r3]); } bool hasMips64r3() const { return (getSTI().getFeatureBits()[Mips::FeatureMips64r3]); } bool hasMips32r5() const { return (getSTI().getFeatureBits()[Mips::FeatureMips32r5]); } bool hasMips64r5() const { return (getSTI().getFeatureBits()[Mips::FeatureMips64r5]); } bool hasMips32r6() const { return getSTI().getFeatureBits()[Mips::FeatureMips32r6]; } bool hasMips64r6() const { return getSTI().getFeatureBits()[Mips::FeatureMips64r6]; } bool hasDSP() const { return getSTI().getFeatureBits()[Mips::FeatureDSP]; } bool hasDSPR2() const { return getSTI().getFeatureBits()[Mips::FeatureDSPR2]; } bool hasDSPR3() const { return getSTI().getFeatureBits()[Mips::FeatureDSPR3]; } bool hasMSA() const { return getSTI().getFeatureBits()[Mips::FeatureMSA]; } bool hasCnMips() const { return (getSTI().getFeatureBits()[Mips::FeatureCnMips]); } bool inPicMode() { return IsPicEnabled; } bool inMips16Mode() const { return getSTI().getFeatureBits()[Mips::FeatureMips16]; } bool useTraps() const { return getSTI().getFeatureBits()[Mips::FeatureUseTCCInDIV]; } bool useSoftFloat() const { return getSTI().getFeatureBits()[Mips::FeatureSoftFloat]; } /// Warn if RegIndex is the same as the current AT. void warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc); void warnIfNoMacro(SMLoc Loc); bool isLittle() const { return IsLittleEndian; } }; } namespace { /// MipsOperand - Instances of this class represent a parsed Mips machine /// instruction. class MipsOperand : public MCParsedAsmOperand { public: /// Broad categories of register classes /// The exact class is finalized by the render method. enum RegKind { RegKind_GPR = 1, /// GPR32 and GPR64 (depending on isGP64bit()) RegKind_FGR = 2, /// FGR32, FGR64, AFGR64 (depending on context and /// isFP64bit()) RegKind_FCC = 4, /// FCC RegKind_MSA128 = 8, /// MSA128[BHWD] (makes no difference which) RegKind_MSACtrl = 16, /// MSA control registers RegKind_COP2 = 32, /// COP2 RegKind_ACC = 64, /// HI32DSP, LO32DSP, and ACC64DSP (depending on /// context). RegKind_CCR = 128, /// CCR RegKind_HWRegs = 256, /// HWRegs RegKind_COP3 = 512, /// COP3 RegKind_COP0 = 1024, /// COP0 /// Potentially any (e.g. $1) RegKind_Numeric = RegKind_GPR | RegKind_FGR | RegKind_FCC | RegKind_MSA128 | RegKind_MSACtrl | RegKind_COP2 | RegKind_ACC | RegKind_CCR | RegKind_HWRegs | RegKind_COP3 | RegKind_COP0 }; private: enum KindTy { k_Immediate, /// An immediate (possibly involving symbol references) k_Memory, /// Base + Offset Memory Address k_PhysRegister, /// A physical register from the Mips namespace k_RegisterIndex, /// A register index in one or more RegKind. k_Token, /// A simple token k_RegList, /// A physical register list k_RegPair /// A pair of physical register } Kind; public: MipsOperand(KindTy K, MipsAsmParser &Parser) : MCParsedAsmOperand(), Kind(K), AsmParser(Parser) {} private: /// For diagnostics, and checking the assembler temporary MipsAsmParser &AsmParser; struct Token { const char *Data; unsigned Length; }; struct PhysRegOp { unsigned Num; /// Register Number }; struct RegIdxOp { unsigned Index; /// Index into the register class RegKind Kind; /// Bitfield of the kinds it could possibly be const MCRegisterInfo *RegInfo; }; struct ImmOp { const MCExpr *Val; }; struct MemOp { MipsOperand *Base; const MCExpr *Off; }; struct RegListOp { SmallVector<unsigned, 10> *List; }; union { struct Token Tok; struct PhysRegOp PhysReg; struct RegIdxOp RegIdx; struct ImmOp Imm; struct MemOp Mem; struct RegListOp RegList; }; SMLoc StartLoc, EndLoc; /// Internal constructor for register kinds static std::unique_ptr<MipsOperand> CreateReg(unsigned Index, RegKind RegKind, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E, MipsAsmParser &Parser) { auto Op = make_unique<MipsOperand>(k_RegisterIndex, Parser); Op->RegIdx.Index = Index; Op->RegIdx.RegInfo = RegInfo; Op->RegIdx.Kind = RegKind; Op->StartLoc = S; Op->EndLoc = E; return Op; } public: /// Coerce the register to GPR32 and return the real register for the current /// target. unsigned getGPR32Reg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!"); AsmParser.warnIfRegIndexIsAT(RegIdx.Index, StartLoc); unsigned ClassID = Mips::GPR32RegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } /// Coerce the register to GPR32 and return the real register for the current /// target. unsigned getGPRMM16Reg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!"); unsigned ClassID = Mips::GPR32RegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } /// Coerce the register to GPR64 and return the real register for the current /// target. unsigned getGPR64Reg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_GPR) && "Invalid access!"); unsigned ClassID = Mips::GPR64RegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } private: /// Coerce the register to AFGR64 and return the real register for the current /// target. unsigned getAFGR64Reg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!"); if (RegIdx.Index % 2 != 0) AsmParser.Warning(StartLoc, "Float register should be even."); return RegIdx.RegInfo->getRegClass(Mips::AFGR64RegClassID) .getRegister(RegIdx.Index / 2); } /// Coerce the register to FGR64 and return the real register for the current /// target. unsigned getFGR64Reg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!"); return RegIdx.RegInfo->getRegClass(Mips::FGR64RegClassID) .getRegister(RegIdx.Index); } /// Coerce the register to FGR32 and return the real register for the current /// target. unsigned getFGR32Reg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!"); return RegIdx.RegInfo->getRegClass(Mips::FGR32RegClassID) .getRegister(RegIdx.Index); } /// Coerce the register to FGRH32 and return the real register for the current /// target. unsigned getFGRH32Reg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_FGR) && "Invalid access!"); return RegIdx.RegInfo->getRegClass(Mips::FGRH32RegClassID) .getRegister(RegIdx.Index); } /// Coerce the register to FCC and return the real register for the current /// target. unsigned getFCCReg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_FCC) && "Invalid access!"); return RegIdx.RegInfo->getRegClass(Mips::FCCRegClassID) .getRegister(RegIdx.Index); } /// Coerce the register to MSA128 and return the real register for the current /// target. unsigned getMSA128Reg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_MSA128) && "Invalid access!"); // It doesn't matter which of the MSA128[BHWD] classes we use. They are all // identical unsigned ClassID = Mips::MSA128BRegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } /// Coerce the register to MSACtrl and return the real register for the /// current target. unsigned getMSACtrlReg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_MSACtrl) && "Invalid access!"); unsigned ClassID = Mips::MSACtrlRegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } /// Coerce the register to COP0 and return the real register for the /// current target. unsigned getCOP0Reg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_COP0) && "Invalid access!"); unsigned ClassID = Mips::COP0RegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } /// Coerce the register to COP2 and return the real register for the /// current target. unsigned getCOP2Reg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_COP2) && "Invalid access!"); unsigned ClassID = Mips::COP2RegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } /// Coerce the register to COP3 and return the real register for the /// current target. unsigned getCOP3Reg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_COP3) && "Invalid access!"); unsigned ClassID = Mips::COP3RegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } /// Coerce the register to ACC64DSP and return the real register for the /// current target. unsigned getACC64DSPReg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!"); unsigned ClassID = Mips::ACC64DSPRegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } /// Coerce the register to HI32DSP and return the real register for the /// current target. unsigned getHI32DSPReg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!"); unsigned ClassID = Mips::HI32DSPRegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } /// Coerce the register to LO32DSP and return the real register for the /// current target. unsigned getLO32DSPReg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_ACC) && "Invalid access!"); unsigned ClassID = Mips::LO32DSPRegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } /// Coerce the register to CCR and return the real register for the /// current target. unsigned getCCRReg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_CCR) && "Invalid access!"); unsigned ClassID = Mips::CCRRegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } /// Coerce the register to HWRegs and return the real register for the /// current target. unsigned getHWRegsReg() const { assert(isRegIdx() && (RegIdx.Kind & RegKind_HWRegs) && "Invalid access!"); unsigned ClassID = Mips::HWRegsRegClassID; return RegIdx.RegInfo->getRegClass(ClassID).getRegister(RegIdx.Index); } public: void addExpr(MCInst &Inst, const MCExpr *Expr) const { // Add as immediate when possible. Null MCExpr = 0. if (!Expr) Inst.addOperand(MCOperand::createImm(0)); else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr)) Inst.addOperand(MCOperand::createImm(CE->getValue())); else Inst.addOperand(MCOperand::createExpr(Expr)); } void addRegOperands(MCInst &Inst, unsigned N) const { llvm_unreachable("Use a custom parser instead"); } /// Render the operand to an MCInst as a GPR32 /// Asserts if the wrong number of operands are requested, or the operand /// is not a k_RegisterIndex compatible with RegKind_GPR void addGPR32AsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getGPR32Reg())); } void addGPRMM16AsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getGPRMM16Reg())); } void addGPRMM16AsmRegZeroOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getGPRMM16Reg())); } void addGPRMM16AsmRegMovePOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getGPRMM16Reg())); } /// Render the operand to an MCInst as a GPR64 /// Asserts if the wrong number of operands are requested, or the operand /// is not a k_RegisterIndex compatible with RegKind_GPR void addGPR64AsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getGPR64Reg())); } void addAFGR64AsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getAFGR64Reg())); } void addFGR64AsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getFGR64Reg())); } void addFGR32AsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getFGR32Reg())); // FIXME: We ought to do this for -integrated-as without -via-file-asm too. if (!AsmParser.useOddSPReg() && RegIdx.Index & 1) AsmParser.Error(StartLoc, "-mno-odd-spreg prohibits the use of odd FPU " "registers"); } void addFGRH32AsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getFGRH32Reg())); } void addFCCAsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getFCCReg())); } void addMSA128AsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getMSA128Reg())); } void addMSACtrlAsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getMSACtrlReg())); } void addCOP0AsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getCOP0Reg())); } void addCOP2AsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getCOP2Reg())); } void addCOP3AsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getCOP3Reg())); } void addACC64DSPAsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getACC64DSPReg())); } void addHI32DSPAsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getHI32DSPReg())); } void addLO32DSPAsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getLO32DSPReg())); } void addCCRAsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getCCRReg())); } void addHWRegsAsmRegOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getHWRegsReg())); } template <unsigned Bits, int Offset = 0, int AdjustOffset = 0> void addConstantUImmOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); uint64_t Imm = getConstantImm() - Offset; Imm &= (1 << Bits) - 1; Imm += Offset; Imm += AdjustOffset; Inst.addOperand(MCOperand::createImm(Imm)); } template <unsigned Bits> void addSImmOperands(MCInst &Inst, unsigned N) const { if (isImm() && !isConstantImm()) { addExpr(Inst, getImm()); return; } addConstantSImmOperands<Bits, 0, 0>(Inst, N); } template <unsigned Bits> void addUImmOperands(MCInst &Inst, unsigned N) const { if (isImm() && !isConstantImm()) { addExpr(Inst, getImm()); return; } addConstantUImmOperands<Bits, 0, 0>(Inst, N); } template <unsigned Bits, int Offset = 0, int AdjustOffset = 0> void addConstantSImmOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); int64_t Imm = getConstantImm() - Offset; Imm = SignExtend64<Bits>(Imm); Imm += Offset; Imm += AdjustOffset; Inst.addOperand(MCOperand::createImm(Imm)); } void addImmOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); const MCExpr *Expr = getImm(); addExpr(Inst, Expr); } void addMemOperands(MCInst &Inst, unsigned N) const { assert(N == 2 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(AsmParser.getABI().ArePtrs64bit() ? getMemBase()->getGPR64Reg() : getMemBase()->getGPR32Reg())); const MCExpr *Expr = getMemOff(); addExpr(Inst, Expr); } void addMicroMipsMemOperands(MCInst &Inst, unsigned N) const { assert(N == 2 && "Invalid number of operands!"); Inst.addOperand(MCOperand::createReg(getMemBase()->getGPRMM16Reg())); const MCExpr *Expr = getMemOff(); addExpr(Inst, Expr); } void addRegListOperands(MCInst &Inst, unsigned N) const { assert(N == 1 && "Invalid number of operands!"); for (auto RegNo : getRegList()) Inst.addOperand(MCOperand::createReg(RegNo)); } void addRegPairOperands(MCInst &Inst, unsigned N) const { assert(N == 2 && "Invalid number of operands!"); assert((RegIdx.Kind & RegKind_GPR) && "Invalid access!"); unsigned RegNo = getRegPair(); AsmParser.warnIfRegIndexIsAT(RegNo, StartLoc); Inst.addOperand(MCOperand::createReg( RegIdx.RegInfo->getRegClass( AsmParser.getABI().AreGprs64bit() ? Mips::GPR64RegClassID : Mips::GPR32RegClassID).getRegister(RegNo++))); Inst.addOperand(MCOperand::createReg( RegIdx.RegInfo->getRegClass( AsmParser.getABI().AreGprs64bit() ? Mips::GPR64RegClassID : Mips::GPR32RegClassID).getRegister(RegNo))); } void addMovePRegPairOperands(MCInst &Inst, unsigned N) const { assert(N == 2 && "Invalid number of operands!"); for (auto RegNo : getRegList()) Inst.addOperand(MCOperand::createReg(RegNo)); } bool isReg() const override { // As a special case until we sort out the definition of div/divu, pretend // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly. if (isGPRAsmReg() && RegIdx.Index == 0) return true; return Kind == k_PhysRegister; } bool isRegIdx() const { return Kind == k_RegisterIndex; } bool isImm() const override { return Kind == k_Immediate; } bool isConstantImm() const { return isImm() && isa<MCConstantExpr>(getImm()); } bool isConstantImmz() const { return isConstantImm() && getConstantImm() == 0; } template <unsigned Bits, int Offset = 0> bool isConstantUImm() const { return isConstantImm() && isUInt<Bits>(getConstantImm() - Offset); } template <unsigned Bits> bool isSImm() const { return isConstantImm() ? isInt<Bits>(getConstantImm()) : isImm(); } template <unsigned Bits> bool isUImm() const { return isConstantImm() ? isUInt<Bits>(getConstantImm()) : isImm(); } template <unsigned Bits> bool isAnyImm() const { return isConstantImm() ? (isInt<Bits>(getConstantImm()) || isUInt<Bits>(getConstantImm())) : isImm(); } template <unsigned Bits, int Offset = 0> bool isConstantSImm() const { return isConstantImm() && isInt<Bits>(getConstantImm() - Offset); } template <unsigned Bottom, unsigned Top> bool isConstantUImmRange() const { return isConstantImm() && getConstantImm() >= Bottom && getConstantImm() <= Top; } bool isToken() const override { // Note: It's not possible to pretend that other operand kinds are tokens. // The matcher emitter checks tokens first. return Kind == k_Token; } bool isMem() const override { return Kind == k_Memory; } bool isConstantMemOff() const { return isMem() && isa<MCConstantExpr>(getMemOff()); } // Allow relocation operators. // FIXME: This predicate and others need to look through binary expressions // and determine whether a Value is a constant or not. template <unsigned Bits, unsigned ShiftAmount = 0> bool isMemWithSimmOffset() const { return isMem() && getMemBase()->isGPRAsmReg() && (isa<MCTargetExpr>(getMemOff()) || (isConstantMemOff() && isShiftedInt<Bits, ShiftAmount>(getConstantMemOff()))); } bool isMemWithGRPMM16Base() const { return isMem() && getMemBase()->isMM16AsmReg(); } template <unsigned Bits> bool isMemWithUimmOffsetSP() const { return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff()) && getMemBase()->isRegIdx() && (getMemBase()->getGPR32Reg() == Mips::SP); } template <unsigned Bits> bool isMemWithUimmWordAlignedOffsetSP() const { return isMem() && isConstantMemOff() && isUInt<Bits>(getConstantMemOff()) && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx() && (getMemBase()->getGPR32Reg() == Mips::SP); } template <unsigned Bits> bool isMemWithSimmWordAlignedOffsetGP() const { return isMem() && isConstantMemOff() && isInt<Bits>(getConstantMemOff()) && (getConstantMemOff() % 4 == 0) && getMemBase()->isRegIdx() && (getMemBase()->getGPR32Reg() == Mips::GP); } template <unsigned Bits, unsigned ShiftLeftAmount> bool isScaledUImm() const { return isConstantImm() && isShiftedUInt<Bits, ShiftLeftAmount>(getConstantImm()); } template <unsigned Bits, unsigned ShiftLeftAmount> bool isScaledSImm() const { return isConstantImm() && isShiftedInt<Bits, ShiftLeftAmount>(getConstantImm()); } bool isRegList16() const { if (!isRegList()) return false; int Size = RegList.List->size(); if (Size < 2 || Size > 5) return false; unsigned R0 = RegList.List->front(); unsigned R1 = RegList.List->back(); if (!((R0 == Mips::S0 && R1 == Mips::RA) || (R0 == Mips::S0_64 && R1 == Mips::RA_64))) return false; int PrevReg = *RegList.List->begin(); for (int i = 1; i < Size - 1; i++) { int Reg = (*(RegList.List))[i]; if ( Reg != PrevReg + 1) return false; PrevReg = Reg; } return true; } bool isInvNum() const { return Kind == k_Immediate; } bool isLSAImm() const { if (!isConstantImm()) return false; int64_t Val = getConstantImm(); return 1 <= Val && Val <= 4; } bool isRegList() const { return Kind == k_RegList; } bool isMovePRegPair() const { if (Kind != k_RegList || RegList.List->size() != 2) return false; unsigned R0 = RegList.List->front(); unsigned R1 = RegList.List->back(); if ((R0 == Mips::A1 && R1 == Mips::A2) || (R0 == Mips::A1 && R1 == Mips::A3) || (R0 == Mips::A2 && R1 == Mips::A3) || (R0 == Mips::A0 && R1 == Mips::S5) || (R0 == Mips::A0 && R1 == Mips::S6) || (R0 == Mips::A0 && R1 == Mips::A1) || (R0 == Mips::A0 && R1 == Mips::A2) || (R0 == Mips::A0 && R1 == Mips::A3) || (R0 == Mips::A1_64 && R1 == Mips::A2_64) || (R0 == Mips::A1_64 && R1 == Mips::A3_64) || (R0 == Mips::A2_64 && R1 == Mips::A3_64) || (R0 == Mips::A0_64 && R1 == Mips::S5_64) || (R0 == Mips::A0_64 && R1 == Mips::S6_64) || (R0 == Mips::A0_64 && R1 == Mips::A1_64) || (R0 == Mips::A0_64 && R1 == Mips::A2_64) || (R0 == Mips::A0_64 && R1 == Mips::A3_64)) return true; return false; } StringRef getToken() const { assert(Kind == k_Token && "Invalid access!"); return StringRef(Tok.Data, Tok.Length); } bool isRegPair() const { return Kind == k_RegPair && RegIdx.Index <= 30; } unsigned getReg() const override { // As a special case until we sort out the definition of div/divu, pretend // that $0/$zero are k_PhysRegister so that MCK_ZERO works correctly. if (Kind == k_RegisterIndex && RegIdx.Index == 0 && RegIdx.Kind & RegKind_GPR) return getGPR32Reg(); // FIXME: GPR64 too assert(Kind == k_PhysRegister && "Invalid access!"); return PhysReg.Num; } const MCExpr *getImm() const { assert((Kind == k_Immediate) && "Invalid access!"); return Imm.Val; } int64_t getConstantImm() const { const MCExpr *Val = getImm(); return static_cast<const MCConstantExpr *>(Val)->getValue(); } MipsOperand *getMemBase() const { assert((Kind == k_Memory) && "Invalid access!"); return Mem.Base; } const MCExpr *getMemOff() const { assert((Kind == k_Memory) && "Invalid access!"); return Mem.Off; } int64_t getConstantMemOff() const { return static_cast<const MCConstantExpr *>(getMemOff())->getValue(); } const SmallVectorImpl<unsigned> &getRegList() const { assert((Kind == k_RegList) && "Invalid access!"); return *(RegList.List); } unsigned getRegPair() const { assert((Kind == k_RegPair) && "Invalid access!"); return RegIdx.Index; } static std::unique_ptr<MipsOperand> CreateToken(StringRef Str, SMLoc S, MipsAsmParser &Parser) { auto Op = make_unique<MipsOperand>(k_Token, Parser); Op->Tok.Data = Str.data(); Op->Tok.Length = Str.size(); Op->StartLoc = S; Op->EndLoc = S; return Op; } /// Create a numeric register (e.g. $1). The exact register remains /// unresolved until an instruction successfully matches static std::unique_ptr<MipsOperand> createNumericReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E, MipsAsmParser &Parser) { DEBUG(dbgs() << "createNumericReg(" << Index << ", ...)\n"); return CreateReg(Index, RegKind_Numeric, RegInfo, S, E, Parser); } /// Create a register that is definitely a GPR. /// This is typically only used for named registers such as $gp. static std::unique_ptr<MipsOperand> createGPRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E, MipsAsmParser &Parser) { return CreateReg(Index, RegKind_GPR, RegInfo, S, E, Parser); } /// Create a register that is definitely a FGR. /// This is typically only used for named registers such as $f0. static std::unique_ptr<MipsOperand> createFGRReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E, MipsAsmParser &Parser) { return CreateReg(Index, RegKind_FGR, RegInfo, S, E, Parser); } /// Create a register that is definitely a HWReg. /// This is typically only used for named registers such as $hwr_cpunum. static std::unique_ptr<MipsOperand> createHWRegsReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E, MipsAsmParser &Parser) { return CreateReg(Index, RegKind_HWRegs, RegInfo, S, E, Parser); } /// Create a register that is definitely an FCC. /// This is typically only used for named registers such as $fcc0. static std::unique_ptr<MipsOperand> createFCCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E, MipsAsmParser &Parser) { return CreateReg(Index, RegKind_FCC, RegInfo, S, E, Parser); } /// Create a register that is definitely an ACC. /// This is typically only used for named registers such as $ac0. static std::unique_ptr<MipsOperand> createACCReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E, MipsAsmParser &Parser) { return CreateReg(Index, RegKind_ACC, RegInfo, S, E, Parser); } /// Create a register that is definitely an MSA128. /// This is typically only used for named registers such as $w0. static std::unique_ptr<MipsOperand> createMSA128Reg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E, MipsAsmParser &Parser) { return CreateReg(Index, RegKind_MSA128, RegInfo, S, E, Parser); } /// Create a register that is definitely an MSACtrl. /// This is typically only used for named registers such as $msaaccess. static std::unique_ptr<MipsOperand> createMSACtrlReg(unsigned Index, const MCRegisterInfo *RegInfo, SMLoc S, SMLoc E, MipsAsmParser &Parser) { return CreateReg(Index, RegKind_MSACtrl, RegInfo, S, E, Parser); } static std::unique_ptr<MipsOperand> CreateImm(const MCExpr *Val, SMLoc S, SMLoc E, MipsAsmParser &Parser) { auto Op = make_unique<MipsOperand>(k_Immediate, Parser); Op->Imm.Val = Val; Op->StartLoc = S; Op->EndLoc = E; return Op; } static std::unique_ptr<MipsOperand> CreateMem(std::unique_ptr<MipsOperand> Base, const MCExpr *Off, SMLoc S, SMLoc E, MipsAsmParser &Parser) { auto Op = make_unique<MipsOperand>(k_Memory, Parser); Op->Mem.Base = Base.release(); Op->Mem.Off = Off; Op->StartLoc = S; Op->EndLoc = E; return Op; } static std::unique_ptr<MipsOperand> CreateRegList(SmallVectorImpl<unsigned> &Regs, SMLoc StartLoc, SMLoc EndLoc, MipsAsmParser &Parser) { assert (Regs.size() > 0 && "Empty list not allowed"); auto Op = make_unique<MipsOperand>(k_RegList, Parser); Op->RegList.List = new SmallVector<unsigned, 10>(Regs.begin(), Regs.end()); Op->StartLoc = StartLoc; Op->EndLoc = EndLoc; return Op; } static std::unique_ptr<MipsOperand> CreateRegPair(const MipsOperand &MOP, SMLoc S, SMLoc E, MipsAsmParser &Parser) { auto Op = make_unique<MipsOperand>(k_RegPair, Parser); Op->RegIdx.Index = MOP.RegIdx.Index; Op->RegIdx.RegInfo = MOP.RegIdx.RegInfo; Op->RegIdx.Kind = MOP.RegIdx.Kind; Op->StartLoc = S; Op->EndLoc = E; return Op; } bool isGPRAsmReg() const { return isRegIdx() && RegIdx.Kind & RegKind_GPR && RegIdx.Index <= 31; } bool isMM16AsmReg() const { if (!(isRegIdx() && RegIdx.Kind)) return false; return ((RegIdx.Index >= 2 && RegIdx.Index <= 7) || RegIdx.Index == 16 || RegIdx.Index == 17); } bool isMM16AsmRegZero() const { if (!(isRegIdx() && RegIdx.Kind)) return false; return (RegIdx.Index == 0 || (RegIdx.Index >= 2 && RegIdx.Index <= 7) || RegIdx.Index == 17); } bool isMM16AsmRegMoveP() const { if (!(isRegIdx() && RegIdx.Kind)) return false; return (RegIdx.Index == 0 || (RegIdx.Index >= 2 && RegIdx.Index <= 3) || (RegIdx.Index >= 16 && RegIdx.Index <= 20)); } bool isFGRAsmReg() const { // AFGR64 is $0-$15 but we handle this in getAFGR64() return isRegIdx() && RegIdx.Kind & RegKind_FGR && RegIdx.Index <= 31; } bool isHWRegsAsmReg() const { return isRegIdx() && RegIdx.Kind & RegKind_HWRegs && RegIdx.Index <= 31; } bool isCCRAsmReg() const { return isRegIdx() && RegIdx.Kind & RegKind_CCR && RegIdx.Index <= 31; } bool isFCCAsmReg() const { if (!(isRegIdx() && RegIdx.Kind & RegKind_FCC)) return false; if (!AsmParser.hasEightFccRegisters()) return RegIdx.Index == 0; return RegIdx.Index <= 7; } bool isACCAsmReg() const { return isRegIdx() && RegIdx.Kind & RegKind_ACC && RegIdx.Index <= 3; } bool isCOP0AsmReg() const { return isRegIdx() && RegIdx.Kind & RegKind_COP0 && RegIdx.Index <= 31; } bool isCOP2AsmReg() const { return isRegIdx() && RegIdx.Kind & RegKind_COP2 && RegIdx.Index <= 31; } bool isCOP3AsmReg() const { return isRegIdx() && RegIdx.Kind & RegKind_COP3 && RegIdx.Index <= 31; } bool isMSA128AsmReg() const { return isRegIdx() && RegIdx.Kind & RegKind_MSA128 && RegIdx.Index <= 31; } bool isMSACtrlAsmReg() const { return isRegIdx() && RegIdx.Kind & RegKind_MSACtrl && RegIdx.Index <= 7; } /// getStartLoc - Get the location of the first token of this operand. SMLoc getStartLoc() const override { return StartLoc; } /// getEndLoc - Get the location of the last token of this operand. SMLoc getEndLoc() const override { return EndLoc; } virtual ~MipsOperand() { switch (Kind) { case k_Immediate: break; case k_Memory: delete Mem.Base; break; case k_RegList: delete RegList.List; case k_PhysRegister: case k_RegisterIndex: case k_Token: case k_RegPair: break; } } void print(raw_ostream &OS) const override { switch (Kind) { case k_Immediate: OS << "Imm<"; OS << *Imm.Val; OS << ">"; break; case k_Memory: OS << "Mem<"; Mem.Base->print(OS); OS << ", "; OS << *Mem.Off; OS << ">"; break; case k_PhysRegister: OS << "PhysReg<" << PhysReg.Num << ">"; break; case k_RegisterIndex: OS << "RegIdx<" << RegIdx.Index << ":" << RegIdx.Kind << ">"; break; case k_Token: OS << Tok.Data; break; case k_RegList: OS << "RegList< "; for (auto Reg : (*RegList.List)) OS << Reg << " "; OS << ">"; break; case k_RegPair: OS << "RegPair<" << RegIdx.Index << "," << RegIdx.Index + 1 << ">"; break; } } }; // class MipsOperand } // namespace namespace llvm { extern const MCInstrDesc MipsInsts[]; } static const MCInstrDesc &getInstDesc(unsigned Opcode) { return MipsInsts[Opcode]; } static bool hasShortDelaySlot(unsigned Opcode) { switch (Opcode) { case Mips::JALS_MM: case Mips::JALRS_MM: case Mips::JALRS16_MM: case Mips::BGEZALS_MM: case Mips::BLTZALS_MM: return true; default: return false; } } static const MCSymbol *getSingleMCSymbol(const MCExpr *Expr) { if (const MCSymbolRefExpr *SRExpr = dyn_cast<MCSymbolRefExpr>(Expr)) { return &SRExpr->getSymbol(); } if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr)) { const MCSymbol *LHSSym = getSingleMCSymbol(BExpr->getLHS()); const MCSymbol *RHSSym = getSingleMCSymbol(BExpr->getRHS()); if (LHSSym) return LHSSym; if (RHSSym) return RHSSym; return nullptr; } if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr)) return getSingleMCSymbol(UExpr->getSubExpr()); return nullptr; } static unsigned countMCSymbolRefExpr(const MCExpr *Expr) { if (isa<MCSymbolRefExpr>(Expr)) return 1; if (const MCBinaryExpr *BExpr = dyn_cast<MCBinaryExpr>(Expr)) return countMCSymbolRefExpr(BExpr->getLHS()) + countMCSymbolRefExpr(BExpr->getRHS()); if (const MCUnaryExpr *UExpr = dyn_cast<MCUnaryExpr>(Expr)) return countMCSymbolRefExpr(UExpr->getSubExpr()); return 0; } bool MipsAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode()); bool ExpandedJalSym = false; Inst.setLoc(IDLoc); if (MCID.isBranch() || MCID.isCall()) { const unsigned Opcode = Inst.getOpcode(); MCOperand Offset; switch (Opcode) { default: break; case Mips::BBIT0: case Mips::BBIT032: case Mips::BBIT1: case Mips::BBIT132: assert(hasCnMips() && "instruction only valid for octeon cpus"); // Fall through case Mips::BEQ: case Mips::BNE: case Mips::BEQ_MM: case Mips::BNE_MM: assert(MCID.getNumOperands() == 3 && "unexpected number of operands"); Offset = Inst.getOperand(2); if (!Offset.isImm()) break; // We'll deal with this situation later on when applying fixups. if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm())) return Error(IDLoc, "branch target out of range"); if (OffsetToAlignment(Offset.getImm(), 1LL << (inMicroMipsMode() ? 1 : 2))) return Error(IDLoc, "branch to misaligned address"); break; case Mips::BGEZ: case Mips::BGTZ: case Mips::BLEZ: case Mips::BLTZ: case Mips::BGEZAL: case Mips::BLTZAL: case Mips::BC1F: case Mips::BC1T: case Mips::BGEZ_MM: case Mips::BGTZ_MM: case Mips::BLEZ_MM: case Mips::BLTZ_MM: case Mips::BGEZAL_MM: case Mips::BLTZAL_MM: case Mips::BC1F_MM: case Mips::BC1T_MM: case Mips::BC1EQZC_MMR6: case Mips::BC1NEZC_MMR6: case Mips::BC2EQZC_MMR6: case Mips::BC2NEZC_MMR6: assert(MCID.getNumOperands() == 2 && "unexpected number of operands"); Offset = Inst.getOperand(1); if (!Offset.isImm()) break; // We'll deal with this situation later on when applying fixups. if (!isIntN(inMicroMipsMode() ? 17 : 18, Offset.getImm())) return Error(IDLoc, "branch target out of range"); if (OffsetToAlignment(Offset.getImm(), 1LL << (inMicroMipsMode() ? 1 : 2))) return Error(IDLoc, "branch to misaligned address"); break; case Mips::BEQZ16_MM: case Mips::BEQZC16_MMR6: case Mips::BNEZ16_MM: case Mips::BNEZC16_MMR6: assert(MCID.getNumOperands() == 2 && "unexpected number of operands"); Offset = Inst.getOperand(1); if (!Offset.isImm()) break; // We'll deal with this situation later on when applying fixups. if (!isInt<8>(Offset.getImm())) return Error(IDLoc, "branch target out of range"); if (OffsetToAlignment(Offset.getImm(), 2LL)) return Error(IDLoc, "branch to misaligned address"); break; } } // SSNOP is deprecated on MIPS32r6/MIPS64r6 // We still accept it but it is a normal nop. if (hasMips32r6() && Inst.getOpcode() == Mips::SSNOP) { std::string ISA = hasMips64r6() ? "MIPS64r6" : "MIPS32r6"; Warning(IDLoc, "ssnop is deprecated for " + ISA + " and is equivalent to a " "nop instruction"); } if (hasCnMips()) { const unsigned Opcode = Inst.getOpcode(); MCOperand Opnd; int Imm; switch (Opcode) { default: break; case Mips::BBIT0: case Mips::BBIT032: case Mips::BBIT1: case Mips::BBIT132: assert(MCID.getNumOperands() == 3 && "unexpected number of operands"); // The offset is handled above Opnd = Inst.getOperand(1); if (!Opnd.isImm()) return Error(IDLoc, "expected immediate operand kind"); Imm = Opnd.getImm(); if (Imm < 0 || Imm > (Opcode == Mips::BBIT0 || Opcode == Mips::BBIT1 ? 63 : 31)) return Error(IDLoc, "immediate operand value out of range"); if (Imm > 31) { Inst.setOpcode(Opcode == Mips::BBIT0 ? Mips::BBIT032 : Mips::BBIT132); Inst.getOperand(1).setImm(Imm - 32); } break; case Mips::SEQi: case Mips::SNEi: assert(MCID.getNumOperands() == 3 && "unexpected number of operands"); Opnd = Inst.getOperand(2); if (!Opnd.isImm()) return Error(IDLoc, "expected immediate operand kind"); Imm = Opnd.getImm(); if (!isInt<10>(Imm)) return Error(IDLoc, "immediate operand value out of range"); break; } } // This expansion is not in a function called by tryExpandInstruction() // because the pseudo-instruction doesn't have a distinct opcode. if ((Inst.getOpcode() == Mips::JAL || Inst.getOpcode() == Mips::JAL_MM) && inPicMode()) { warnIfNoMacro(IDLoc); const MCExpr *JalExpr = Inst.getOperand(0).getExpr(); // We can do this expansion if there's only 1 symbol in the argument // expression. if (countMCSymbolRefExpr(JalExpr) > 1) return Error(IDLoc, "jal doesn't support multiple symbols in PIC mode"); // FIXME: This is checking the expression can be handled by the later stages // of the assembler. We ought to leave it to those later stages. const MCSymbol *JalSym = getSingleMCSymbol(JalExpr); // FIXME: Add support for label+offset operands (currently causes an error). // FIXME: Add support for forward-declared local symbols. // FIXME: Add expansion for when the LargeGOT option is enabled. if (JalSym->isInSection() || JalSym->isTemporary()) { if (isABI_O32()) { // If it's a local symbol and the O32 ABI is being used, we expand to: // lw $25, 0($gp) // R_(MICRO)MIPS_GOT16 label // addiu $25, $25, 0 // R_(MICRO)MIPS_LO16 label // jalr $25 const MCExpr *Got16RelocExpr = MipsMCExpr::create(MipsMCExpr::MEK_GOT, JalExpr, getContext()); const MCExpr *Lo16RelocExpr = MipsMCExpr::create(MipsMCExpr::MEK_LO, JalExpr, getContext()); TOut.emitRRX(Mips::LW, Mips::T9, Mips::GP, MCOperand::createExpr(Got16RelocExpr), IDLoc, STI); TOut.emitRRX(Mips::ADDiu, Mips::T9, Mips::T9, MCOperand::createExpr(Lo16RelocExpr), IDLoc, STI); } else if (isABI_N32() || isABI_N64()) { // If it's a local symbol and the N32/N64 ABIs are being used, // we expand to: // lw/ld $25, 0($gp) // R_(MICRO)MIPS_GOT_DISP label // jalr $25 const MCExpr *GotDispRelocExpr = MipsMCExpr::create(MipsMCExpr::MEK_GOT_DISP, JalExpr, getContext()); TOut.emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9, Mips::GP, MCOperand::createExpr(GotDispRelocExpr), IDLoc, STI); } } else { // If it's an external/weak symbol, we expand to: // lw/ld $25, 0($gp) // R_(MICRO)MIPS_CALL16 label // jalr $25 const MCExpr *Call16RelocExpr = MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, JalExpr, getContext()); TOut.emitRRX(ABI.ArePtrs64bit() ? Mips::LD : Mips::LW, Mips::T9, Mips::GP, MCOperand::createExpr(Call16RelocExpr), IDLoc, STI); } MCInst JalrInst; if (IsCpRestoreSet && inMicroMipsMode()) JalrInst.setOpcode(Mips::JALRS_MM); else JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR); JalrInst.addOperand(MCOperand::createReg(Mips::RA)); JalrInst.addOperand(MCOperand::createReg(Mips::T9)); // FIXME: Add an R_(MICRO)MIPS_JALR relocation after the JALR. // This relocation is supposed to be an optimization hint for the linker // and is not necessary for correctness. Inst = JalrInst; ExpandedJalSym = true; } if (MCID.mayLoad() || MCID.mayStore()) { // Check the offset of memory operand, if it is a symbol // reference or immediate we may have to expand instructions. for (unsigned i = 0; i < MCID.getNumOperands(); i++) { const MCOperandInfo &OpInfo = MCID.OpInfo[i]; if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) || (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) { MCOperand &Op = Inst.getOperand(i); if (Op.isImm()) { int MemOffset = Op.getImm(); if (MemOffset < -32768 || MemOffset > 32767) { // Offset can't exceed 16bit value. expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad(), true); return false; } } else if (Op.isExpr()) { const MCExpr *Expr = Op.getExpr(); if (Expr->getKind() == MCExpr::SymbolRef) { const MCSymbolRefExpr *SR = static_cast<const MCSymbolRefExpr *>(Expr); if (SR->getKind() == MCSymbolRefExpr::VK_None) { // Expand symbol. expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad(), false); return false; } } else if (!isEvaluated(Expr)) { expandMemInst(Inst, IDLoc, Out, STI, MCID.mayLoad(), false); return false; } } } } // for } // if load/store if (inMicroMipsMode()) { if (MCID.mayLoad()) { // Try to create 16-bit GP relative load instruction. for (unsigned i = 0; i < MCID.getNumOperands(); i++) { const MCOperandInfo &OpInfo = MCID.OpInfo[i]; if ((OpInfo.OperandType == MCOI::OPERAND_MEMORY) || (OpInfo.OperandType == MCOI::OPERAND_UNKNOWN)) { MCOperand &Op = Inst.getOperand(i); if (Op.isImm()) { int MemOffset = Op.getImm(); MCOperand &DstReg = Inst.getOperand(0); MCOperand &BaseReg = Inst.getOperand(1); if (isInt<9>(MemOffset) && (MemOffset % 4 == 0) && getContext().getRegisterInfo()->getRegClass( Mips::GPRMM16RegClassID).contains(DstReg.getReg()) && (BaseReg.getReg() == Mips::GP || BaseReg.getReg() == Mips::GP_64)) { TOut.emitRRI(Mips::LWGP_MM, DstReg.getReg(), Mips::GP, MemOffset, IDLoc, STI); return false; } } } } // for } // if load // TODO: Handle this with the AsmOperandClass.PredicateMethod. MCOperand Opnd; int Imm; switch (Inst.getOpcode()) { default: break; case Mips::ADDIUSP_MM: Opnd = Inst.getOperand(0); if (!Opnd.isImm()) return Error(IDLoc, "expected immediate operand kind"); Imm = Opnd.getImm(); if (Imm < -1032 || Imm > 1028 || (Imm < 8 && Imm > -12) || Imm % 4 != 0) return Error(IDLoc, "immediate operand value out of range"); break; case Mips::SLL16_MM: case Mips::SRL16_MM: Opnd = Inst.getOperand(2); if (!Opnd.isImm()) return Error(IDLoc, "expected immediate operand kind"); Imm = Opnd.getImm(); if (Imm < 1 || Imm > 8) return Error(IDLoc, "immediate operand value out of range"); break; case Mips::LI16_MM: Opnd = Inst.getOperand(1); if (!Opnd.isImm()) return Error(IDLoc, "expected immediate operand kind"); Imm = Opnd.getImm(); if (Imm < -1 || Imm > 126) return Error(IDLoc, "immediate operand value out of range"); break; case Mips::ADDIUR2_MM: Opnd = Inst.getOperand(2); if (!Opnd.isImm()) return Error(IDLoc, "expected immediate operand kind"); Imm = Opnd.getImm(); if (!(Imm == 1 || Imm == -1 || ((Imm % 4 == 0) && Imm < 28 && Imm > 0))) return Error(IDLoc, "immediate operand value out of range"); break; case Mips::ANDI16_MM: Opnd = Inst.getOperand(2); if (!Opnd.isImm()) return Error(IDLoc, "expected immediate operand kind"); Imm = Opnd.getImm(); if (!(Imm == 128 || (Imm >= 1 && Imm <= 4) || Imm == 7 || Imm == 8 || Imm == 15 || Imm == 16 || Imm == 31 || Imm == 32 || Imm == 63 || Imm == 64 || Imm == 255 || Imm == 32768 || Imm == 65535)) return Error(IDLoc, "immediate operand value out of range"); break; case Mips::LBU16_MM: Opnd = Inst.getOperand(2); if (!Opnd.isImm()) return Error(IDLoc, "expected immediate operand kind"); Imm = Opnd.getImm(); if (Imm < -1 || Imm > 14) return Error(IDLoc, "immediate operand value out of range"); break; case Mips::SB16_MM: case Mips::SB16_MMR6: Opnd = Inst.getOperand(2); if (!Opnd.isImm()) return Error(IDLoc, "expected immediate operand kind"); Imm = Opnd.getImm(); if (Imm < 0 || Imm > 15) return Error(IDLoc, "immediate operand value out of range"); break; case Mips::LHU16_MM: case Mips::SH16_MM: case Mips::SH16_MMR6: Opnd = Inst.getOperand(2); if (!Opnd.isImm()) return Error(IDLoc, "expected immediate operand kind"); Imm = Opnd.getImm(); if (Imm < 0 || Imm > 30 || (Imm % 2 != 0)) return Error(IDLoc, "immediate operand value out of range"); break; case Mips::LW16_MM: case Mips::SW16_MM: case Mips::SW16_MMR6: Opnd = Inst.getOperand(2); if (!Opnd.isImm()) return Error(IDLoc, "expected immediate operand kind"); Imm = Opnd.getImm(); if (Imm < 0 || Imm > 60 || (Imm % 4 != 0)) return Error(IDLoc, "immediate operand value out of range"); break; case Mips::ADDIUPC_MM: MCOperand Opnd = Inst.getOperand(1); if (!Opnd.isImm()) return Error(IDLoc, "expected immediate operand kind"); int Imm = Opnd.getImm(); if ((Imm % 4 != 0) || !isInt<25>(Imm)) return Error(IDLoc, "immediate operand value out of range"); break; } } bool FillDelaySlot = MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder(); if (FillDelaySlot) TOut.emitDirectiveSetNoReorder(); MacroExpanderResultTy ExpandResult = tryExpandInstruction(Inst, IDLoc, Out, STI); switch (ExpandResult) { case MER_NotAMacro: Out.EmitInstruction(Inst, *STI); break; case MER_Success: break; case MER_Fail: return true; } // We know we emitted an instruction on the MER_NotAMacro or MER_Success path. // If we're in microMIPS mode then we must also set EF_MIPS_MICROMIPS. if (inMicroMipsMode()) TOut.setUsesMicroMips(); // If this instruction has a delay slot and .set reorder is active, // emit a NOP after it. if (FillDelaySlot) { TOut.emitEmptyDelaySlot(hasShortDelaySlot(Inst.getOpcode()), IDLoc, STI); TOut.emitDirectiveSetReorder(); } if ((Inst.getOpcode() == Mips::JalOneReg || Inst.getOpcode() == Mips::JalTwoReg || ExpandedJalSym) && isPicAndNotNxxAbi()) { if (IsCpRestoreSet) { // We need a NOP between the JALR and the LW: // If .set reorder has been used, we've already emitted a NOP. // If .set noreorder has been used, we need to emit a NOP at this point. if (!AssemblerOptions.back()->isReorder()) TOut.emitEmptyDelaySlot(hasShortDelaySlot(Inst.getOpcode()), IDLoc, STI); // Load the $gp from the stack. TOut.emitGPRestore(CpRestoreOffset, IDLoc, STI); } else Warning(IDLoc, "no .cprestore used in PIC mode"); } return false; } MipsAsmParser::MacroExpanderResultTy MipsAsmParser::tryExpandInstruction(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { switch (Inst.getOpcode()) { default: return MER_NotAMacro; case Mips::LoadImm32: return expandLoadImm(Inst, true, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::LoadImm64: return expandLoadImm(Inst, false, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::LoadAddrImm32: case Mips::LoadAddrImm64: assert(Inst.getOperand(0).isReg() && "expected register operand kind"); assert((Inst.getOperand(1).isImm() || Inst.getOperand(1).isExpr()) && "expected immediate operand kind"); return expandLoadAddress(Inst.getOperand(0).getReg(), Mips::NoRegister, Inst.getOperand(1), Inst.getOpcode() == Mips::LoadAddrImm32, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::LoadAddrReg32: case Mips::LoadAddrReg64: assert(Inst.getOperand(0).isReg() && "expected register operand kind"); assert(Inst.getOperand(1).isReg() && "expected register operand kind"); assert((Inst.getOperand(2).isImm() || Inst.getOperand(2).isExpr()) && "expected immediate operand kind"); return expandLoadAddress(Inst.getOperand(0).getReg(), Inst.getOperand(1).getReg(), Inst.getOperand(2), Inst.getOpcode() == Mips::LoadAddrReg32, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::B_MM_Pseudo: case Mips::B_MMR6_Pseudo: return expandUncondBranchMMPseudo(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::SWM_MM: case Mips::LWM_MM: return expandLoadStoreMultiple(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::JalOneReg: case Mips::JalTwoReg: return expandJalWithRegs(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::BneImm: case Mips::BeqImm: return expandBranchImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::BLT: case Mips::BLE: case Mips::BGE: case Mips::BGT: case Mips::BLTU: case Mips::BLEU: case Mips::BGEU: case Mips::BGTU: case Mips::BLTL: case Mips::BLEL: case Mips::BGEL: case Mips::BGTL: case Mips::BLTUL: case Mips::BLEUL: case Mips::BGEUL: case Mips::BGTUL: case Mips::BLTImmMacro: case Mips::BLEImmMacro: case Mips::BGEImmMacro: case Mips::BGTImmMacro: case Mips::BLTUImmMacro: case Mips::BLEUImmMacro: case Mips::BGEUImmMacro: case Mips::BGTUImmMacro: case Mips::BLTLImmMacro: case Mips::BLELImmMacro: case Mips::BGELImmMacro: case Mips::BGTLImmMacro: case Mips::BLTULImmMacro: case Mips::BLEULImmMacro: case Mips::BGEULImmMacro: case Mips::BGTULImmMacro: return expandCondBranches(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::SDivMacro: return expandDiv(Inst, IDLoc, Out, STI, false, true) ? MER_Fail : MER_Success; case Mips::DSDivMacro: return expandDiv(Inst, IDLoc, Out, STI, true, true) ? MER_Fail : MER_Success; case Mips::UDivMacro: return expandDiv(Inst, IDLoc, Out, STI, false, false) ? MER_Fail : MER_Success; case Mips::DUDivMacro: return expandDiv(Inst, IDLoc, Out, STI, true, false) ? MER_Fail : MER_Success; case Mips::PseudoTRUNC_W_S: return expandTrunc(Inst, false, false, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::PseudoTRUNC_W_D32: return expandTrunc(Inst, true, false, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::PseudoTRUNC_W_D: return expandTrunc(Inst, true, true, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::Ulh: return expandUlh(Inst, true, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::Ulhu: return expandUlh(Inst, false, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::Ulw: return expandUlw(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::NORImm: return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::ADDi: case Mips::ADDiu: case Mips::SLTi: case Mips::SLTiu: if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) { int64_t ImmValue = Inst.getOperand(2).getImm(); if (isInt<16>(ImmValue)) return MER_NotAMacro; return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; } return MER_NotAMacro; case Mips::ANDi: case Mips::ORi: case Mips::XORi: if ((Inst.getNumOperands() == 3) && Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm()) { int64_t ImmValue = Inst.getOperand(2).getImm(); if (isUInt<16>(ImmValue)) return MER_NotAMacro; return expandAliasImmediate(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; } return MER_NotAMacro; case Mips::ROL: case Mips::ROR: return expandRotation(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::ROLImm: case Mips::RORImm: return expandRotationImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::DROL: case Mips::DROR: return expandDRotation(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::DROLImm: case Mips::DRORImm: return expandDRotationImm(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; case Mips::ABSMacro: return expandAbs(Inst, IDLoc, Out, STI) ? MER_Fail : MER_Success; } } bool MipsAsmParser::expandJalWithRegs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); // Create a JALR instruction which is going to replace the pseudo-JAL. MCInst JalrInst; JalrInst.setLoc(IDLoc); const MCOperand FirstRegOp = Inst.getOperand(0); const unsigned Opcode = Inst.getOpcode(); if (Opcode == Mips::JalOneReg) { // jal $rs => jalr $rs if (IsCpRestoreSet && inMicroMipsMode()) { JalrInst.setOpcode(Mips::JALRS16_MM); JalrInst.addOperand(FirstRegOp); } else if (inMicroMipsMode()) { JalrInst.setOpcode(hasMips32r6() ? Mips::JALRC16_MMR6 : Mips::JALR16_MM); JalrInst.addOperand(FirstRegOp); } else { JalrInst.setOpcode(Mips::JALR); JalrInst.addOperand(MCOperand::createReg(Mips::RA)); JalrInst.addOperand(FirstRegOp); } } else if (Opcode == Mips::JalTwoReg) { // jal $rd, $rs => jalr $rd, $rs if (IsCpRestoreSet && inMicroMipsMode()) JalrInst.setOpcode(Mips::JALRS_MM); else JalrInst.setOpcode(inMicroMipsMode() ? Mips::JALR_MM : Mips::JALR); JalrInst.addOperand(FirstRegOp); const MCOperand SecondRegOp = Inst.getOperand(1); JalrInst.addOperand(SecondRegOp); } Out.EmitInstruction(JalrInst, *STI); // If .set reorder is active and branch instruction has a delay slot, // emit a NOP after it. const MCInstrDesc &MCID = getInstDesc(JalrInst.getOpcode()); if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder()) TOut.emitEmptyDelaySlot(hasShortDelaySlot(JalrInst.getOpcode()), IDLoc, STI); return false; } /// Can the value be represented by a unsigned N-bit value and a shift left? template <unsigned N> static bool isShiftedUIntAtAnyPosition(uint64_t x) { unsigned BitNum = findFirstSet(x); return (x == x >> BitNum << BitNum) && isUInt<N>(x >> BitNum); } /// Load (or add) an immediate into a register. /// /// @param ImmValue The immediate to load. /// @param DstReg The register that will hold the immediate. /// @param SrcReg A register to add to the immediate or Mips::NoRegister /// for a simple initialization. /// @param Is32BitImm Is ImmValue 32-bit or 64-bit? /// @param IsAddress True if the immediate represents an address. False if it /// is an integer. /// @param IDLoc Location of the immediate in the source file. bool MipsAsmParser::loadImmediate(int64_t ImmValue, unsigned DstReg, unsigned SrcReg, bool Is32BitImm, bool IsAddress, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); if (!Is32BitImm && !isGP64bit()) { Error(IDLoc, "instruction requires a 64-bit architecture"); return true; } if (Is32BitImm) { if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) { // Sign extend up to 64-bit so that the predicates match the hardware // behaviour. In particular, isInt<16>(0xffff8000) and similar should be // true. ImmValue = SignExtend64<32>(ImmValue); } else { Error(IDLoc, "instruction requires a 32-bit immediate"); return true; } } unsigned ZeroReg = IsAddress ? ABI.GetNullPtr() : ABI.GetZeroReg(); unsigned AdduOp = !Is32BitImm ? Mips::DADDu : Mips::ADDu; bool UseSrcReg = false; if (SrcReg != Mips::NoRegister) UseSrcReg = true; unsigned TmpReg = DstReg; if (UseSrcReg && getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) { // At this point we need AT to perform the expansions and we exit if it is // not available. unsigned ATReg = getATReg(IDLoc); if (!ATReg) return true; TmpReg = ATReg; } if (isInt<16>(ImmValue)) { if (!UseSrcReg) SrcReg = ZeroReg; // This doesn't quite follow the usual ABI expectations for N32 but matches // traditional assembler behaviour. N32 would normally use addiu for both // integers and addresses. if (IsAddress && !Is32BitImm) { TOut.emitRRI(Mips::DADDiu, DstReg, SrcReg, ImmValue, IDLoc, STI); return false; } TOut.emitRRI(Mips::ADDiu, DstReg, SrcReg, ImmValue, IDLoc, STI); return false; } if (isUInt<16>(ImmValue)) { unsigned TmpReg = DstReg; if (SrcReg == DstReg) { TmpReg = getATReg(IDLoc); if (!TmpReg) return true; } TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, ImmValue, IDLoc, STI); if (UseSrcReg) TOut.emitRRR(ABI.GetPtrAdduOp(), DstReg, TmpReg, SrcReg, IDLoc, STI); return false; } if (isInt<32>(ImmValue) || isUInt<32>(ImmValue)) { warnIfNoMacro(IDLoc); uint16_t Bits31To16 = (ImmValue >> 16) & 0xffff; uint16_t Bits15To0 = ImmValue & 0xffff; if (!Is32BitImm && !isInt<32>(ImmValue)) { // Traditional behaviour seems to special case this particular value. It's // not clear why other masks are handled differently. if (ImmValue == 0xffffffff) { TOut.emitRI(Mips::LUi, TmpReg, 0xffff, IDLoc, STI); TOut.emitRRI(Mips::DSRL32, TmpReg, TmpReg, 0, IDLoc, STI); if (UseSrcReg) TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI); return false; } // Expand to an ORi instead of a LUi to avoid sign-extending into the // upper 32 bits. TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits31To16, IDLoc, STI); TOut.emitRRI(Mips::DSLL, TmpReg, TmpReg, 16, IDLoc, STI); if (Bits15To0) TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, STI); if (UseSrcReg) TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI); return false; } TOut.emitRI(Mips::LUi, TmpReg, Bits31To16, IDLoc, STI); if (Bits15To0) TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, Bits15To0, IDLoc, STI); if (UseSrcReg) TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI); return false; } if (isShiftedUIntAtAnyPosition<16>(ImmValue)) { if (Is32BitImm) { Error(IDLoc, "instruction requires a 32-bit immediate"); return true; } // Traditionally, these immediates are shifted as little as possible and as // such we align the most significant bit to bit 15 of our temporary. unsigned FirstSet = findFirstSet((uint64_t)ImmValue); unsigned LastSet = findLastSet((uint64_t)ImmValue); unsigned ShiftAmount = FirstSet - (15 - (LastSet - FirstSet)); uint16_t Bits = (ImmValue >> ShiftAmount) & 0xffff; TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits, IDLoc, STI); TOut.emitRRI(Mips::DSLL, TmpReg, TmpReg, ShiftAmount, IDLoc, STI); if (UseSrcReg) TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI); return false; } warnIfNoMacro(IDLoc); // The remaining case is packed with a sequence of dsll and ori with zeros // being omitted and any neighbouring dsll's being coalesced. // The highest 32-bit's are equivalent to a 32-bit immediate load. // Load bits 32-63 of ImmValue into bits 0-31 of the temporary register. if (loadImmediate(ImmValue >> 32, TmpReg, Mips::NoRegister, true, false, IDLoc, Out, STI)) return false; // Shift and accumulate into the register. If a 16-bit chunk is zero, then // skip it and defer the shift to the next chunk. unsigned ShiftCarriedForwards = 16; for (int BitNum = 16; BitNum >= 0; BitNum -= 16) { uint16_t ImmChunk = (ImmValue >> BitNum) & 0xffff; if (ImmChunk != 0) { TOut.emitDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc, STI); TOut.emitRRI(Mips::ORi, TmpReg, TmpReg, ImmChunk, IDLoc, STI); ShiftCarriedForwards = 0; } ShiftCarriedForwards += 16; } ShiftCarriedForwards -= 16; // Finish any remaining shifts left by trailing zeros. if (ShiftCarriedForwards) TOut.emitDSLL(TmpReg, TmpReg, ShiftCarriedForwards, IDLoc, STI); if (UseSrcReg) TOut.emitRRR(AdduOp, DstReg, TmpReg, SrcReg, IDLoc, STI); return false; } bool MipsAsmParser::expandLoadImm(MCInst &Inst, bool Is32BitImm, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { const MCOperand &ImmOp = Inst.getOperand(1); assert(ImmOp.isImm() && "expected immediate operand kind"); const MCOperand &DstRegOp = Inst.getOperand(0); assert(DstRegOp.isReg() && "expected register operand kind"); if (loadImmediate(ImmOp.getImm(), DstRegOp.getReg(), Mips::NoRegister, Is32BitImm, false, IDLoc, Out, STI)) return true; return false; } bool MipsAsmParser::expandLoadAddress(unsigned DstReg, unsigned BaseReg, const MCOperand &Offset, bool Is32BitAddress, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { // la can't produce a usable address when addresses are 64-bit. if (Is32BitAddress && ABI.ArePtrs64bit()) { // FIXME: Demote this to a warning and continue as if we had 'dla' instead. // We currently can't do this because we depend on the equality // operator and N64 can end up with a GPR32/GPR64 mismatch. Error(IDLoc, "la used to load 64-bit address"); // Continue as if we had 'dla' instead. Is32BitAddress = false; } // dla requires 64-bit addresses. if (!Is32BitAddress && !hasMips3()) { Error(IDLoc, "instruction requires a 64-bit architecture"); return true; } if (!Offset.isImm()) return loadAndAddSymbolAddress(Offset.getExpr(), DstReg, BaseReg, Is32BitAddress, IDLoc, Out, STI); if (!ABI.ArePtrs64bit()) { // Continue as if we had 'la' whether we had 'la' or 'dla'. Is32BitAddress = true; } return loadImmediate(Offset.getImm(), DstReg, BaseReg, Is32BitAddress, true, IDLoc, Out, STI); } bool MipsAsmParser::loadAndAddSymbolAddress(const MCExpr *SymExpr, unsigned DstReg, unsigned SrcReg, bool Is32BitSym, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); bool UseSrcReg = SrcReg != Mips::NoRegister; warnIfNoMacro(IDLoc); if (inPicMode() && ABI.IsO32()) { MCValue Res; if (!SymExpr->evaluateAsRelocatable(Res, nullptr, nullptr)) { Error(IDLoc, "expected relocatable expression"); return true; } if (Res.getSymB() != nullptr) { Error(IDLoc, "expected relocatable expression with only one symbol"); return true; } // The case where the result register is $25 is somewhat special. If the // symbol in the final relocation is external and not modified with a // constant then we must use R_MIPS_CALL16 instead of R_MIPS_GOT16. if ((DstReg == Mips::T9 || DstReg == Mips::T9_64) && !UseSrcReg && Res.getConstant() == 0 && !Res.getSymA()->getSymbol().isInSection() && !Res.getSymA()->getSymbol().isTemporary()) { const MCExpr *CallExpr = MipsMCExpr::create(MipsMCExpr::MEK_GOT_CALL, SymExpr, getContext()); TOut.emitRRX(Mips::LW, DstReg, ABI.GetGlobalPtr(), MCOperand::createExpr(CallExpr), IDLoc, STI); return false; } // The remaining cases are: // External GOT: lw $tmp, %got(symbol+offset)($gp) // >addiu $tmp, $tmp, %lo(offset) // >addiu $rd, $tmp, $rs // Local GOT: lw $tmp, %got(symbol+offset)($gp) // addiu $tmp, $tmp, %lo(symbol+offset)($gp) // >addiu $rd, $tmp, $rs // The addiu's marked with a '>' may be omitted if they are redundant. If // this happens then the last instruction must use $rd as the result // register. const MipsMCExpr *GotExpr = MipsMCExpr::create(MipsMCExpr::MEK_GOT, SymExpr, getContext()); const MCExpr *LoExpr = nullptr; if (Res.getSymA()->getSymbol().isInSection() || Res.getSymA()->getSymbol().isTemporary()) LoExpr = MipsMCExpr::create(MipsMCExpr::MEK_LO, SymExpr, getContext()); else if (Res.getConstant() != 0) { // External symbols fully resolve the symbol with just the %got(symbol) // but we must still account for any offset to the symbol for expressions // like symbol+8. LoExpr = MCConstantExpr::create(Res.getConstant(), getContext()); } unsigned TmpReg = DstReg; if (UseSrcReg && getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) { // If $rs is the same as $rd, we need to use AT. // If it is not available we exit. unsigned ATReg = getATReg(IDLoc); if (!ATReg) return true; TmpReg = ATReg; } TOut.emitRRX(Mips::LW, TmpReg, ABI.GetGlobalPtr(), MCOperand::createExpr(GotExpr), IDLoc, STI); if (LoExpr) TOut.emitRRX(Mips::ADDiu, TmpReg, TmpReg, MCOperand::createExpr(LoExpr), IDLoc, STI); if (UseSrcReg) TOut.emitRRR(Mips::ADDu, DstReg, TmpReg, SrcReg, IDLoc, STI); return false; } const MipsMCExpr *HiExpr = MipsMCExpr::create(MipsMCExpr::MEK_HI, SymExpr, getContext()); const MipsMCExpr *LoExpr = MipsMCExpr::create(MipsMCExpr::MEK_LO, SymExpr, getContext()); // This is the 64-bit symbol address expansion. if (ABI.ArePtrs64bit() && isGP64bit()) { // We always need AT for the 64-bit expansion. // If it is not available we exit. unsigned ATReg = getATReg(IDLoc); if (!ATReg) return true; const MipsMCExpr *HighestExpr = MipsMCExpr::create(MipsMCExpr::MEK_HIGHEST, SymExpr, getContext()); const MipsMCExpr *HigherExpr = MipsMCExpr::create(MipsMCExpr::MEK_HIGHER, SymExpr, getContext()); if (UseSrcReg && getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) { // If $rs is the same as $rd: // (d)la $rd, sym($rd) => lui $at, %highest(sym) // daddiu $at, $at, %higher(sym) // dsll $at, $at, 16 // daddiu $at, $at, %hi(sym) // dsll $at, $at, 16 // daddiu $at, $at, %lo(sym) // daddu $rd, $at, $rd TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HighestExpr), IDLoc, STI); TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(HigherExpr), IDLoc, STI); TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI); TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(HiExpr), IDLoc, STI); TOut.emitRRI(Mips::DSLL, ATReg, ATReg, 16, IDLoc, STI); TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr), IDLoc, STI); TOut.emitRRR(Mips::DADDu, DstReg, ATReg, SrcReg, IDLoc, STI); return false; } // Otherwise, if the $rs is different from $rd or if $rs isn't specified: // (d)la $rd, sym/sym($rs) => lui $rd, %highest(sym) // lui $at, %hi(sym) // daddiu $rd, $rd, %higher(sym) // daddiu $at, $at, %lo(sym) // dsll32 $rd, $rd, 0 // daddu $rd, $rd, $at // (daddu $rd, $rd, $rs) TOut.emitRX(Mips::LUi, DstReg, MCOperand::createExpr(HighestExpr), IDLoc, STI); TOut.emitRX(Mips::LUi, ATReg, MCOperand::createExpr(HiExpr), IDLoc, STI); TOut.emitRRX(Mips::DADDiu, DstReg, DstReg, MCOperand::createExpr(HigherExpr), IDLoc, STI); TOut.emitRRX(Mips::DADDiu, ATReg, ATReg, MCOperand::createExpr(LoExpr), IDLoc, STI); TOut.emitRRI(Mips::DSLL32, DstReg, DstReg, 0, IDLoc, STI); TOut.emitRRR(Mips::DADDu, DstReg, DstReg, ATReg, IDLoc, STI); if (UseSrcReg) TOut.emitRRR(Mips::DADDu, DstReg, DstReg, SrcReg, IDLoc, STI); return false; } // And now, the 32-bit symbol address expansion: // If $rs is the same as $rd: // (d)la $rd, sym($rd) => lui $at, %hi(sym) // ori $at, $at, %lo(sym) // addu $rd, $at, $rd // Otherwise, if the $rs is different from $rd or if $rs isn't specified: // (d)la $rd, sym/sym($rs) => lui $rd, %hi(sym) // ori $rd, $rd, %lo(sym) // (addu $rd, $rd, $rs) unsigned TmpReg = DstReg; if (UseSrcReg && getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, SrcReg)) { // If $rs is the same as $rd, we need to use AT. // If it is not available we exit. unsigned ATReg = getATReg(IDLoc); if (!ATReg) return true; TmpReg = ATReg; } TOut.emitRX(Mips::LUi, TmpReg, MCOperand::createExpr(HiExpr), IDLoc, STI); TOut.emitRRX(Mips::ADDiu, TmpReg, TmpReg, MCOperand::createExpr(LoExpr), IDLoc, STI); if (UseSrcReg) TOut.emitRRR(Mips::ADDu, DstReg, TmpReg, SrcReg, IDLoc, STI); else assert( getContext().getRegisterInfo()->isSuperOrSubRegisterEq(DstReg, TmpReg)); return false; } bool MipsAsmParser::expandUncondBranchMMPseudo(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); assert(getInstDesc(Inst.getOpcode()).getNumOperands() == 1 && "unexpected number of operands"); MCOperand Offset = Inst.getOperand(0); if (Offset.isExpr()) { Inst.clear(); Inst.setOpcode(Mips::BEQ_MM); Inst.addOperand(MCOperand::createReg(Mips::ZERO)); Inst.addOperand(MCOperand::createReg(Mips::ZERO)); Inst.addOperand(MCOperand::createExpr(Offset.getExpr())); } else { assert(Offset.isImm() && "expected immediate operand kind"); if (isInt<11>(Offset.getImm())) { // If offset fits into 11 bits then this instruction becomes microMIPS // 16-bit unconditional branch instruction. if (inMicroMipsMode()) Inst.setOpcode(hasMips32r6() ? Mips::BC16_MMR6 : Mips::B16_MM); } else { if (!isInt<17>(Offset.getImm())) Error(IDLoc, "branch target out of range"); if (OffsetToAlignment(Offset.getImm(), 1LL << 1)) Error(IDLoc, "branch to misaligned address"); Inst.clear(); Inst.setOpcode(Mips::BEQ_MM); Inst.addOperand(MCOperand::createReg(Mips::ZERO)); Inst.addOperand(MCOperand::createReg(Mips::ZERO)); Inst.addOperand(MCOperand::createImm(Offset.getImm())); } } Out.EmitInstruction(Inst, *STI); // If .set reorder is active and branch instruction has a delay slot, // emit a NOP after it. const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode()); if (MCID.hasDelaySlot() && AssemblerOptions.back()->isReorder()) TOut.emitEmptyDelaySlot(true, IDLoc, STI); return false; } bool MipsAsmParser::expandBranchImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); const MCOperand &DstRegOp = Inst.getOperand(0); assert(DstRegOp.isReg() && "expected register operand kind"); const MCOperand &ImmOp = Inst.getOperand(1); assert(ImmOp.isImm() && "expected immediate operand kind"); const MCOperand &MemOffsetOp = Inst.getOperand(2); assert((MemOffsetOp.isImm() || MemOffsetOp.isExpr()) && "expected immediate or expression operand"); unsigned OpCode = 0; switch(Inst.getOpcode()) { case Mips::BneImm: OpCode = Mips::BNE; break; case Mips::BeqImm: OpCode = Mips::BEQ; break; default: llvm_unreachable("Unknown immediate branch pseudo-instruction."); break; } int64_t ImmValue = ImmOp.getImm(); if (ImmValue == 0) TOut.emitRRX(OpCode, DstRegOp.getReg(), Mips::ZERO, MemOffsetOp, IDLoc, STI); else { warnIfNoMacro(IDLoc); unsigned ATReg = getATReg(IDLoc); if (!ATReg) return true; if (loadImmediate(ImmValue, ATReg, Mips::NoRegister, !isGP64bit(), true, IDLoc, Out, STI)) return true; TOut.emitRRX(OpCode, DstRegOp.getReg(), ATReg, MemOffsetOp, IDLoc, STI); } return false; } void MipsAsmParser::expandMemInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI, bool IsLoad, bool IsImmOpnd) { if (IsLoad) { expandLoadInst(Inst, IDLoc, Out, STI, IsImmOpnd); return; } expandStoreInst(Inst, IDLoc, Out, STI, IsImmOpnd); } void MipsAsmParser::expandLoadInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI, bool IsImmOpnd) { MipsTargetStreamer &TOut = getTargetStreamer(); unsigned DstReg = Inst.getOperand(0).getReg(); unsigned BaseReg = Inst.getOperand(1).getReg(); const MCInstrDesc &Desc = getInstDesc(Inst.getOpcode()); int16_t DstRegClass = Desc.OpInfo[0].RegClass; unsigned DstRegClassID = getContext().getRegisterInfo()->getRegClass(DstRegClass).getID(); bool IsGPR = (DstRegClassID == Mips::GPR32RegClassID) || (DstRegClassID == Mips::GPR64RegClassID); if (IsImmOpnd) { // Try to use DstReg as the temporary. if (IsGPR && (BaseReg != DstReg)) { TOut.emitLoadWithImmOffset(Inst.getOpcode(), DstReg, BaseReg, Inst.getOperand(2).getImm(), DstReg, IDLoc, STI); return; } // At this point we need AT to perform the expansions and we exit if it is // not available. unsigned ATReg = getATReg(IDLoc); if (!ATReg) return; TOut.emitLoadWithImmOffset(Inst.getOpcode(), DstReg, BaseReg, Inst.getOperand(2).getImm(), ATReg, IDLoc, STI); return; } const MCExpr *ExprOffset = Inst.getOperand(2).getExpr(); MCOperand LoOperand = MCOperand::createExpr( MipsMCExpr::create(MipsMCExpr::MEK_LO, ExprOffset, getContext())); MCOperand HiOperand = MCOperand::createExpr( MipsMCExpr::create(MipsMCExpr::MEK_HI, ExprOffset, getContext())); // Try to use DstReg as the temporary. if (IsGPR && (BaseReg != DstReg)) { TOut.emitLoadWithSymOffset(Inst.getOpcode(), DstReg, BaseReg, HiOperand, LoOperand, DstReg, IDLoc, STI); return; } // At this point we need AT to perform the expansions and we exit if it is // not available. unsigned ATReg = getATReg(IDLoc); if (!ATReg) return; TOut.emitLoadWithSymOffset(Inst.getOpcode(), DstReg, BaseReg, HiOperand, LoOperand, ATReg, IDLoc, STI); } void MipsAsmParser::expandStoreInst(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI, bool IsImmOpnd) { MipsTargetStreamer &TOut = getTargetStreamer(); unsigned SrcReg = Inst.getOperand(0).getReg(); unsigned BaseReg = Inst.getOperand(1).getReg(); if (IsImmOpnd) { TOut.emitStoreWithImmOffset(Inst.getOpcode(), SrcReg, BaseReg, Inst.getOperand(2).getImm(), [&]() { return getATReg(IDLoc); }, IDLoc, STI); return; } unsigned ATReg = getATReg(IDLoc); if (!ATReg) return; const MCExpr *ExprOffset = Inst.getOperand(2).getExpr(); MCOperand LoOperand = MCOperand::createExpr( MipsMCExpr::create(MipsMCExpr::MEK_LO, ExprOffset, getContext())); MCOperand HiOperand = MCOperand::createExpr( MipsMCExpr::create(MipsMCExpr::MEK_HI, ExprOffset, getContext())); TOut.emitStoreWithSymOffset(Inst.getOpcode(), SrcReg, BaseReg, HiOperand, LoOperand, ATReg, IDLoc, STI); } bool MipsAsmParser::expandLoadStoreMultiple(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { unsigned OpNum = Inst.getNumOperands(); unsigned Opcode = Inst.getOpcode(); unsigned NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM32_MM : Mips::LWM32_MM; assert (Inst.getOperand(OpNum - 1).isImm() && Inst.getOperand(OpNum - 2).isReg() && Inst.getOperand(OpNum - 3).isReg() && "Invalid instruction operand."); if (OpNum < 8 && Inst.getOperand(OpNum - 1).getImm() <= 60 && Inst.getOperand(OpNum - 1).getImm() >= 0 && (Inst.getOperand(OpNum - 2).getReg() == Mips::SP || Inst.getOperand(OpNum - 2).getReg() == Mips::SP_64) && (Inst.getOperand(OpNum - 3).getReg() == Mips::RA || Inst.getOperand(OpNum - 3).getReg() == Mips::RA_64)) { // It can be implemented as SWM16 or LWM16 instruction. if (inMicroMipsMode() && hasMips32r6()) NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MMR6 : Mips::LWM16_MMR6; else NewOpcode = Opcode == Mips::SWM_MM ? Mips::SWM16_MM : Mips::LWM16_MM; } Inst.setOpcode(NewOpcode); Out.EmitInstruction(Inst, *STI); return false; } bool MipsAsmParser::expandCondBranches(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); bool EmittedNoMacroWarning = false; unsigned PseudoOpcode = Inst.getOpcode(); unsigned SrcReg = Inst.getOperand(0).getReg(); const MCOperand &TrgOp = Inst.getOperand(1); const MCExpr *OffsetExpr = Inst.getOperand(2).getExpr(); unsigned ZeroSrcOpcode, ZeroTrgOpcode; bool ReverseOrderSLT, IsUnsigned, IsLikely, AcceptsEquality; unsigned TrgReg; if (TrgOp.isReg()) TrgReg = TrgOp.getReg(); else if (TrgOp.isImm()) { warnIfNoMacro(IDLoc); EmittedNoMacroWarning = true; TrgReg = getATReg(IDLoc); if (!TrgReg) return true; switch(PseudoOpcode) { default: llvm_unreachable("unknown opcode for branch pseudo-instruction"); case Mips::BLTImmMacro: PseudoOpcode = Mips::BLT; break; case Mips::BLEImmMacro: PseudoOpcode = Mips::BLE; break; case Mips::BGEImmMacro: PseudoOpcode = Mips::BGE; break; case Mips::BGTImmMacro: PseudoOpcode = Mips::BGT; break; case Mips::BLTUImmMacro: PseudoOpcode = Mips::BLTU; break; case Mips::BLEUImmMacro: PseudoOpcode = Mips::BLEU; break; case Mips::BGEUImmMacro: PseudoOpcode = Mips::BGEU; break; case Mips::BGTUImmMacro: PseudoOpcode = Mips::BGTU; break; case Mips::BLTLImmMacro: PseudoOpcode = Mips::BLTL; break; case Mips::BLELImmMacro: PseudoOpcode = Mips::BLEL; break; case Mips::BGELImmMacro: PseudoOpcode = Mips::BGEL; break; case Mips::BGTLImmMacro: PseudoOpcode = Mips::BGTL; break; case Mips::BLTULImmMacro: PseudoOpcode = Mips::BLTUL; break; case Mips::BLEULImmMacro: PseudoOpcode = Mips::BLEUL; break; case Mips::BGEULImmMacro: PseudoOpcode = Mips::BGEUL; break; case Mips::BGTULImmMacro: PseudoOpcode = Mips::BGTUL; break; } if (loadImmediate(TrgOp.getImm(), TrgReg, Mips::NoRegister, !isGP64bit(), false, IDLoc, Out, STI)) return true; } switch (PseudoOpcode) { case Mips::BLT: case Mips::BLTU: case Mips::BLTL: case Mips::BLTUL: AcceptsEquality = false; ReverseOrderSLT = false; IsUnsigned = ((PseudoOpcode == Mips::BLTU) || (PseudoOpcode == Mips::BLTUL)); IsLikely = ((PseudoOpcode == Mips::BLTL) || (PseudoOpcode == Mips::BLTUL)); ZeroSrcOpcode = Mips::BGTZ; ZeroTrgOpcode = Mips::BLTZ; break; case Mips::BLE: case Mips::BLEU: case Mips::BLEL: case Mips::BLEUL: AcceptsEquality = true; ReverseOrderSLT = true; IsUnsigned = ((PseudoOpcode == Mips::BLEU) || (PseudoOpcode == Mips::BLEUL)); IsLikely = ((PseudoOpcode == Mips::BLEL) || (PseudoOpcode == Mips::BLEUL)); ZeroSrcOpcode = Mips::BGEZ; ZeroTrgOpcode = Mips::BLEZ; break; case Mips::BGE: case Mips::BGEU: case Mips::BGEL: case Mips::BGEUL: AcceptsEquality = true; ReverseOrderSLT = false; IsUnsigned = ((PseudoOpcode == Mips::BGEU) || (PseudoOpcode == Mips::BGEUL)); IsLikely = ((PseudoOpcode == Mips::BGEL) || (PseudoOpcode == Mips::BGEUL)); ZeroSrcOpcode = Mips::BLEZ; ZeroTrgOpcode = Mips::BGEZ; break; case Mips::BGT: case Mips::BGTU: case Mips::BGTL: case Mips::BGTUL: AcceptsEquality = false; ReverseOrderSLT = true; IsUnsigned = ((PseudoOpcode == Mips::BGTU) || (PseudoOpcode == Mips::BGTUL)); IsLikely = ((PseudoOpcode == Mips::BGTL) || (PseudoOpcode == Mips::BGTUL)); ZeroSrcOpcode = Mips::BLTZ; ZeroTrgOpcode = Mips::BGTZ; break; default: llvm_unreachable("unknown opcode for branch pseudo-instruction"); } bool IsTrgRegZero = (TrgReg == Mips::ZERO); bool IsSrcRegZero = (SrcReg == Mips::ZERO); if (IsSrcRegZero && IsTrgRegZero) { // FIXME: All of these Opcode-specific if's are needed for compatibility // with GAS' behaviour. However, they may not generate the most efficient // code in some circumstances. if (PseudoOpcode == Mips::BLT) { TOut.emitRX(Mips::BLTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc, STI); return false; } if (PseudoOpcode == Mips::BLE) { TOut.emitRX(Mips::BLEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc, STI); Warning(IDLoc, "branch is always taken"); return false; } if (PseudoOpcode == Mips::BGE) { TOut.emitRX(Mips::BGEZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc, STI); Warning(IDLoc, "branch is always taken"); return false; } if (PseudoOpcode == Mips::BGT) { TOut.emitRX(Mips::BGTZ, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc, STI); return false; } if (PseudoOpcode == Mips::BGTU) { TOut.emitRRX(Mips::BNE, Mips::ZERO, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc, STI); return false; } if (AcceptsEquality) { // If both registers are $0 and the pseudo-branch accepts equality, it // will always be taken, so we emit an unconditional branch. TOut.emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc, STI); Warning(IDLoc, "branch is always taken"); return false; } // If both registers are $0 and the pseudo-branch does not accept // equality, it will never be taken, so we don't have to emit anything. return false; } if (IsSrcRegZero || IsTrgRegZero) { if ((IsSrcRegZero && PseudoOpcode == Mips::BGTU) || (IsTrgRegZero && PseudoOpcode == Mips::BLTU)) { // If the $rs is $0 and the pseudo-branch is BGTU (0 > x) or // if the $rt is $0 and the pseudo-branch is BLTU (x < 0), // the pseudo-branch will never be taken, so we don't emit anything. // This only applies to unsigned pseudo-branches. return false; } if ((IsSrcRegZero && PseudoOpcode == Mips::BLEU) || (IsTrgRegZero && PseudoOpcode == Mips::BGEU)) { // If the $rs is $0 and the pseudo-branch is BLEU (0 <= x) or // if the $rt is $0 and the pseudo-branch is BGEU (x >= 0), // the pseudo-branch will always be taken, so we emit an unconditional // branch. // This only applies to unsigned pseudo-branches. TOut.emitRRX(Mips::BEQ, Mips::ZERO, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc, STI); Warning(IDLoc, "branch is always taken"); return false; } if (IsUnsigned) { // If the $rs is $0 and the pseudo-branch is BLTU (0 < x) or // if the $rt is $0 and the pseudo-branch is BGTU (x > 0), // the pseudo-branch will be taken only when the non-zero register is // different from 0, so we emit a BNEZ. // // If the $rs is $0 and the pseudo-branch is BGEU (0 >= x) or // if the $rt is $0 and the pseudo-branch is BLEU (x <= 0), // the pseudo-branch will be taken only when the non-zero register is // equal to 0, so we emit a BEQZ. // // Because only BLEU and BGEU branch on equality, we can use the // AcceptsEquality variable to decide when to emit the BEQZ. TOut.emitRRX(AcceptsEquality ? Mips::BEQ : Mips::BNE, IsSrcRegZero ? TrgReg : SrcReg, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc, STI); return false; } // If we have a signed pseudo-branch and one of the registers is $0, // we can use an appropriate compare-to-zero branch. We select which one // to use in the switch statement above. TOut.emitRX(IsSrcRegZero ? ZeroSrcOpcode : ZeroTrgOpcode, IsSrcRegZero ? TrgReg : SrcReg, MCOperand::createExpr(OffsetExpr), IDLoc, STI); return false; } // If neither the SrcReg nor the TrgReg are $0, we need AT to perform the // expansions. If it is not available, we return. unsigned ATRegNum = getATReg(IDLoc); if (!ATRegNum) return true; if (!EmittedNoMacroWarning) warnIfNoMacro(IDLoc); // SLT fits well with 2 of our 4 pseudo-branches: // BLT, where $rs < $rt, translates into "slt $at, $rs, $rt" and // BGT, where $rs > $rt, translates into "slt $at, $rt, $rs". // If the result of the SLT is 1, we branch, and if it's 0, we don't. // This is accomplished by using a BNEZ with the result of the SLT. // // The other 2 pseudo-branches are opposites of the above 2 (BGE with BLT // and BLE with BGT), so we change the BNEZ into a a BEQZ. // Because only BGE and BLE branch on equality, we can use the // AcceptsEquality variable to decide when to emit the BEQZ. // Note that the order of the SLT arguments doesn't change between // opposites. // // The same applies to the unsigned variants, except that SLTu is used // instead of SLT. TOut.emitRRR(IsUnsigned ? Mips::SLTu : Mips::SLT, ATRegNum, ReverseOrderSLT ? TrgReg : SrcReg, ReverseOrderSLT ? SrcReg : TrgReg, IDLoc, STI); TOut.emitRRX(IsLikely ? (AcceptsEquality ? Mips::BEQL : Mips::BNEL) : (AcceptsEquality ? Mips::BEQ : Mips::BNE), ATRegNum, Mips::ZERO, MCOperand::createExpr(OffsetExpr), IDLoc, STI); return false; } bool MipsAsmParser::expandDiv(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI, const bool IsMips64, const bool Signed) { MipsTargetStreamer &TOut = getTargetStreamer(); warnIfNoMacro(IDLoc); const MCOperand &RdRegOp = Inst.getOperand(0); assert(RdRegOp.isReg() && "expected register operand kind"); unsigned RdReg = RdRegOp.getReg(); const MCOperand &RsRegOp = Inst.getOperand(1); assert(RsRegOp.isReg() && "expected register operand kind"); unsigned RsReg = RsRegOp.getReg(); const MCOperand &RtRegOp = Inst.getOperand(2); assert(RtRegOp.isReg() && "expected register operand kind"); unsigned RtReg = RtRegOp.getReg(); unsigned DivOp; unsigned ZeroReg; if (IsMips64) { DivOp = Signed ? Mips::DSDIV : Mips::DUDIV; ZeroReg = Mips::ZERO_64; } else { DivOp = Signed ? Mips::SDIV : Mips::UDIV; ZeroReg = Mips::ZERO; } bool UseTraps = useTraps(); if (RsReg == Mips::ZERO || RsReg == Mips::ZERO_64) { if (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64) Warning(IDLoc, "dividing zero by zero"); if (IsMips64) { if (Signed && (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64)) { if (UseTraps) { TOut.emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, STI); return false; } TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI); return false; } } else { TOut.emitRR(DivOp, RsReg, RtReg, IDLoc, STI); return false; } } if (RtReg == Mips::ZERO || RtReg == Mips::ZERO_64) { Warning(IDLoc, "division by zero"); if (Signed) { if (UseTraps) { TOut.emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, STI); return false; } TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI); return false; } } // FIXME: The values for these two BranchTarget variables may be different in // micromips. These magic numbers need to be removed. unsigned BranchTargetNoTraps; unsigned BranchTarget; if (UseTraps) { BranchTarget = IsMips64 ? 12 : 8; TOut.emitRRI(Mips::TEQ, RtReg, ZeroReg, 0x7, IDLoc, STI); } else { BranchTarget = IsMips64 ? 20 : 16; BranchTargetNoTraps = 8; // Branch to the li instruction. TOut.emitRRI(Mips::BNE, RtReg, ZeroReg, BranchTargetNoTraps, IDLoc, STI); } TOut.emitRR(DivOp, RsReg, RtReg, IDLoc, STI); if (!UseTraps) TOut.emitII(Mips::BREAK, 0x7, 0, IDLoc, STI); if (!Signed) { TOut.emitR(Mips::MFLO, RdReg, IDLoc, STI); return false; } unsigned ATReg = getATReg(IDLoc); if (!ATReg) return true; TOut.emitRRI(Mips::ADDiu, ATReg, ZeroReg, -1, IDLoc, STI); if (IsMips64) { // Branch to the mflo instruction. TOut.emitRRI(Mips::BNE, RtReg, ATReg, BranchTarget, IDLoc, STI); TOut.emitRRI(Mips::ADDiu, ATReg, ZeroReg, 1, IDLoc, STI); TOut.emitRRI(Mips::DSLL32, ATReg, ATReg, 0x1f, IDLoc, STI); } else { // Branch to the mflo instruction. TOut.emitRRI(Mips::BNE, RtReg, ATReg, BranchTarget, IDLoc, STI); TOut.emitRI(Mips::LUi, ATReg, (uint16_t)0x8000, IDLoc, STI); } if (UseTraps) TOut.emitRRI(Mips::TEQ, RsReg, ATReg, 0x6, IDLoc, STI); else { // Branch to the mflo instruction. TOut.emitRRI(Mips::BNE, RsReg, ATReg, BranchTargetNoTraps, IDLoc, STI); TOut.emitRRI(Mips::SLL, ZeroReg, ZeroReg, 0, IDLoc, STI); TOut.emitII(Mips::BREAK, 0x6, 0, IDLoc, STI); } TOut.emitR(Mips::MFLO, RdReg, IDLoc, STI); return false; } bool MipsAsmParser::expandTrunc(MCInst &Inst, bool IsDouble, bool Is64FPU, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); assert(Inst.getNumOperands() == 3 && "Invalid operand count"); assert(Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg() && Inst.getOperand(2).isReg() && "Invalid instruction operand."); unsigned FirstReg = Inst.getOperand(0).getReg(); unsigned SecondReg = Inst.getOperand(1).getReg(); unsigned ThirdReg = Inst.getOperand(2).getReg(); if (hasMips1() && !hasMips2()) { unsigned ATReg = getATReg(IDLoc); if (!ATReg) return true; TOut.emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, STI); TOut.emitRR(Mips::CFC1, ThirdReg, Mips::RA, IDLoc, STI); TOut.emitNop(IDLoc, STI); TOut.emitRRI(Mips::ORi, ATReg, ThirdReg, 0x3, IDLoc, STI); TOut.emitRRI(Mips::XORi, ATReg, ATReg, 0x2, IDLoc, STI); TOut.emitRR(Mips::CTC1, Mips::RA, ATReg, IDLoc, STI); TOut.emitNop(IDLoc, STI); TOut.emitRR(IsDouble ? (Is64FPU ? Mips::CVT_W_D64 : Mips::CVT_W_D32) : Mips::CVT_W_S, FirstReg, SecondReg, IDLoc, STI); TOut.emitRR(Mips::CTC1, Mips::RA, ThirdReg, IDLoc, STI); TOut.emitNop(IDLoc, STI); return false; } TOut.emitRR(IsDouble ? (Is64FPU ? Mips::TRUNC_W_D64 : Mips::TRUNC_W_D32) : Mips::TRUNC_W_S, FirstReg, SecondReg, IDLoc, STI); return false; } bool MipsAsmParser::expandUlh(MCInst &Inst, bool Signed, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); if (hasMips32r6() || hasMips64r6()) { Error(IDLoc, "instruction not supported on mips32r6 or mips64r6"); return false; } warnIfNoMacro(IDLoc); const MCOperand &DstRegOp = Inst.getOperand(0); assert(DstRegOp.isReg() && "expected register operand kind"); const MCOperand &SrcRegOp = Inst.getOperand(1); assert(SrcRegOp.isReg() && "expected register operand kind"); const MCOperand &OffsetImmOp = Inst.getOperand(2); assert(OffsetImmOp.isImm() && "expected immediate operand kind"); unsigned DstReg = DstRegOp.getReg(); unsigned SrcReg = SrcRegOp.getReg(); int64_t OffsetValue = OffsetImmOp.getImm(); // NOTE: We always need AT for ULHU, as it is always used as the source // register for one of the LBu's. unsigned ATReg = getATReg(IDLoc); if (!ATReg) return true; // When the value of offset+1 does not fit in 16 bits, we have to load the // offset in AT, (D)ADDu the original source register (if there was one), and // then use AT as the source register for the 2 generated LBu's. bool LoadedOffsetInAT = false; if (!isInt<16>(OffsetValue + 1) || !isInt<16>(OffsetValue)) { LoadedOffsetInAT = true; if (loadImmediate(OffsetValue, ATReg, Mips::NoRegister, !ABI.ArePtrs64bit(), true, IDLoc, Out, STI)) return true; // NOTE: We do this (D)ADDu here instead of doing it in loadImmediate() // because it will make our output more similar to GAS'. For example, // generating an "ori $1, $zero, 32768" followed by an "addu $1, $1, $9", // instead of just an "ori $1, $9, 32768". // NOTE: If there is no source register specified in the ULHU, the parser // will interpret it as $0. if (SrcReg != Mips::ZERO && SrcReg != Mips::ZERO_64) TOut.emitAddu(ATReg, ATReg, SrcReg, ABI.ArePtrs64bit(), STI); } unsigned FirstLbuDstReg = LoadedOffsetInAT ? DstReg : ATReg; unsigned SecondLbuDstReg = LoadedOffsetInAT ? ATReg : DstReg; unsigned LbuSrcReg = LoadedOffsetInAT ? ATReg : SrcReg; int64_t FirstLbuOffset = 0, SecondLbuOffset = 0; if (isLittle()) { FirstLbuOffset = LoadedOffsetInAT ? 1 : (OffsetValue + 1); SecondLbuOffset = LoadedOffsetInAT ? 0 : OffsetValue; } else { FirstLbuOffset = LoadedOffsetInAT ? 0 : OffsetValue; SecondLbuOffset = LoadedOffsetInAT ? 1 : (OffsetValue + 1); } unsigned SllReg = LoadedOffsetInAT ? DstReg : ATReg; TOut.emitRRI(Signed ? Mips::LB : Mips::LBu, FirstLbuDstReg, LbuSrcReg, FirstLbuOffset, IDLoc, STI); TOut.emitRRI(Mips::LBu, SecondLbuDstReg, LbuSrcReg, SecondLbuOffset, IDLoc, STI); TOut.emitRRI(Mips::SLL, SllReg, SllReg, 8, IDLoc, STI); TOut.emitRRR(Mips::OR, DstReg, DstReg, ATReg, IDLoc, STI); return false; } bool MipsAsmParser::expandUlw(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); if (hasMips32r6() || hasMips64r6()) { Error(IDLoc, "instruction not supported on mips32r6 or mips64r6"); return false; } const MCOperand &DstRegOp = Inst.getOperand(0); assert(DstRegOp.isReg() && "expected register operand kind"); const MCOperand &SrcRegOp = Inst.getOperand(1); assert(SrcRegOp.isReg() && "expected register operand kind"); const MCOperand &OffsetImmOp = Inst.getOperand(2); assert(OffsetImmOp.isImm() && "expected immediate operand kind"); unsigned SrcReg = SrcRegOp.getReg(); int64_t OffsetValue = OffsetImmOp.getImm(); unsigned ATReg = 0; // When the value of offset+3 does not fit in 16 bits, we have to load the // offset in AT, (D)ADDu the original source register (if there was one), and // then use AT as the source register for the generated LWL and LWR. bool LoadedOffsetInAT = false; if (!isInt<16>(OffsetValue + 3) || !isInt<16>(OffsetValue)) { ATReg = getATReg(IDLoc); if (!ATReg) return true; LoadedOffsetInAT = true; warnIfNoMacro(IDLoc); if (loadImmediate(OffsetValue, ATReg, Mips::NoRegister, !ABI.ArePtrs64bit(), true, IDLoc, Out, STI)) return true; // NOTE: We do this (D)ADDu here instead of doing it in loadImmediate() // because it will make our output more similar to GAS'. For example, // generating an "ori $1, $zero, 32768" followed by an "addu $1, $1, $9", // instead of just an "ori $1, $9, 32768". // NOTE: If there is no source register specified in the ULW, the parser // will interpret it as $0. if (SrcReg != Mips::ZERO && SrcReg != Mips::ZERO_64) TOut.emitAddu(ATReg, ATReg, SrcReg, ABI.ArePtrs64bit(), STI); } unsigned FinalSrcReg = LoadedOffsetInAT ? ATReg : SrcReg; int64_t LeftLoadOffset = 0, RightLoadOffset = 0; if (isLittle()) { LeftLoadOffset = LoadedOffsetInAT ? 3 : (OffsetValue + 3); RightLoadOffset = LoadedOffsetInAT ? 0 : OffsetValue; } else { LeftLoadOffset = LoadedOffsetInAT ? 0 : OffsetValue; RightLoadOffset = LoadedOffsetInAT ? 3 : (OffsetValue + 3); } TOut.emitRRI(Mips::LWL, DstRegOp.getReg(), FinalSrcReg, LeftLoadOffset, IDLoc, STI); TOut.emitRRI(Mips::LWR, DstRegOp.getReg(), FinalSrcReg, RightLoadOffset, IDLoc, STI); return false; } bool MipsAsmParser::expandAliasImmediate(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); assert (Inst.getNumOperands() == 3 && "Invalid operand count"); assert (Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg() && Inst.getOperand(2).isImm() && "Invalid instruction operand."); unsigned ATReg = Mips::NoRegister; unsigned FinalDstReg = Mips::NoRegister; unsigned DstReg = Inst.getOperand(0).getReg(); unsigned SrcReg = Inst.getOperand(1).getReg(); int64_t ImmValue = Inst.getOperand(2).getImm(); bool Is32Bit = isInt<32>(ImmValue) || isUInt<32>(ImmValue); unsigned FinalOpcode = Inst.getOpcode(); if (DstReg == SrcReg) { ATReg = getATReg(Inst.getLoc()); if (!ATReg) return true; FinalDstReg = DstReg; DstReg = ATReg; } if (!loadImmediate(ImmValue, DstReg, Mips::NoRegister, Is32Bit, false, Inst.getLoc(), Out, STI)) { switch (FinalOpcode) { default: llvm_unreachable("unimplemented expansion"); case (Mips::ADDi): FinalOpcode = Mips::ADD; break; case (Mips::ADDiu): FinalOpcode = Mips::ADDu; break; case (Mips::ANDi): FinalOpcode = Mips::AND; break; case (Mips::NORImm): FinalOpcode = Mips::NOR; break; case (Mips::ORi): FinalOpcode = Mips::OR; break; case (Mips::SLTi): FinalOpcode = Mips::SLT; break; case (Mips::SLTiu): FinalOpcode = Mips::SLTu; break; case (Mips::XORi): FinalOpcode = Mips::XOR; break; } if (FinalDstReg == Mips::NoRegister) TOut.emitRRR(FinalOpcode, DstReg, DstReg, SrcReg, IDLoc, STI); else TOut.emitRRR(FinalOpcode, FinalDstReg, FinalDstReg, DstReg, IDLoc, STI); return false; } return true; } bool MipsAsmParser::expandRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); unsigned ATReg = Mips::NoRegister; unsigned DReg = Inst.getOperand(0).getReg(); unsigned SReg = Inst.getOperand(1).getReg(); unsigned TReg = Inst.getOperand(2).getReg(); unsigned TmpReg = DReg; unsigned FirstShift = Mips::NOP; unsigned SecondShift = Mips::NOP; if (hasMips32r2()) { if (DReg == SReg) { TmpReg = getATReg(Inst.getLoc()); if (!TmpReg) return true; } if (Inst.getOpcode() == Mips::ROL) { TOut.emitRRR(Mips::SUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), STI); TOut.emitRRR(Mips::ROTRV, DReg, SReg, TmpReg, Inst.getLoc(), STI); return false; } if (Inst.getOpcode() == Mips::ROR) { TOut.emitRRR(Mips::ROTRV, DReg, SReg, TReg, Inst.getLoc(), STI); return false; } return true; } if (hasMips32()) { switch (Inst.getOpcode()) { default: llvm_unreachable("unexpected instruction opcode"); case Mips::ROL: FirstShift = Mips::SRLV; SecondShift = Mips::SLLV; break; case Mips::ROR: FirstShift = Mips::SLLV; SecondShift = Mips::SRLV; break; } ATReg = getATReg(Inst.getLoc()); if (!ATReg) return true; TOut.emitRRR(Mips::SUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), STI); TOut.emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), STI); TOut.emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), STI); TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI); return false; } return true; } bool MipsAsmParser::expandRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); unsigned ATReg = Mips::NoRegister; unsigned DReg = Inst.getOperand(0).getReg(); unsigned SReg = Inst.getOperand(1).getReg(); int64_t ImmValue = Inst.getOperand(2).getImm(); unsigned FirstShift = Mips::NOP; unsigned SecondShift = Mips::NOP; if (hasMips32r2()) { if (Inst.getOpcode() == Mips::ROLImm) { uint64_t MaxShift = 32; uint64_t ShiftValue = ImmValue; if (ImmValue != 0) ShiftValue = MaxShift - ImmValue; TOut.emitRRI(Mips::ROTR, DReg, SReg, ShiftValue, Inst.getLoc(), STI); return false; } if (Inst.getOpcode() == Mips::RORImm) { TOut.emitRRI(Mips::ROTR, DReg, SReg, ImmValue, Inst.getLoc(), STI); return false; } return true; } if (hasMips32()) { if (ImmValue == 0) { TOut.emitRRI(Mips::SRL, DReg, SReg, 0, Inst.getLoc(), STI); return false; } switch (Inst.getOpcode()) { default: llvm_unreachable("unexpected instruction opcode"); case Mips::ROLImm: FirstShift = Mips::SLL; SecondShift = Mips::SRL; break; case Mips::RORImm: FirstShift = Mips::SRL; SecondShift = Mips::SLL; break; } ATReg = getATReg(Inst.getLoc()); if (!ATReg) return true; TOut.emitRRI(FirstShift, ATReg, SReg, ImmValue, Inst.getLoc(), STI); TOut.emitRRI(SecondShift, DReg, SReg, 32 - ImmValue, Inst.getLoc(), STI); TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI); return false; } return true; } bool MipsAsmParser::expandDRotation(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); unsigned ATReg = Mips::NoRegister; unsigned DReg = Inst.getOperand(0).getReg(); unsigned SReg = Inst.getOperand(1).getReg(); unsigned TReg = Inst.getOperand(2).getReg(); unsigned TmpReg = DReg; unsigned FirstShift = Mips::NOP; unsigned SecondShift = Mips::NOP; if (hasMips64r2()) { if (TmpReg == SReg) { TmpReg = getATReg(Inst.getLoc()); if (!TmpReg) return true; } if (Inst.getOpcode() == Mips::DROL) { TOut.emitRRR(Mips::DSUBu, TmpReg, Mips::ZERO, TReg, Inst.getLoc(), STI); TOut.emitRRR(Mips::DROTRV, DReg, SReg, TmpReg, Inst.getLoc(), STI); return false; } if (Inst.getOpcode() == Mips::DROR) { TOut.emitRRR(Mips::DROTRV, DReg, SReg, TReg, Inst.getLoc(), STI); return false; } return true; } if (hasMips64()) { switch (Inst.getOpcode()) { default: llvm_unreachable("unexpected instruction opcode"); case Mips::DROL: FirstShift = Mips::DSRLV; SecondShift = Mips::DSLLV; break; case Mips::DROR: FirstShift = Mips::DSLLV; SecondShift = Mips::DSRLV; break; } ATReg = getATReg(Inst.getLoc()); if (!ATReg) return true; TOut.emitRRR(Mips::DSUBu, ATReg, Mips::ZERO, TReg, Inst.getLoc(), STI); TOut.emitRRR(FirstShift, ATReg, SReg, ATReg, Inst.getLoc(), STI); TOut.emitRRR(SecondShift, DReg, SReg, TReg, Inst.getLoc(), STI); TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI); return false; } return true; } bool MipsAsmParser::expandDRotationImm(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); unsigned ATReg = Mips::NoRegister; unsigned DReg = Inst.getOperand(0).getReg(); unsigned SReg = Inst.getOperand(1).getReg(); int64_t ImmValue = Inst.getOperand(2).getImm() % 64; unsigned FirstShift = Mips::NOP; unsigned SecondShift = Mips::NOP; MCInst TmpInst; if (hasMips64r2()) { unsigned FinalOpcode = Mips::NOP; if (ImmValue == 0) FinalOpcode = Mips::DROTR; else if (ImmValue % 32 == 0) FinalOpcode = Mips::DROTR32; else if ((ImmValue >= 1) && (ImmValue <= 32)) { if (Inst.getOpcode() == Mips::DROLImm) FinalOpcode = Mips::DROTR32; else FinalOpcode = Mips::DROTR; } else if (ImmValue >= 33) { if (Inst.getOpcode() == Mips::DROLImm) FinalOpcode = Mips::DROTR; else FinalOpcode = Mips::DROTR32; } uint64_t ShiftValue = ImmValue % 32; if (Inst.getOpcode() == Mips::DROLImm) ShiftValue = (32 - ImmValue % 32) % 32; TOut.emitRRI(FinalOpcode, DReg, SReg, ShiftValue, Inst.getLoc(), STI); return false; } if (hasMips64()) { if (ImmValue == 0) { TOut.emitRRI(Mips::DSRL, DReg, SReg, 0, Inst.getLoc(), STI); return false; } switch (Inst.getOpcode()) { default: llvm_unreachable("unexpected instruction opcode"); case Mips::DROLImm: if ((ImmValue >= 1) && (ImmValue <= 31)) { FirstShift = Mips::DSLL; SecondShift = Mips::DSRL32; } if (ImmValue == 32) { FirstShift = Mips::DSLL32; SecondShift = Mips::DSRL32; } if ((ImmValue >= 33) && (ImmValue <= 63)) { FirstShift = Mips::DSLL32; SecondShift = Mips::DSRL; } break; case Mips::DRORImm: if ((ImmValue >= 1) && (ImmValue <= 31)) { FirstShift = Mips::DSRL; SecondShift = Mips::DSLL32; } if (ImmValue == 32) { FirstShift = Mips::DSRL32; SecondShift = Mips::DSLL32; } if ((ImmValue >= 33) && (ImmValue <= 63)) { FirstShift = Mips::DSRL32; SecondShift = Mips::DSLL; } break; } ATReg = getATReg(Inst.getLoc()); if (!ATReg) return true; TOut.emitRRI(FirstShift, ATReg, SReg, ImmValue % 32, Inst.getLoc(), STI); TOut.emitRRI(SecondShift, DReg, SReg, (32 - ImmValue % 32) % 32, Inst.getLoc(), STI); TOut.emitRRR(Mips::OR, DReg, DReg, ATReg, Inst.getLoc(), STI); return false; } return true; } bool MipsAsmParser::expandAbs(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); unsigned FirstRegOp = Inst.getOperand(0).getReg(); unsigned SecondRegOp = Inst.getOperand(1).getReg(); TOut.emitRI(Mips::BGEZ, SecondRegOp, 8, IDLoc, STI); if (FirstRegOp != SecondRegOp) TOut.emitRRR(Mips::ADDu, FirstRegOp, SecondRegOp, Mips::ZERO, IDLoc, STI); else TOut.emitEmptyDelaySlot(false, IDLoc, STI); TOut.emitRRR(Mips::SUB, FirstRegOp, Mips::ZERO, SecondRegOp, IDLoc, STI); return false; } void MipsAsmParser::createCpRestoreMemOp(bool IsLoad, int StackOffset, SMLoc IDLoc, MCStreamer &Out, const MCSubtargetInfo *STI) { MipsTargetStreamer &TOut = getTargetStreamer(); if (IsLoad) { TOut.emitLoadWithImmOffset(Mips::LW, Mips::GP, Mips::SP, StackOffset, Mips::GP, IDLoc, STI); return; } TOut.emitStoreWithImmOffset(Mips::SW, Mips::GP, Mips::SP, StackOffset, [&]() { return getATReg(IDLoc); }, IDLoc, STI); } unsigned MipsAsmParser::checkTargetMatchPredicate(MCInst &Inst) { switch (Inst.getOpcode()) { // As described by the Mips32r2 spec, the registers Rd and Rs for // jalr.hb must be different. // It also applies for registers Rt and Rs of microMIPSr6 jalrc.hb instruction // and registers Rd and Base for microMIPS lwp instruction case Mips::JALR_HB: case Mips::JALRC_HB_MMR6: case Mips::JALRC_MMR6: if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) return Match_RequiresDifferentSrcAndDst; return Match_Success; case Mips::LWP_MM: case Mips::LWP_MMR6: if (Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) return Match_RequiresDifferentSrcAndDst; return Match_Success; // As described the MIPSR6 spec, the compact branches that compare registers // must: // a) Not use the zero register. // b) Not use the same register twice. // c) rs < rt for bnec, beqc. // NB: For this case, the encoding will swap the operands as their // ordering doesn't matter. GAS performs this transformation too. // Hence, that constraint does not have to be enforced. // // The compact branches that branch iff the signed addition of two registers // would overflow must have rs >= rt. That can be handled like beqc/bnec with // operand swapping. They do not have restriction of using the zero register. case Mips::BLEZC: case Mips::BGEZC: case Mips::BGTZC: case Mips::BLTZC: case Mips::BEQZC: case Mips::BNEZC: if (Inst.getOperand(0).getReg() == Mips::ZERO) return Match_RequiresNoZeroRegister; return Match_Success; case Mips::BGEC: case Mips::BLTC: case Mips::BGEUC: case Mips::BLTUC: case Mips::BEQC: case Mips::BNEC: if (Inst.getOperand(0).getReg() == Mips::ZERO) return Match_RequiresNoZeroRegister; if (Inst.getOperand(1).getReg() == Mips::ZERO) return Match_RequiresNoZeroRegister; if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) return Match_RequiresDifferentOperands; return Match_Success; default: return Match_Success; } } static SMLoc RefineErrorLoc(const SMLoc Loc, const OperandVector &Operands, uint64_t ErrorInfo) { if (ErrorInfo != ~0ULL && ErrorInfo < Operands.size()) { SMLoc ErrorLoc = Operands[ErrorInfo]->getStartLoc(); if (ErrorLoc == SMLoc()) return Loc; return ErrorLoc; } return Loc; } bool MipsAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, OperandVector &Operands, MCStreamer &Out, uint64_t &ErrorInfo, bool MatchingInlineAsm) { MCInst Inst; unsigned MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm); switch (MatchResult) { case Match_Success: { if (processInstruction(Inst, IDLoc, Out, STI)) return true; return false; } case Match_MissingFeature: Error(IDLoc, "instruction requires a CPU feature not currently enabled"); return true; case Match_InvalidOperand: { SMLoc ErrorLoc = IDLoc; if (ErrorInfo != ~0ULL) { if (ErrorInfo >= Operands.size()) return Error(IDLoc, "too few operands for instruction"); ErrorLoc = Operands[ErrorInfo]->getStartLoc(); if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc; } return Error(ErrorLoc, "invalid operand for instruction"); } case Match_MnemonicFail: return Error(IDLoc, "invalid instruction"); case Match_RequiresDifferentSrcAndDst: return Error(IDLoc, "source and destination must be different"); case Match_RequiresDifferentOperands: return Error(IDLoc, "registers must be different"); case Match_RequiresNoZeroRegister: return Error(IDLoc, "invalid operand ($zero) for instruction"); case Match_Immz: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected '0'"); case Match_UImm1_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 1-bit unsigned immediate"); case Match_UImm2_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 2-bit unsigned immediate"); case Match_UImm2_1: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected immediate in range 1 .. 4"); case Match_UImm3_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 3-bit unsigned immediate"); case Match_UImm4_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 4-bit unsigned immediate"); case Match_SImm4_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 4-bit signed immediate"); case Match_UImm5_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 5-bit unsigned immediate"); case Match_SImm5_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 5-bit signed immediate"); case Match_UImm5_1: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected immediate in range 1 .. 32"); case Match_UImm5_32: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected immediate in range 32 .. 63"); case Match_UImm5_33: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected immediate in range 33 .. 64"); case Match_UImm5_0_Report_UImm6: // This is used on UImm5 operands that have a corresponding UImm5_32 // operand to avoid confusing the user. return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 6-bit unsigned immediate"); case Match_UImm5_Lsl2: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected both 7-bit unsigned immediate and multiple of 4"); case Match_UImmRange2_64: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected immediate in range 2 .. 64"); case Match_UImm6_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 6-bit unsigned immediate"); case Match_UImm6_Lsl2: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected both 8-bit unsigned immediate and multiple of 4"); case Match_SImm6_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 6-bit signed immediate"); case Match_UImm7_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 7-bit unsigned immediate"); case Match_UImm7_N1: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected immediate in range -1 .. 126"); case Match_SImm7_Lsl2: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected both 9-bit signed immediate and multiple of 4"); case Match_UImm8_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 8-bit unsigned immediate"); case Match_UImm10_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 10-bit unsigned immediate"); case Match_SImm10_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 10-bit signed immediate"); case Match_SImm11_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 11-bit signed immediate"); case Match_UImm16: case Match_UImm16_Relaxed: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 16-bit unsigned immediate"); case Match_SImm16: case Match_SImm16_Relaxed: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 16-bit signed immediate"); case Match_UImm20_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 20-bit unsigned immediate"); case Match_UImm26_0: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 26-bit unsigned immediate"); case Match_SImm32: case Match_SImm32_Relaxed: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected 32-bit signed immediate"); case Match_MemSImm9: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected memory with 9-bit signed offset"); case Match_MemSImm10: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected memory with 10-bit signed offset"); case Match_MemSImm10Lsl1: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected memory with 11-bit signed offset and multiple of 2"); case Match_MemSImm10Lsl2: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected memory with 12-bit signed offset and multiple of 4"); case Match_MemSImm10Lsl3: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected memory with 13-bit signed offset and multiple of 8"); case Match_MemSImm11: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected memory with 11-bit signed offset"); case Match_MemSImm12: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected memory with 12-bit signed offset"); case Match_MemSImm16: return Error(RefineErrorLoc(IDLoc, Operands, ErrorInfo), "expected memory with 16-bit signed offset"); } llvm_unreachable("Implement any new match types added!"); } void MipsAsmParser::warnIfRegIndexIsAT(unsigned RegIndex, SMLoc Loc) { if (RegIndex != 0 && AssemblerOptions.back()->getATRegIndex() == RegIndex) Warning(Loc, "used $at (currently $" + Twine(RegIndex) + ") without \".set noat\""); } void MipsAsmParser::warnIfNoMacro(SMLoc Loc) { if (!AssemblerOptions.back()->isMacro()) Warning(Loc, "macro instruction expanded into multiple instructions"); } void MipsAsmParser::printWarningWithFixIt(const Twine &Msg, const Twine &FixMsg, SMRange Range, bool ShowColors) { getSourceManager().PrintMessage(Range.Start, SourceMgr::DK_Warning, Msg, Range, SMFixIt(Range, FixMsg), ShowColors); } int MipsAsmParser::matchCPURegisterName(StringRef Name) { int CC; CC = StringSwitch<unsigned>(Name) .Case("zero", 0) .Case("at", 1) .Case("a0", 4) .Case("a1", 5) .Case("a2", 6) .Case("a3", 7) .Case("v0", 2) .Case("v1", 3) .Case("s0", 16) .Case("s1", 17) .Case("s2", 18) .Case("s3", 19) .Case("s4", 20) .Case("s5", 21) .Case("s6", 22) .Case("s7", 23) .Case("k0", 26) .Case("k1", 27) .Case("gp", 28) .Case("sp", 29) .Case("fp", 30) .Case("s8", 30) .Case("ra", 31) .Case("t0", 8) .Case("t1", 9) .Case("t2", 10) .Case("t3", 11) .Case("t4", 12) .Case("t5", 13) .Case("t6", 14) .Case("t7", 15) .Case("t8", 24) .Case("t9", 25) .Default(-1); if (!(isABI_N32() || isABI_N64())) return CC; if (12 <= CC && CC <= 15) { // Name is one of t4-t7 AsmToken RegTok = getLexer().peekTok(); SMRange RegRange = RegTok.getLocRange(); StringRef FixedName = StringSwitch<StringRef>(Name) .Case("t4", "t0") .Case("t5", "t1") .Case("t6", "t2") .Case("t7", "t3") .Default(""); assert(FixedName != "" && "Register name is not one of t4-t7."); printWarningWithFixIt("register names $t4-$t7 are only available in O32.", "Did you mean $" + FixedName + "?", RegRange); } // Although SGI documentation just cuts out t0-t3 for n32/n64, // GNU pushes the values of t0-t3 to override the o32/o64 values for t4-t7 // We are supporting both cases, so for t0-t3 we'll just push them to t4-t7. if (8 <= CC && CC <= 11) CC += 4; if (CC == -1) CC = StringSwitch<unsigned>(Name) .Case("a4", 8) .Case("a5", 9) .Case("a6", 10) .Case("a7", 11) .Case("kt0", 26) .Case("kt1", 27) .Default(-1); return CC; } int MipsAsmParser::matchHWRegsRegisterName(StringRef Name) { int CC; CC = StringSwitch<unsigned>(Name) .Case("hwr_cpunum", 0) .Case("hwr_synci_step", 1) .Case("hwr_cc", 2) .Case("hwr_ccres", 3) .Case("hwr_ulr", 29) .Default(-1); return CC; } int MipsAsmParser::matchFPURegisterName(StringRef Name) { if (Name[0] == 'f') { StringRef NumString = Name.substr(1); unsigned IntVal; if (NumString.getAsInteger(10, IntVal)) return -1; // This is not an integer. if (IntVal > 31) // Maximum index for fpu register. return -1; return IntVal; } return -1; } int MipsAsmParser::matchFCCRegisterName(StringRef Name) { if (Name.startswith("fcc")) { StringRef NumString = Name.substr(3); unsigned IntVal; if (NumString.getAsInteger(10, IntVal)) return -1; // This is not an integer. if (IntVal > 7) // There are only 8 fcc registers. return -1; return IntVal; } return -1; } int MipsAsmParser::matchACRegisterName(StringRef Name) { if (Name.startswith("ac")) { StringRef NumString = Name.substr(2); unsigned IntVal; if (NumString.getAsInteger(10, IntVal)) return -1; // This is not an integer. if (IntVal > 3) // There are only 3 acc registers. return -1; return IntVal; } return -1; } int MipsAsmParser::matchMSA128RegisterName(StringRef Name) { unsigned IntVal; if (Name.front() != 'w' || Name.drop_front(1).getAsInteger(10, IntVal)) return -1; if (IntVal > 31) return -1; return IntVal; } int MipsAsmParser::matchMSA128CtrlRegisterName(StringRef Name) { int CC; CC = StringSwitch<unsigned>(Name) .Case("msair", 0) .Case("msacsr", 1) .Case("msaaccess", 2) .Case("msasave", 3) .Case("msamodify", 4) .Case("msarequest", 5) .Case("msamap", 6) .Case("msaunmap", 7) .Default(-1); return CC; } unsigned MipsAsmParser::getATReg(SMLoc Loc) { unsigned ATIndex = AssemblerOptions.back()->getATRegIndex(); if (ATIndex == 0) { reportParseError(Loc, "pseudo-instruction requires $at, which is not available"); return 0; } unsigned AT = getReg( (isGP64bit()) ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, ATIndex); return AT; } unsigned MipsAsmParser::getReg(int RC, int RegNo) { return *(getContext().getRegisterInfo()->getRegClass(RC).begin() + RegNo); } unsigned MipsAsmParser::getGPR(int RegNo) { return getReg(isGP64bit() ? Mips::GPR64RegClassID : Mips::GPR32RegClassID, RegNo); } int MipsAsmParser::matchRegisterByNumber(unsigned RegNum, unsigned RegClass) { if (RegNum > getContext().getRegisterInfo()->getRegClass(RegClass).getNumRegs() - 1) return -1; return getReg(RegClass, RegNum); } bool MipsAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) { MCAsmParser &Parser = getParser(); DEBUG(dbgs() << "parseOperand\n"); // Check if the current operand has a custom associated parser, if so, try to // custom parse the operand, or fallback to the general approach. OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic); if (ResTy == MatchOperand_Success) return false; // If there wasn't a custom match, try the generic matcher below. Otherwise, // there was a match, but an error occurred, in which case, just return that // the operand parsing failed. if (ResTy == MatchOperand_ParseFail) return true; DEBUG(dbgs() << ".. Generic Parser\n"); switch (getLexer().getKind()) { default: Error(Parser.getTok().getLoc(), "unexpected token in operand"); return true; case AsmToken::Dollar: { // Parse the register. SMLoc S = Parser.getTok().getLoc(); // Almost all registers have been parsed by custom parsers. There is only // one exception to this. $zero (and it's alias $0) will reach this point // for div, divu, and similar instructions because it is not an operand // to the instruction definition but an explicit register. Special case // this situation for now. if (parseAnyRegister(Operands) != MatchOperand_NoMatch) return false; // Maybe it is a symbol reference. StringRef Identifier; if (Parser.parseIdentifier(Identifier)) return true; SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); MCSymbol *Sym = getContext().getOrCreateSymbol("$" + Identifier); // Otherwise create a symbol reference. const MCExpr *Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext()); Operands.push_back(MipsOperand::CreateImm(Res, S, E, *this)); return false; } // Else drop to expression parsing. case AsmToken::LParen: case AsmToken::Minus: case AsmToken::Plus: case AsmToken::Integer: case AsmToken::Tilde: case AsmToken::String: { DEBUG(dbgs() << ".. generic integer\n"); OperandMatchResultTy ResTy = parseImm(Operands); return ResTy != MatchOperand_Success; } case AsmToken::Percent: { // It is a symbol reference or constant expression. const MCExpr *IdVal; SMLoc S = Parser.getTok().getLoc(); // Start location of the operand. if (parseRelocOperand(IdVal)) return true; SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this)); return false; } // case AsmToken::Percent } // switch(getLexer().getKind()) return true; } const MCExpr *MipsAsmParser::evaluateRelocExpr(const MCExpr *Expr, StringRef RelocStr) { if (RelocStr == "hi(%neg(%gp_rel") return MipsMCExpr::createGpOff(MipsMCExpr::MEK_HI, Expr, getContext()); else if (RelocStr == "lo(%neg(%gp_rel") return MipsMCExpr::createGpOff(MipsMCExpr::MEK_LO, Expr, getContext()); MipsMCExpr::MipsExprKind Kind = StringSwitch<MipsMCExpr::MipsExprKind>(RelocStr) .Case("call16", MipsMCExpr::MEK_GOT_CALL) .Case("call_hi", MipsMCExpr::MEK_CALL_HI16) .Case("call_lo", MipsMCExpr::MEK_CALL_LO16) .Case("dtprel_hi", MipsMCExpr::MEK_DTPREL_HI) .Case("dtprel_lo", MipsMCExpr::MEK_DTPREL_LO) .Case("got", MipsMCExpr::MEK_GOT) .Case("got_disp", MipsMCExpr::MEK_GOT_DISP) .Case("got_hi", MipsMCExpr::MEK_GOT_HI16) .Case("got_lo", MipsMCExpr::MEK_GOT_LO16) .Case("got_ofst", MipsMCExpr::MEK_GOT_OFST) .Case("got_page", MipsMCExpr::MEK_GOT_PAGE) .Case("gottprel", MipsMCExpr::MEK_GOTTPREL) .Case("gp_rel", MipsMCExpr::MEK_GPREL) .Case("hi", MipsMCExpr::MEK_HI) .Case("higher", MipsMCExpr::MEK_HIGHER) .Case("highest", MipsMCExpr::MEK_HIGHEST) .Case("lo", MipsMCExpr::MEK_LO) .Case("neg", MipsMCExpr::MEK_NEG) .Case("pcrel_hi", MipsMCExpr::MEK_PCREL_HI16) .Case("pcrel_lo", MipsMCExpr::MEK_PCREL_LO16) .Case("tlsgd", MipsMCExpr::MEK_TLSGD) .Case("tlsldm", MipsMCExpr::MEK_TLSLDM) .Case("tprel_hi", MipsMCExpr::MEK_TPREL_HI) .Case("tprel_lo", MipsMCExpr::MEK_TPREL_LO) .Default(MipsMCExpr::MEK_None); assert(Kind != MipsMCExpr::MEK_None); return MipsMCExpr::create(Kind, Expr, getContext()); } bool MipsAsmParser::isEvaluated(const MCExpr *Expr) { switch (Expr->getKind()) { case MCExpr::Constant: return true; case MCExpr::SymbolRef: return (cast<MCSymbolRefExpr>(Expr)->getKind() != MCSymbolRefExpr::VK_None); case MCExpr::Binary: if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) { if (!isEvaluated(BE->getLHS())) return false; return isEvaluated(BE->getRHS()); } case MCExpr::Unary: return isEvaluated(cast<MCUnaryExpr>(Expr)->getSubExpr()); case MCExpr::Target: return true; } return false; } bool MipsAsmParser::parseRelocOperand(const MCExpr *&Res) { MCAsmParser &Parser = getParser(); Parser.Lex(); // Eat the % token. const AsmToken &Tok = Parser.getTok(); // Get next token, operation. if (Tok.isNot(AsmToken::Identifier)) return true; std::string Str = Tok.getIdentifier(); Parser.Lex(); // Eat the identifier. // Now make an expression from the rest of the operand. const MCExpr *IdVal; SMLoc EndLoc; if (getLexer().getKind() == AsmToken::LParen) { while (1) { Parser.Lex(); // Eat the '(' token. if (getLexer().getKind() == AsmToken::Percent) { Parser.Lex(); // Eat the % token. const AsmToken &nextTok = Parser.getTok(); if (nextTok.isNot(AsmToken::Identifier)) return true; Str += "(%"; Str += nextTok.getIdentifier(); Parser.Lex(); // Eat the identifier. if (getLexer().getKind() != AsmToken::LParen) return true; } else break; } if (getParser().parseParenExpression(IdVal, EndLoc)) return true; while (getLexer().getKind() == AsmToken::RParen) Parser.Lex(); // Eat the ')' token. } else return true; // Parenthesis must follow the relocation operand. Res = evaluateRelocExpr(IdVal, Str); return false; } bool MipsAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) { SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands; OperandMatchResultTy ResTy = parseAnyRegister(Operands); if (ResTy == MatchOperand_Success) { assert(Operands.size() == 1); MipsOperand &Operand = static_cast<MipsOperand &>(*Operands.front()); StartLoc = Operand.getStartLoc(); EndLoc = Operand.getEndLoc(); // AFAIK, we only support numeric registers and named GPR's in CFI // directives. // Don't worry about eating tokens before failing. Using an unrecognised // register is a parse error. if (Operand.isGPRAsmReg()) { // Resolve to GPR32 or GPR64 appropriately. RegNo = isGP64bit() ? Operand.getGPR64Reg() : Operand.getGPR32Reg(); } return (RegNo == (unsigned)-1); } assert(Operands.size() == 0); return (RegNo == (unsigned)-1); } bool MipsAsmParser::parseMemOffset(const MCExpr *&Res, bool isParenExpr) { MCAsmParser &Parser = getParser(); SMLoc S; bool Result = true; unsigned NumOfLParen = 0; while (getLexer().getKind() == AsmToken::LParen) { Parser.Lex(); ++NumOfLParen; } switch (getLexer().getKind()) { default: return true; case AsmToken::Identifier: case AsmToken::LParen: case AsmToken::Integer: case AsmToken::Minus: case AsmToken::Plus: if (isParenExpr) Result = getParser().parseParenExprOfDepth(NumOfLParen, Res, S); else Result = (getParser().parseExpression(Res)); while (getLexer().getKind() == AsmToken::RParen) Parser.Lex(); break; case AsmToken::Percent: Result = parseRelocOperand(Res); } return Result; } MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMemOperand(OperandVector &Operands) { MCAsmParser &Parser = getParser(); DEBUG(dbgs() << "parseMemOperand\n"); const MCExpr *IdVal = nullptr; SMLoc S; bool isParenExpr = false; MipsAsmParser::OperandMatchResultTy Res = MatchOperand_NoMatch; // First operand is the offset. S = Parser.getTok().getLoc(); if (getLexer().getKind() == AsmToken::LParen) { Parser.Lex(); isParenExpr = true; } if (getLexer().getKind() != AsmToken::Dollar) { if (parseMemOffset(IdVal, isParenExpr)) return MatchOperand_ParseFail; const AsmToken &Tok = Parser.getTok(); // Get the next token. if (Tok.isNot(AsmToken::LParen)) { MipsOperand &Mnemonic = static_cast<MipsOperand &>(*Operands[0]); if (Mnemonic.getToken() == "la" || Mnemonic.getToken() == "dla") { SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this)); return MatchOperand_Success; } if (Tok.is(AsmToken::EndOfStatement)) { SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); // Zero register assumed, add a memory operand with ZERO as its base. // "Base" will be managed by k_Memory. auto Base = MipsOperand::createGPRReg(0, getContext().getRegisterInfo(), S, E, *this); Operands.push_back( MipsOperand::CreateMem(std::move(Base), IdVal, S, E, *this)); return MatchOperand_Success; } Error(Parser.getTok().getLoc(), "'(' expected"); return MatchOperand_ParseFail; } Parser.Lex(); // Eat the '(' token. } Res = parseAnyRegister(Operands); if (Res != MatchOperand_Success) return Res; if (Parser.getTok().isNot(AsmToken::RParen)) { Error(Parser.getTok().getLoc(), "')' expected"); return MatchOperand_ParseFail; } SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); Parser.Lex(); // Eat the ')' token. if (!IdVal) IdVal = MCConstantExpr::create(0, getContext()); // Replace the register operand with the memory operand. std::unique_ptr<MipsOperand> op( static_cast<MipsOperand *>(Operands.back().release())); // Remove the register from the operands. // "op" will be managed by k_Memory. Operands.pop_back(); // Add the memory operand. if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(IdVal)) { int64_t Imm; if (IdVal->evaluateAsAbsolute(Imm)) IdVal = MCConstantExpr::create(Imm, getContext()); else if (BE->getLHS()->getKind() != MCExpr::SymbolRef) IdVal = MCBinaryExpr::create(BE->getOpcode(), BE->getRHS(), BE->getLHS(), getContext()); } Operands.push_back(MipsOperand::CreateMem(std::move(op), IdVal, S, E, *this)); return MatchOperand_Success; } bool MipsAsmParser::searchSymbolAlias(OperandVector &Operands) { MCAsmParser &Parser = getParser(); MCSymbol *Sym = getContext().lookupSymbol(Parser.getTok().getIdentifier()); if (Sym) { SMLoc S = Parser.getTok().getLoc(); const MCExpr *Expr; if (Sym->isVariable()) Expr = Sym->getVariableValue(); else return false; if (Expr->getKind() == MCExpr::SymbolRef) { const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr); StringRef DefSymbol = Ref->getSymbol().getName(); if (DefSymbol.startswith("$")) { OperandMatchResultTy ResTy = matchAnyRegisterNameWithoutDollar(Operands, DefSymbol.substr(1), S); if (ResTy == MatchOperand_Success) { Parser.Lex(); return true; } else if (ResTy == MatchOperand_ParseFail) llvm_unreachable("Should never ParseFail"); return false; } } else if (Expr->getKind() == MCExpr::Constant) { Parser.Lex(); const MCConstantExpr *Const = static_cast<const MCConstantExpr *>(Expr); Operands.push_back( MipsOperand::CreateImm(Const, S, Parser.getTok().getLoc(), *this)); return true; } } return false; } MipsAsmParser::OperandMatchResultTy MipsAsmParser::matchAnyRegisterNameWithoutDollar(OperandVector &Operands, StringRef Identifier, SMLoc S) { int Index = matchCPURegisterName(Identifier); if (Index != -1) { Operands.push_back(MipsOperand::createGPRReg( Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this)); return MatchOperand_Success; } Index = matchHWRegsRegisterName(Identifier); if (Index != -1) { Operands.push_back(MipsOperand::createHWRegsReg( Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this)); return MatchOperand_Success; } Index = matchFPURegisterName(Identifier); if (Index != -1) { Operands.push_back(MipsOperand::createFGRReg( Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this)); return MatchOperand_Success; } Index = matchFCCRegisterName(Identifier); if (Index != -1) { Operands.push_back(MipsOperand::createFCCReg( Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this)); return MatchOperand_Success; } Index = matchACRegisterName(Identifier); if (Index != -1) { Operands.push_back(MipsOperand::createACCReg( Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this)); return MatchOperand_Success; } Index = matchMSA128RegisterName(Identifier); if (Index != -1) { Operands.push_back(MipsOperand::createMSA128Reg( Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this)); return MatchOperand_Success; } Index = matchMSA128CtrlRegisterName(Identifier); if (Index != -1) { Operands.push_back(MipsOperand::createMSACtrlReg( Index, getContext().getRegisterInfo(), S, getLexer().getLoc(), *this)); return MatchOperand_Success; } return MatchOperand_NoMatch; } MipsAsmParser::OperandMatchResultTy MipsAsmParser::matchAnyRegisterWithoutDollar(OperandVector &Operands, SMLoc S) { MCAsmParser &Parser = getParser(); auto Token = Parser.getLexer().peekTok(false); if (Token.is(AsmToken::Identifier)) { DEBUG(dbgs() << ".. identifier\n"); StringRef Identifier = Token.getIdentifier(); OperandMatchResultTy ResTy = matchAnyRegisterNameWithoutDollar(Operands, Identifier, S); return ResTy; } else if (Token.is(AsmToken::Integer)) { DEBUG(dbgs() << ".. integer\n"); Operands.push_back(MipsOperand::createNumericReg( Token.getIntVal(), getContext().getRegisterInfo(), S, Token.getLoc(), *this)); return MatchOperand_Success; } DEBUG(dbgs() << Parser.getTok().getKind() << "\n"); return MatchOperand_NoMatch; } MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseAnyRegister(OperandVector &Operands) { MCAsmParser &Parser = getParser(); DEBUG(dbgs() << "parseAnyRegister\n"); auto Token = Parser.getTok(); SMLoc S = Token.getLoc(); if (Token.isNot(AsmToken::Dollar)) { DEBUG(dbgs() << ".. !$ -> try sym aliasing\n"); if (Token.is(AsmToken::Identifier)) { if (searchSymbolAlias(Operands)) return MatchOperand_Success; } DEBUG(dbgs() << ".. !symalias -> NoMatch\n"); return MatchOperand_NoMatch; } DEBUG(dbgs() << ".. $\n"); OperandMatchResultTy ResTy = matchAnyRegisterWithoutDollar(Operands, S); if (ResTy == MatchOperand_Success) { Parser.Lex(); // $ Parser.Lex(); // identifier } return ResTy; } MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseImm(OperandVector &Operands) { MCAsmParser &Parser = getParser(); switch (getLexer().getKind()) { default: return MatchOperand_NoMatch; case AsmToken::LParen: case AsmToken::Minus: case AsmToken::Plus: case AsmToken::Integer: case AsmToken::Tilde: case AsmToken::String: break; } const MCExpr *IdVal; SMLoc S = Parser.getTok().getLoc(); if (getParser().parseExpression(IdVal)) return MatchOperand_ParseFail; SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); Operands.push_back(MipsOperand::CreateImm(IdVal, S, E, *this)); return MatchOperand_Success; } MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseJumpTarget(OperandVector &Operands) { MCAsmParser &Parser = getParser(); DEBUG(dbgs() << "parseJumpTarget\n"); SMLoc S = getLexer().getLoc(); // Integers and expressions are acceptable OperandMatchResultTy ResTy = parseImm(Operands); if (ResTy != MatchOperand_NoMatch) return ResTy; // Registers are a valid target and have priority over symbols. ResTy = parseAnyRegister(Operands); if (ResTy != MatchOperand_NoMatch) return ResTy; const MCExpr *Expr = nullptr; if (Parser.parseExpression(Expr)) { // We have no way of knowing if a symbol was consumed so we must ParseFail return MatchOperand_ParseFail; } Operands.push_back( MipsOperand::CreateImm(Expr, S, getLexer().getLoc(), *this)); return MatchOperand_Success; } MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseInvNum(OperandVector &Operands) { MCAsmParser &Parser = getParser(); const MCExpr *IdVal; // If the first token is '$' we may have register operand. if (Parser.getTok().is(AsmToken::Dollar)) return MatchOperand_NoMatch; SMLoc S = Parser.getTok().getLoc(); if (getParser().parseExpression(IdVal)) return MatchOperand_ParseFail; const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(IdVal); assert(MCE && "Unexpected MCExpr type."); int64_t Val = MCE->getValue(); SMLoc E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1); Operands.push_back(MipsOperand::CreateImm( MCConstantExpr::create(0 - Val, getContext()), S, E, *this)); return MatchOperand_Success; } MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseLSAImm(OperandVector &Operands) { MCAsmParser &Parser = getParser(); switch (getLexer().getKind()) { default: return MatchOperand_NoMatch; case AsmToken::LParen: case AsmToken::Plus: case AsmToken::Minus: case AsmToken::Integer: break; } const MCExpr *Expr; SMLoc S = Parser.getTok().getLoc(); if (getParser().parseExpression(Expr)) return MatchOperand_ParseFail; int64_t Val; if (!Expr->evaluateAsAbsolute(Val)) { Error(S, "expected immediate value"); return MatchOperand_ParseFail; } // The LSA instruction allows a 2-bit unsigned immediate. For this reason // and because the CPU always adds one to the immediate field, the allowed // range becomes 1..4. We'll only check the range here and will deal // with the addition/subtraction when actually decoding/encoding // the instruction. if (Val < 1 || Val > 4) { Error(S, "immediate not in range (1..4)"); return MatchOperand_ParseFail; } Operands.push_back( MipsOperand::CreateImm(Expr, S, Parser.getTok().getLoc(), *this)); return MatchOperand_Success; } MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseRegisterList(OperandVector &Operands) { MCAsmParser &Parser = getParser(); SmallVector<unsigned, 10> Regs; unsigned RegNo; unsigned PrevReg = Mips::NoRegister; bool RegRange = false; SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands; if (Parser.getTok().isNot(AsmToken::Dollar)) return MatchOperand_ParseFail; SMLoc S = Parser.getTok().getLoc(); while (parseAnyRegister(TmpOperands) == MatchOperand_Success) { SMLoc E = getLexer().getLoc(); MipsOperand &Reg = static_cast<MipsOperand &>(*TmpOperands.back()); RegNo = isGP64bit() ? Reg.getGPR64Reg() : Reg.getGPR32Reg(); if (RegRange) { // Remove last register operand because registers from register range // should be inserted first. if ((isGP64bit() && RegNo == Mips::RA_64) || (!isGP64bit() && RegNo == Mips::RA)) { Regs.push_back(RegNo); } else { unsigned TmpReg = PrevReg + 1; while (TmpReg <= RegNo) { if ((((TmpReg < Mips::S0) || (TmpReg > Mips::S7)) && !isGP64bit()) || (((TmpReg < Mips::S0_64) || (TmpReg > Mips::S7_64)) && isGP64bit())) { Error(E, "invalid register operand"); return MatchOperand_ParseFail; } PrevReg = TmpReg; Regs.push_back(TmpReg++); } } RegRange = false; } else { if ((PrevReg == Mips::NoRegister) && ((isGP64bit() && (RegNo != Mips::S0_64) && (RegNo != Mips::RA_64)) || (!isGP64bit() && (RegNo != Mips::S0) && (RegNo != Mips::RA)))) { Error(E, "$16 or $31 expected"); return MatchOperand_ParseFail; } else if (!(((RegNo == Mips::FP || RegNo == Mips::RA || (RegNo >= Mips::S0 && RegNo <= Mips::S7)) && !isGP64bit()) || ((RegNo == Mips::FP_64 || RegNo == Mips::RA_64 || (RegNo >= Mips::S0_64 && RegNo <= Mips::S7_64)) && isGP64bit()))) { Error(E, "invalid register operand"); return MatchOperand_ParseFail; } else if ((PrevReg != Mips::NoRegister) && (RegNo != PrevReg + 1) && ((RegNo != Mips::FP && RegNo != Mips::RA && !isGP64bit()) || (RegNo != Mips::FP_64 && RegNo != Mips::RA_64 && isGP64bit()))) { Error(E, "consecutive register numbers expected"); return MatchOperand_ParseFail; } Regs.push_back(RegNo); } if (Parser.getTok().is(AsmToken::Minus)) RegRange = true; if (!Parser.getTok().isNot(AsmToken::Minus) && !Parser.getTok().isNot(AsmToken::Comma)) { Error(E, "',' or '-' expected"); return MatchOperand_ParseFail; } Lex(); // Consume comma or minus if (Parser.getTok().isNot(AsmToken::Dollar)) break; PrevReg = RegNo; } SMLoc E = Parser.getTok().getLoc(); Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this)); parseMemOperand(Operands); return MatchOperand_Success; } MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseRegisterPair(OperandVector &Operands) { MCAsmParser &Parser = getParser(); SMLoc S = Parser.getTok().getLoc(); if (parseAnyRegister(Operands) != MatchOperand_Success) return MatchOperand_ParseFail; SMLoc E = Parser.getTok().getLoc(); MipsOperand Op = static_cast<MipsOperand &>(*Operands.back()); Operands.pop_back(); Operands.push_back(MipsOperand::CreateRegPair(Op, S, E, *this)); return MatchOperand_Success; } MipsAsmParser::OperandMatchResultTy MipsAsmParser::parseMovePRegPair(OperandVector &Operands) { MCAsmParser &Parser = getParser(); SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> TmpOperands; SmallVector<unsigned, 10> Regs; if (Parser.getTok().isNot(AsmToken::Dollar)) return MatchOperand_ParseFail; SMLoc S = Parser.getTok().getLoc(); if (parseAnyRegister(TmpOperands) != MatchOperand_Success) return MatchOperand_ParseFail; MipsOperand *Reg = &static_cast<MipsOperand &>(*TmpOperands.back()); unsigned RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg(); Regs.push_back(RegNo); SMLoc E = Parser.getTok().getLoc(); if (Parser.getTok().isNot(AsmToken::Comma)) { Error(E, "',' expected"); return MatchOperand_ParseFail; } // Remove comma. Parser.Lex(); if (parseAnyRegister(TmpOperands) != MatchOperand_Success) return MatchOperand_ParseFail; Reg = &static_cast<MipsOperand &>(*TmpOperands.back()); RegNo = isGP64bit() ? Reg->getGPR64Reg() : Reg->getGPR32Reg(); Regs.push_back(RegNo); Operands.push_back(MipsOperand::CreateRegList(Regs, S, E, *this)); return MatchOperand_Success; } /// Sometimes (i.e. load/stores) the operand may be followed immediately by /// either this. /// ::= '(', register, ')' /// handle it before we iterate so we don't get tripped up by the lack of /// a comma. bool MipsAsmParser::parseParenSuffix(StringRef Name, OperandVector &Operands) { MCAsmParser &Parser = getParser(); if (getLexer().is(AsmToken::LParen)) { Operands.push_back( MipsOperand::CreateToken("(", getLexer().getLoc(), *this)); Parser.Lex(); if (parseOperand(Operands, Name)) { SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, "unexpected token in argument list"); } if (Parser.getTok().isNot(AsmToken::RParen)) { SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, "unexpected token, expected ')'"); } Operands.push_back( MipsOperand::CreateToken(")", getLexer().getLoc(), *this)); Parser.Lex(); } return false; } /// Sometimes (i.e. in MSA) the operand may be followed immediately by /// either one of these. /// ::= '[', register, ']' /// ::= '[', integer, ']' /// handle it before we iterate so we don't get tripped up by the lack of /// a comma. bool MipsAsmParser::parseBracketSuffix(StringRef Name, OperandVector &Operands) { MCAsmParser &Parser = getParser(); if (getLexer().is(AsmToken::LBrac)) { Operands.push_back( MipsOperand::CreateToken("[", getLexer().getLoc(), *this)); Parser.Lex(); if (parseOperand(Operands, Name)) { SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, "unexpected token in argument list"); } if (Parser.getTok().isNot(AsmToken::RBrac)) { SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, "unexpected token, expected ']'"); } Operands.push_back( MipsOperand::CreateToken("]", getLexer().getLoc(), *this)); Parser.Lex(); } return false; } bool MipsAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc, OperandVector &Operands) { MCAsmParser &Parser = getParser(); DEBUG(dbgs() << "ParseInstruction\n"); // We have reached first instruction, module directive are now forbidden. getTargetStreamer().forbidModuleDirective(); // Check if we have valid mnemonic if (!mnemonicIsValid(Name, 0)) { Parser.eatToEndOfStatement(); return Error(NameLoc, "unknown instruction"); } // First operand in MCInst is instruction mnemonic. Operands.push_back(MipsOperand::CreateToken(Name, NameLoc, *this)); // Read the remaining operands. if (getLexer().isNot(AsmToken::EndOfStatement)) { // Read the first operand. if (parseOperand(Operands, Name)) { SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, "unexpected token in argument list"); } if (getLexer().is(AsmToken::LBrac) && parseBracketSuffix(Name, Operands)) return true; // AFAIK, parenthesis suffixes are never on the first operand while (getLexer().is(AsmToken::Comma)) { Parser.Lex(); // Eat the comma. // Parse and remember the operand. if (parseOperand(Operands, Name)) { SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, "unexpected token in argument list"); } // Parse bracket and parenthesis suffixes before we iterate if (getLexer().is(AsmToken::LBrac)) { if (parseBracketSuffix(Name, Operands)) return true; } else if (getLexer().is(AsmToken::LParen) && parseParenSuffix(Name, Operands)) return true; } } if (getLexer().isNot(AsmToken::EndOfStatement)) { SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, "unexpected token in argument list"); } Parser.Lex(); // Consume the EndOfStatement. return false; } // FIXME: Given that these have the same name, these should both be // consistent on affecting the Parser. bool MipsAsmParser::reportParseError(Twine ErrorMsg) { MCAsmParser &Parser = getParser(); SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, ErrorMsg); } bool MipsAsmParser::reportParseError(SMLoc Loc, Twine ErrorMsg) { return Error(Loc, ErrorMsg); } bool MipsAsmParser::parseSetNoAtDirective() { MCAsmParser &Parser = getParser(); // Line should look like: ".set noat". // Set the $at register to $0. AssemblerOptions.back()->setATRegIndex(0); Parser.Lex(); // Eat "noat". // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } getTargetStreamer().emitDirectiveSetNoAt(); Parser.Lex(); // Consume the EndOfStatement. return false; } bool MipsAsmParser::parseSetAtDirective() { // Line can be: ".set at", which sets $at to $1 // or ".set at=$reg", which sets $at to $reg. MCAsmParser &Parser = getParser(); Parser.Lex(); // Eat "at". if (getLexer().is(AsmToken::EndOfStatement)) { // No register was specified, so we set $at to $1. AssemblerOptions.back()->setATRegIndex(1); getTargetStreamer().emitDirectiveSetAt(); Parser.Lex(); // Consume the EndOfStatement. return false; } if (getLexer().isNot(AsmToken::Equal)) { reportParseError("unexpected token, expected equals sign"); return false; } Parser.Lex(); // Eat "=". if (getLexer().isNot(AsmToken::Dollar)) { if (getLexer().is(AsmToken::EndOfStatement)) { reportParseError("no register specified"); return false; } else { reportParseError("unexpected token, expected dollar sign '$'"); return false; } } Parser.Lex(); // Eat "$". // Find out what "reg" is. unsigned AtRegNo; const AsmToken &Reg = Parser.getTok(); if (Reg.is(AsmToken::Identifier)) { AtRegNo = matchCPURegisterName(Reg.getIdentifier()); } else if (Reg.is(AsmToken::Integer)) { AtRegNo = Reg.getIntVal(); } else { reportParseError("unexpected token, expected identifier or integer"); return false; } // Check if $reg is a valid register. If it is, set $at to $reg. if (!AssemblerOptions.back()->setATRegIndex(AtRegNo)) { reportParseError("invalid register"); return false; } Parser.Lex(); // Eat "reg". // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } getTargetStreamer().emitDirectiveSetAtWithArg(AtRegNo); Parser.Lex(); // Consume the EndOfStatement. return false; } bool MipsAsmParser::parseSetReorderDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } AssemblerOptions.back()->setReorder(); getTargetStreamer().emitDirectiveSetReorder(); Parser.Lex(); // Consume the EndOfStatement. return false; } bool MipsAsmParser::parseSetNoReorderDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } AssemblerOptions.back()->setNoReorder(); getTargetStreamer().emitDirectiveSetNoReorder(); Parser.Lex(); // Consume the EndOfStatement. return false; } bool MipsAsmParser::parseSetMacroDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } AssemblerOptions.back()->setMacro(); getTargetStreamer().emitDirectiveSetMacro(); Parser.Lex(); // Consume the EndOfStatement. return false; } bool MipsAsmParser::parseSetNoMacroDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } if (AssemblerOptions.back()->isReorder()) { reportParseError("`noreorder' must be set before `nomacro'"); return false; } AssemblerOptions.back()->setNoMacro(); getTargetStreamer().emitDirectiveSetNoMacro(); Parser.Lex(); // Consume the EndOfStatement. return false; } bool MipsAsmParser::parseSetMsaDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) return reportParseError("unexpected token, expected end of statement"); setFeatureBits(Mips::FeatureMSA, "msa"); getTargetStreamer().emitDirectiveSetMsa(); return false; } bool MipsAsmParser::parseSetNoMsaDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) return reportParseError("unexpected token, expected end of statement"); clearFeatureBits(Mips::FeatureMSA, "msa"); getTargetStreamer().emitDirectiveSetNoMsa(); return false; } bool MipsAsmParser::parseSetNoDspDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); // Eat "nodsp". // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } clearFeatureBits(Mips::FeatureDSP, "dsp"); getTargetStreamer().emitDirectiveSetNoDsp(); return false; } bool MipsAsmParser::parseSetMips16Directive() { MCAsmParser &Parser = getParser(); Parser.Lex(); // Eat "mips16". // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } setFeatureBits(Mips::FeatureMips16, "mips16"); getTargetStreamer().emitDirectiveSetMips16(); Parser.Lex(); // Consume the EndOfStatement. return false; } bool MipsAsmParser::parseSetNoMips16Directive() { MCAsmParser &Parser = getParser(); Parser.Lex(); // Eat "nomips16". // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } clearFeatureBits(Mips::FeatureMips16, "mips16"); getTargetStreamer().emitDirectiveSetNoMips16(); Parser.Lex(); // Consume the EndOfStatement. return false; } bool MipsAsmParser::parseSetFpDirective() { MCAsmParser &Parser = getParser(); MipsABIFlagsSection::FpABIKind FpAbiVal; // Line can be: .set fp=32 // .set fp=xx // .set fp=64 Parser.Lex(); // Eat fp token AsmToken Tok = Parser.getTok(); if (Tok.isNot(AsmToken::Equal)) { reportParseError("unexpected token, expected equals sign '='"); return false; } Parser.Lex(); // Eat '=' token. Tok = Parser.getTok(); if (!parseFpABIValue(FpAbiVal, ".set")) return false; if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } getTargetStreamer().emitDirectiveSetFp(FpAbiVal); Parser.Lex(); // Consume the EndOfStatement. return false; } bool MipsAsmParser::parseSetOddSPRegDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); // Eat "oddspreg". if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } clearFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg"); getTargetStreamer().emitDirectiveSetOddSPReg(); return false; } bool MipsAsmParser::parseSetNoOddSPRegDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); // Eat "nooddspreg". if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } setFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg"); getTargetStreamer().emitDirectiveSetNoOddSPReg(); return false; } bool MipsAsmParser::parseSetPopDirective() { MCAsmParser &Parser = getParser(); SMLoc Loc = getLexer().getLoc(); Parser.Lex(); if (getLexer().isNot(AsmToken::EndOfStatement)) return reportParseError("unexpected token, expected end of statement"); // Always keep an element on the options "stack" to prevent the user // from changing the initial options. This is how we remember them. if (AssemblerOptions.size() == 2) return reportParseError(Loc, ".set pop with no .set push"); MCSubtargetInfo &STI = copySTI(); AssemblerOptions.pop_back(); setAvailableFeatures( ComputeAvailableFeatures(AssemblerOptions.back()->getFeatures())); STI.setFeatureBits(AssemblerOptions.back()->getFeatures()); getTargetStreamer().emitDirectiveSetPop(); return false; } bool MipsAsmParser::parseSetPushDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); if (getLexer().isNot(AsmToken::EndOfStatement)) return reportParseError("unexpected token, expected end of statement"); // Create a copy of the current assembler options environment and push it. AssemblerOptions.push_back( make_unique<MipsAssemblerOptions>(AssemblerOptions.back().get())); getTargetStreamer().emitDirectiveSetPush(); return false; } bool MipsAsmParser::parseSetSoftFloatDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); if (getLexer().isNot(AsmToken::EndOfStatement)) return reportParseError("unexpected token, expected end of statement"); setFeatureBits(Mips::FeatureSoftFloat, "soft-float"); getTargetStreamer().emitDirectiveSetSoftFloat(); return false; } bool MipsAsmParser::parseSetHardFloatDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); if (getLexer().isNot(AsmToken::EndOfStatement)) return reportParseError("unexpected token, expected end of statement"); clearFeatureBits(Mips::FeatureSoftFloat, "soft-float"); getTargetStreamer().emitDirectiveSetHardFloat(); return false; } bool MipsAsmParser::parseSetAssignment() { StringRef Name; const MCExpr *Value; MCAsmParser &Parser = getParser(); if (Parser.parseIdentifier(Name)) reportParseError("expected identifier after .set"); if (getLexer().isNot(AsmToken::Comma)) return reportParseError("unexpected token, expected comma"); Lex(); // Eat comma if (Parser.parseExpression(Value)) return reportParseError("expected valid expression after comma"); MCSymbol *Sym = getContext().getOrCreateSymbol(Name); Sym->setVariableValue(Value); return false; } bool MipsAsmParser::parseSetMips0Directive() { MCAsmParser &Parser = getParser(); Parser.Lex(); if (getLexer().isNot(AsmToken::EndOfStatement)) return reportParseError("unexpected token, expected end of statement"); // Reset assembler options to their initial values. MCSubtargetInfo &STI = copySTI(); setAvailableFeatures( ComputeAvailableFeatures(AssemblerOptions.front()->getFeatures())); STI.setFeatureBits(AssemblerOptions.front()->getFeatures()); AssemblerOptions.back()->setFeatures(AssemblerOptions.front()->getFeatures()); getTargetStreamer().emitDirectiveSetMips0(); return false; } bool MipsAsmParser::parseSetArchDirective() { MCAsmParser &Parser = getParser(); Parser.Lex(); if (getLexer().isNot(AsmToken::Equal)) return reportParseError("unexpected token, expected equals sign"); Parser.Lex(); StringRef Arch; if (Parser.parseIdentifier(Arch)) return reportParseError("expected arch identifier"); StringRef ArchFeatureName = StringSwitch<StringRef>(Arch) .Case("mips1", "mips1") .Case("mips2", "mips2") .Case("mips3", "mips3") .Case("mips4", "mips4") .Case("mips5", "mips5") .Case("mips32", "mips32") .Case("mips32r2", "mips32r2") .Case("mips32r3", "mips32r3") .Case("mips32r5", "mips32r5") .Case("mips32r6", "mips32r6") .Case("mips64", "mips64") .Case("mips64r2", "mips64r2") .Case("mips64r3", "mips64r3") .Case("mips64r5", "mips64r5") .Case("mips64r6", "mips64r6") .Case("octeon", "cnmips") .Case("r4000", "mips3") // This is an implementation of Mips3. .Default(""); if (ArchFeatureName.empty()) return reportParseError("unsupported architecture"); selectArch(ArchFeatureName); getTargetStreamer().emitDirectiveSetArch(Arch); return false; } bool MipsAsmParser::parseSetFeature(uint64_t Feature) { MCAsmParser &Parser = getParser(); Parser.Lex(); if (getLexer().isNot(AsmToken::EndOfStatement)) return reportParseError("unexpected token, expected end of statement"); switch (Feature) { default: llvm_unreachable("Unimplemented feature"); case Mips::FeatureDSP: setFeatureBits(Mips::FeatureDSP, "dsp"); getTargetStreamer().emitDirectiveSetDsp(); break; case Mips::FeatureMicroMips: setFeatureBits(Mips::FeatureMicroMips, "micromips"); getTargetStreamer().emitDirectiveSetMicroMips(); break; case Mips::FeatureMips1: selectArch("mips1"); getTargetStreamer().emitDirectiveSetMips1(); break; case Mips::FeatureMips2: selectArch("mips2"); getTargetStreamer().emitDirectiveSetMips2(); break; case Mips::FeatureMips3: selectArch("mips3"); getTargetStreamer().emitDirectiveSetMips3(); break; case Mips::FeatureMips4: selectArch("mips4"); getTargetStreamer().emitDirectiveSetMips4(); break; case Mips::FeatureMips5: selectArch("mips5"); getTargetStreamer().emitDirectiveSetMips5(); break; case Mips::FeatureMips32: selectArch("mips32"); getTargetStreamer().emitDirectiveSetMips32(); break; case Mips::FeatureMips32r2: selectArch("mips32r2"); getTargetStreamer().emitDirectiveSetMips32R2(); break; case Mips::FeatureMips32r3: selectArch("mips32r3"); getTargetStreamer().emitDirectiveSetMips32R3(); break; case Mips::FeatureMips32r5: selectArch("mips32r5"); getTargetStreamer().emitDirectiveSetMips32R5(); break; case Mips::FeatureMips32r6: selectArch("mips32r6"); getTargetStreamer().emitDirectiveSetMips32R6(); break; case Mips::FeatureMips64: selectArch("mips64"); getTargetStreamer().emitDirectiveSetMips64(); break; case Mips::FeatureMips64r2: selectArch("mips64r2"); getTargetStreamer().emitDirectiveSetMips64R2(); break; case Mips::FeatureMips64r3: selectArch("mips64r3"); getTargetStreamer().emitDirectiveSetMips64R3(); break; case Mips::FeatureMips64r5: selectArch("mips64r5"); getTargetStreamer().emitDirectiveSetMips64R5(); break; case Mips::FeatureMips64r6: selectArch("mips64r6"); getTargetStreamer().emitDirectiveSetMips64R6(); break; } return false; } bool MipsAsmParser::eatComma(StringRef ErrorStr) { MCAsmParser &Parser = getParser(); if (getLexer().isNot(AsmToken::Comma)) { SMLoc Loc = getLexer().getLoc(); Parser.eatToEndOfStatement(); return Error(Loc, ErrorStr); } Parser.Lex(); // Eat the comma. return true; } // Used to determine if .cpload, .cprestore, and .cpsetup have any effect. // In this class, it is only used for .cprestore. // FIXME: Only keep track of IsPicEnabled in one place, instead of in both // MipsTargetELFStreamer and MipsAsmParser. bool MipsAsmParser::isPicAndNotNxxAbi() { return inPicMode() && !(isABI_N32() || isABI_N64()); } bool MipsAsmParser::parseDirectiveCpLoad(SMLoc Loc) { if (AssemblerOptions.back()->isReorder()) Warning(Loc, ".cpload should be inside a noreorder section"); if (inMips16Mode()) { reportParseError(".cpload is not supported in Mips16 mode"); return false; } SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Reg; OperandMatchResultTy ResTy = parseAnyRegister(Reg); if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) { reportParseError("expected register containing function address"); return false; } MipsOperand &RegOpnd = static_cast<MipsOperand &>(*Reg[0]); if (!RegOpnd.isGPRAsmReg()) { reportParseError(RegOpnd.getStartLoc(), "invalid register"); return false; } // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } getTargetStreamer().emitDirectiveCpLoad(RegOpnd.getGPR32Reg()); return false; } bool MipsAsmParser::parseDirectiveCpRestore(SMLoc Loc) { MCAsmParser &Parser = getParser(); // Note that .cprestore is ignored if used with the N32 and N64 ABIs or if it // is used in non-PIC mode. if (inMips16Mode()) { reportParseError(".cprestore is not supported in Mips16 mode"); return false; } // Get the stack offset value. const MCExpr *StackOffset; int64_t StackOffsetVal; if (Parser.parseExpression(StackOffset)) { reportParseError("expected stack offset value"); return false; } if (!StackOffset->evaluateAsAbsolute(StackOffsetVal)) { reportParseError("stack offset is not an absolute expression"); return false; } if (StackOffsetVal < 0) { Warning(Loc, ".cprestore with negative stack offset has no effect"); IsCpRestoreSet = false; } else { IsCpRestoreSet = true; CpRestoreOffset = StackOffsetVal; } // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } if (!getTargetStreamer().emitDirectiveCpRestore( CpRestoreOffset, [&]() { return getATReg(Loc); }, Loc, STI)) return true; Parser.Lex(); // Consume the EndOfStatement. return false; } bool MipsAsmParser::parseDirectiveCPSetup() { MCAsmParser &Parser = getParser(); unsigned FuncReg; unsigned Save; bool SaveIsReg = true; SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg; OperandMatchResultTy ResTy = parseAnyRegister(TmpReg); if (ResTy == MatchOperand_NoMatch) { reportParseError("expected register containing function address"); return false; } MipsOperand &FuncRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]); if (!FuncRegOpnd.isGPRAsmReg()) { reportParseError(FuncRegOpnd.getStartLoc(), "invalid register"); Parser.eatToEndOfStatement(); return false; } FuncReg = FuncRegOpnd.getGPR32Reg(); TmpReg.clear(); if (!eatComma("unexpected token, expected comma")) return true; ResTy = parseAnyRegister(TmpReg); if (ResTy == MatchOperand_NoMatch) { const MCExpr *OffsetExpr; int64_t OffsetVal; SMLoc ExprLoc = getLexer().getLoc(); if (Parser.parseExpression(OffsetExpr) || !OffsetExpr->evaluateAsAbsolute(OffsetVal)) { reportParseError(ExprLoc, "expected save register or stack offset"); Parser.eatToEndOfStatement(); return false; } Save = OffsetVal; SaveIsReg = false; } else { MipsOperand &SaveOpnd = static_cast<MipsOperand &>(*TmpReg[0]); if (!SaveOpnd.isGPRAsmReg()) { reportParseError(SaveOpnd.getStartLoc(), "invalid register"); Parser.eatToEndOfStatement(); return false; } Save = SaveOpnd.getGPR32Reg(); } if (!eatComma("unexpected token, expected comma")) return true; const MCExpr *Expr; if (Parser.parseExpression(Expr)) { reportParseError("expected expression"); return false; } if (Expr->getKind() != MCExpr::SymbolRef) { reportParseError("expected symbol"); return false; } const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr *>(Expr); CpSaveLocation = Save; CpSaveLocationIsRegister = SaveIsReg; getTargetStreamer().emitDirectiveCpsetup(FuncReg, Save, Ref->getSymbol(), SaveIsReg); return false; } bool MipsAsmParser::parseDirectiveCPReturn() { getTargetStreamer().emitDirectiveCpreturn(CpSaveLocation, CpSaveLocationIsRegister); return false; } bool MipsAsmParser::parseDirectiveNaN() { MCAsmParser &Parser = getParser(); if (getLexer().isNot(AsmToken::EndOfStatement)) { const AsmToken &Tok = Parser.getTok(); if (Tok.getString() == "2008") { Parser.Lex(); getTargetStreamer().emitDirectiveNaN2008(); return false; } else if (Tok.getString() == "legacy") { Parser.Lex(); getTargetStreamer().emitDirectiveNaNLegacy(); return false; } } // If we don't recognize the option passed to the .nan // directive (e.g. no option or unknown option), emit an error. reportParseError("invalid option in .nan directive"); return false; } bool MipsAsmParser::parseDirectiveSet() { MCAsmParser &Parser = getParser(); // Get the next token. const AsmToken &Tok = Parser.getTok(); if (Tok.getString() == "noat") { return parseSetNoAtDirective(); } else if (Tok.getString() == "at") { return parseSetAtDirective(); } else if (Tok.getString() == "arch") { return parseSetArchDirective(); } else if (Tok.getString() == "fp") { return parseSetFpDirective(); } else if (Tok.getString() == "oddspreg") { return parseSetOddSPRegDirective(); } else if (Tok.getString() == "nooddspreg") { return parseSetNoOddSPRegDirective(); } else if (Tok.getString() == "pop") { return parseSetPopDirective(); } else if (Tok.getString() == "push") { return parseSetPushDirective(); } else if (Tok.getString() == "reorder") { return parseSetReorderDirective(); } else if (Tok.getString() == "noreorder") { return parseSetNoReorderDirective(); } else if (Tok.getString() == "macro") { return parseSetMacroDirective(); } else if (Tok.getString() == "nomacro") { return parseSetNoMacroDirective(); } else if (Tok.getString() == "mips16") { return parseSetMips16Directive(); } else if (Tok.getString() == "nomips16") { return parseSetNoMips16Directive(); } else if (Tok.getString() == "nomicromips") { clearFeatureBits(Mips::FeatureMicroMips, "micromips"); getTargetStreamer().emitDirectiveSetNoMicroMips(); Parser.eatToEndOfStatement(); return false; } else if (Tok.getString() == "micromips") { return parseSetFeature(Mips::FeatureMicroMips); } else if (Tok.getString() == "mips0") { return parseSetMips0Directive(); } else if (Tok.getString() == "mips1") { return parseSetFeature(Mips::FeatureMips1); } else if (Tok.getString() == "mips2") { return parseSetFeature(Mips::FeatureMips2); } else if (Tok.getString() == "mips3") { return parseSetFeature(Mips::FeatureMips3); } else if (Tok.getString() == "mips4") { return parseSetFeature(Mips::FeatureMips4); } else if (Tok.getString() == "mips5") { return parseSetFeature(Mips::FeatureMips5); } else if (Tok.getString() == "mips32") { return parseSetFeature(Mips::FeatureMips32); } else if (Tok.getString() == "mips32r2") { return parseSetFeature(Mips::FeatureMips32r2); } else if (Tok.getString() == "mips32r3") { return parseSetFeature(Mips::FeatureMips32r3); } else if (Tok.getString() == "mips32r5") { return parseSetFeature(Mips::FeatureMips32r5); } else if (Tok.getString() == "mips32r6") { return parseSetFeature(Mips::FeatureMips32r6); } else if (Tok.getString() == "mips64") { return parseSetFeature(Mips::FeatureMips64); } else if (Tok.getString() == "mips64r2") { return parseSetFeature(Mips::FeatureMips64r2); } else if (Tok.getString() == "mips64r3") { return parseSetFeature(Mips::FeatureMips64r3); } else if (Tok.getString() == "mips64r5") { return parseSetFeature(Mips::FeatureMips64r5); } else if (Tok.getString() == "mips64r6") { return parseSetFeature(Mips::FeatureMips64r6); } else if (Tok.getString() == "dsp") { return parseSetFeature(Mips::FeatureDSP); } else if (Tok.getString() == "nodsp") { return parseSetNoDspDirective(); } else if (Tok.getString() == "msa") { return parseSetMsaDirective(); } else if (Tok.getString() == "nomsa") { return parseSetNoMsaDirective(); } else if (Tok.getString() == "softfloat") { return parseSetSoftFloatDirective(); } else if (Tok.getString() == "hardfloat") { return parseSetHardFloatDirective(); } else { // It is just an identifier, look for an assignment. parseSetAssignment(); return false; } return true; } /// parseDataDirective /// ::= .word [ expression (, expression)* ] bool MipsAsmParser::parseDataDirective(unsigned Size, SMLoc L) { MCAsmParser &Parser = getParser(); if (getLexer().isNot(AsmToken::EndOfStatement)) { for (;;) { const MCExpr *Value; if (getParser().parseExpression(Value)) return true; getParser().getStreamer().EmitValue(Value, Size); if (getLexer().is(AsmToken::EndOfStatement)) break; if (getLexer().isNot(AsmToken::Comma)) return Error(L, "unexpected token, expected comma"); Parser.Lex(); } } Parser.Lex(); return false; } /// parseDirectiveGpWord /// ::= .gpword local_sym bool MipsAsmParser::parseDirectiveGpWord() { MCAsmParser &Parser = getParser(); const MCExpr *Value; // EmitGPRel32Value requires an expression, so we are using base class // method to evaluate the expression. if (getParser().parseExpression(Value)) return true; getParser().getStreamer().EmitGPRel32Value(Value); if (getLexer().isNot(AsmToken::EndOfStatement)) return Error(getLexer().getLoc(), "unexpected token, expected end of statement"); Parser.Lex(); // Eat EndOfStatement token. return false; } /// parseDirectiveGpDWord /// ::= .gpdword local_sym bool MipsAsmParser::parseDirectiveGpDWord() { MCAsmParser &Parser = getParser(); const MCExpr *Value; // EmitGPRel64Value requires an expression, so we are using base class // method to evaluate the expression. if (getParser().parseExpression(Value)) return true; getParser().getStreamer().EmitGPRel64Value(Value); if (getLexer().isNot(AsmToken::EndOfStatement)) return Error(getLexer().getLoc(), "unexpected token, expected end of statement"); Parser.Lex(); // Eat EndOfStatement token. return false; } bool MipsAsmParser::parseDirectiveOption() { MCAsmParser &Parser = getParser(); // Get the option token. AsmToken Tok = Parser.getTok(); // At the moment only identifiers are supported. if (Tok.isNot(AsmToken::Identifier)) { Error(Parser.getTok().getLoc(), "unexpected token, expected identifier"); Parser.eatToEndOfStatement(); return false; } StringRef Option = Tok.getIdentifier(); if (Option == "pic0") { // MipsAsmParser needs to know if the current PIC mode changes. IsPicEnabled = false; getTargetStreamer().emitDirectiveOptionPic0(); Parser.Lex(); if (Parser.getTok().isNot(AsmToken::EndOfStatement)) { Error(Parser.getTok().getLoc(), "unexpected token, expected end of statement"); Parser.eatToEndOfStatement(); } return false; } if (Option == "pic2") { // MipsAsmParser needs to know if the current PIC mode changes. IsPicEnabled = true; getTargetStreamer().emitDirectiveOptionPic2(); Parser.Lex(); if (Parser.getTok().isNot(AsmToken::EndOfStatement)) { Error(Parser.getTok().getLoc(), "unexpected token, expected end of statement"); Parser.eatToEndOfStatement(); } return false; } // Unknown option. Warning(Parser.getTok().getLoc(), "unknown option, expected 'pic0' or 'pic2'"); Parser.eatToEndOfStatement(); return false; } /// parseInsnDirective /// ::= .insn bool MipsAsmParser::parseInsnDirective() { // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } // The actual label marking happens in // MipsELFStreamer::createPendingLabelRelocs(). getTargetStreamer().emitDirectiveInsn(); getParser().Lex(); // Eat EndOfStatement token. return false; } /// parseSSectionDirective /// ::= .sbss /// ::= .sdata bool MipsAsmParser::parseSSectionDirective(StringRef Section, unsigned Type) { // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } MCSection *ELFSection = getContext().getELFSection( Section, Type, ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_MIPS_GPREL); getParser().getStreamer().SwitchSection(ELFSection); getParser().Lex(); // Eat EndOfStatement token. return false; } /// parseDirectiveModule /// ::= .module oddspreg /// ::= .module nooddspreg /// ::= .module fp=value /// ::= .module softfloat /// ::= .module hardfloat bool MipsAsmParser::parseDirectiveModule() { MCAsmParser &Parser = getParser(); MCAsmLexer &Lexer = getLexer(); SMLoc L = Lexer.getLoc(); if (!getTargetStreamer().isModuleDirectiveAllowed()) { // TODO : get a better message. reportParseError(".module directive must appear before any code"); return false; } StringRef Option; if (Parser.parseIdentifier(Option)) { reportParseError("expected .module option identifier"); return false; } if (Option == "oddspreg") { clearModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg"); // Synchronize the abiflags information with the FeatureBits information we // changed above. getTargetStreamer().updateABIInfo(*this); // If printing assembly, use the recently updated abiflags information. // If generating ELF, don't do anything (the .MIPS.abiflags section gets // emitted at the end). getTargetStreamer().emitDirectiveModuleOddSPReg(); // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } return false; // parseDirectiveModule has finished successfully. } else if (Option == "nooddspreg") { if (!isABI_O32()) { Error(L, "'.module nooddspreg' requires the O32 ABI"); return false; } setModuleFeatureBits(Mips::FeatureNoOddSPReg, "nooddspreg"); // Synchronize the abiflags information with the FeatureBits information we // changed above. getTargetStreamer().updateABIInfo(*this); // If printing assembly, use the recently updated abiflags information. // If generating ELF, don't do anything (the .MIPS.abiflags section gets // emitted at the end). getTargetStreamer().emitDirectiveModuleOddSPReg(); // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } return false; // parseDirectiveModule has finished successfully. } else if (Option == "fp") { return parseDirectiveModuleFP(); } else if (Option == "softfloat") { setModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float"); // Synchronize the ABI Flags information with the FeatureBits information we // updated above. getTargetStreamer().updateABIInfo(*this); // If printing assembly, use the recently updated ABI Flags information. // If generating ELF, don't do anything (the .MIPS.abiflags section gets // emitted later). getTargetStreamer().emitDirectiveModuleSoftFloat(); // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } return false; // parseDirectiveModule has finished successfully. } else if (Option == "hardfloat") { clearModuleFeatureBits(Mips::FeatureSoftFloat, "soft-float"); // Synchronize the ABI Flags information with the FeatureBits information we // updated above. getTargetStreamer().updateABIInfo(*this); // If printing assembly, use the recently updated ABI Flags information. // If generating ELF, don't do anything (the .MIPS.abiflags section gets // emitted later). getTargetStreamer().emitDirectiveModuleHardFloat(); // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } return false; // parseDirectiveModule has finished successfully. } else { return Error(L, "'" + Twine(Option) + "' is not a valid .module option."); } } /// parseDirectiveModuleFP /// ::= =32 /// ::= =xx /// ::= =64 bool MipsAsmParser::parseDirectiveModuleFP() { MCAsmParser &Parser = getParser(); MCAsmLexer &Lexer = getLexer(); if (Lexer.isNot(AsmToken::Equal)) { reportParseError("unexpected token, expected equals sign '='"); return false; } Parser.Lex(); // Eat '=' token. MipsABIFlagsSection::FpABIKind FpABI; if (!parseFpABIValue(FpABI, ".module")) return false; if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } // Synchronize the abiflags information with the FeatureBits information we // changed above. getTargetStreamer().updateABIInfo(*this); // If printing assembly, use the recently updated abiflags information. // If generating ELF, don't do anything (the .MIPS.abiflags section gets // emitted at the end). getTargetStreamer().emitDirectiveModuleFP(); Parser.Lex(); // Consume the EndOfStatement. return false; } bool MipsAsmParser::parseFpABIValue(MipsABIFlagsSection::FpABIKind &FpABI, StringRef Directive) { MCAsmParser &Parser = getParser(); MCAsmLexer &Lexer = getLexer(); bool ModuleLevelOptions = Directive == ".module"; if (Lexer.is(AsmToken::Identifier)) { StringRef Value = Parser.getTok().getString(); Parser.Lex(); if (Value != "xx") { reportParseError("unsupported value, expected 'xx', '32' or '64'"); return false; } if (!isABI_O32()) { reportParseError("'" + Directive + " fp=xx' requires the O32 ABI"); return false; } FpABI = MipsABIFlagsSection::FpABIKind::XX; if (ModuleLevelOptions) { setModuleFeatureBits(Mips::FeatureFPXX, "fpxx"); clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64"); } else { setFeatureBits(Mips::FeatureFPXX, "fpxx"); clearFeatureBits(Mips::FeatureFP64Bit, "fp64"); } return true; } if (Lexer.is(AsmToken::Integer)) { unsigned Value = Parser.getTok().getIntVal(); Parser.Lex(); if (Value != 32 && Value != 64) { reportParseError("unsupported value, expected 'xx', '32' or '64'"); return false; } if (Value == 32) { if (!isABI_O32()) { reportParseError("'" + Directive + " fp=32' requires the O32 ABI"); return false; } FpABI = MipsABIFlagsSection::FpABIKind::S32; if (ModuleLevelOptions) { clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx"); clearModuleFeatureBits(Mips::FeatureFP64Bit, "fp64"); } else { clearFeatureBits(Mips::FeatureFPXX, "fpxx"); clearFeatureBits(Mips::FeatureFP64Bit, "fp64"); } } else { FpABI = MipsABIFlagsSection::FpABIKind::S64; if (ModuleLevelOptions) { clearModuleFeatureBits(Mips::FeatureFPXX, "fpxx"); setModuleFeatureBits(Mips::FeatureFP64Bit, "fp64"); } else { clearFeatureBits(Mips::FeatureFPXX, "fpxx"); setFeatureBits(Mips::FeatureFP64Bit, "fp64"); } } return true; } return false; } bool MipsAsmParser::ParseDirective(AsmToken DirectiveID) { // This returns false if this function recognizes the directive // regardless of whether it is successfully handles or reports an // error. Otherwise it returns true to give the generic parser a // chance at recognizing it. MCAsmParser &Parser = getParser(); StringRef IDVal = DirectiveID.getString(); if (IDVal == ".cpload") { parseDirectiveCpLoad(DirectiveID.getLoc()); return false; } if (IDVal == ".cprestore") { parseDirectiveCpRestore(DirectiveID.getLoc()); return false; } if (IDVal == ".dword") { parseDataDirective(8, DirectiveID.getLoc()); return false; } if (IDVal == ".ent") { StringRef SymbolName; if (Parser.parseIdentifier(SymbolName)) { reportParseError("expected identifier after .ent"); return false; } // There's an undocumented extension that allows an integer to // follow the name of the procedure which AFAICS is ignored by GAS. // Example: .ent foo,2 if (getLexer().isNot(AsmToken::EndOfStatement)) { if (getLexer().isNot(AsmToken::Comma)) { // Even though we accept this undocumented extension for compatibility // reasons, the additional integer argument does not actually change // the behaviour of the '.ent' directive, so we would like to discourage // its use. We do this by not referring to the extended version in // error messages which are not directly related to its use. reportParseError("unexpected token, expected end of statement"); return false; } Parser.Lex(); // Eat the comma. const MCExpr *DummyNumber; int64_t DummyNumberVal; // If the user was explicitly trying to use the extended version, // we still give helpful extension-related error messages. if (Parser.parseExpression(DummyNumber)) { reportParseError("expected number after comma"); return false; } if (!DummyNumber->evaluateAsAbsolute(DummyNumberVal)) { reportParseError("expected an absolute expression after comma"); return false; } } // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName); getTargetStreamer().emitDirectiveEnt(*Sym); CurrentFn = Sym; IsCpRestoreSet = false; return false; } if (IDVal == ".end") { StringRef SymbolName; if (Parser.parseIdentifier(SymbolName)) { reportParseError("expected identifier after .end"); return false; } if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } if (CurrentFn == nullptr) { reportParseError(".end used without .ent"); return false; } if ((SymbolName != CurrentFn->getName())) { reportParseError(".end symbol does not match .ent symbol"); return false; } getTargetStreamer().emitDirectiveEnd(SymbolName); CurrentFn = nullptr; IsCpRestoreSet = false; return false; } if (IDVal == ".frame") { // .frame $stack_reg, frame_size_in_bytes, $return_reg SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> TmpReg; OperandMatchResultTy ResTy = parseAnyRegister(TmpReg); if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) { reportParseError("expected stack register"); return false; } MipsOperand &StackRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]); if (!StackRegOpnd.isGPRAsmReg()) { reportParseError(StackRegOpnd.getStartLoc(), "expected general purpose register"); return false; } unsigned StackReg = StackRegOpnd.getGPR32Reg(); if (Parser.getTok().is(AsmToken::Comma)) Parser.Lex(); else { reportParseError("unexpected token, expected comma"); return false; } // Parse the frame size. const MCExpr *FrameSize; int64_t FrameSizeVal; if (Parser.parseExpression(FrameSize)) { reportParseError("expected frame size value"); return false; } if (!FrameSize->evaluateAsAbsolute(FrameSizeVal)) { reportParseError("frame size not an absolute expression"); return false; } if (Parser.getTok().is(AsmToken::Comma)) Parser.Lex(); else { reportParseError("unexpected token, expected comma"); return false; } // Parse the return register. TmpReg.clear(); ResTy = parseAnyRegister(TmpReg); if (ResTy == MatchOperand_NoMatch || ResTy == MatchOperand_ParseFail) { reportParseError("expected return register"); return false; } MipsOperand &ReturnRegOpnd = static_cast<MipsOperand &>(*TmpReg[0]); if (!ReturnRegOpnd.isGPRAsmReg()) { reportParseError(ReturnRegOpnd.getStartLoc(), "expected general purpose register"); return false; } // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } getTargetStreamer().emitFrame(StackReg, FrameSizeVal, ReturnRegOpnd.getGPR32Reg()); IsCpRestoreSet = false; return false; } if (IDVal == ".set") { parseDirectiveSet(); return false; } if (IDVal == ".mask" || IDVal == ".fmask") { // .mask bitmask, frame_offset // bitmask: One bit for each register used. // frame_offset: Offset from Canonical Frame Address ($sp on entry) where // first register is expected to be saved. // Examples: // .mask 0x80000000, -4 // .fmask 0x80000000, -4 // // Parse the bitmask const MCExpr *BitMask; int64_t BitMaskVal; if (Parser.parseExpression(BitMask)) { reportParseError("expected bitmask value"); return false; } if (!BitMask->evaluateAsAbsolute(BitMaskVal)) { reportParseError("bitmask not an absolute expression"); return false; } if (Parser.getTok().is(AsmToken::Comma)) Parser.Lex(); else { reportParseError("unexpected token, expected comma"); return false; } // Parse the frame_offset const MCExpr *FrameOffset; int64_t FrameOffsetVal; if (Parser.parseExpression(FrameOffset)) { reportParseError("expected frame offset value"); return false; } if (!FrameOffset->evaluateAsAbsolute(FrameOffsetVal)) { reportParseError("frame offset not an absolute expression"); return false; } // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } if (IDVal == ".mask") getTargetStreamer().emitMask(BitMaskVal, FrameOffsetVal); else getTargetStreamer().emitFMask(BitMaskVal, FrameOffsetVal); return false; } if (IDVal == ".nan") return parseDirectiveNaN(); if (IDVal == ".gpword") { parseDirectiveGpWord(); return false; } if (IDVal == ".gpdword") { parseDirectiveGpDWord(); return false; } if (IDVal == ".word") { parseDataDirective(4, DirectiveID.getLoc()); return false; } if (IDVal == ".hword") { parseDataDirective(2, DirectiveID.getLoc()); return false; } if (IDVal == ".option") { parseDirectiveOption(); return false; } if (IDVal == ".abicalls") { getTargetStreamer().emitDirectiveAbiCalls(); if (Parser.getTok().isNot(AsmToken::EndOfStatement)) { Error(Parser.getTok().getLoc(), "unexpected token, expected end of statement"); // Clear line Parser.eatToEndOfStatement(); } return false; } if (IDVal == ".cpsetup") { parseDirectiveCPSetup(); return false; } if (IDVal == ".cpreturn") { parseDirectiveCPReturn(); return false; } if (IDVal == ".module") { parseDirectiveModule(); return false; } if (IDVal == ".llvm_internal_mips_reallow_module_directive") { parseInternalDirectiveReallowModule(); return false; } if (IDVal == ".insn") { parseInsnDirective(); return false; } if (IDVal == ".sbss") { parseSSectionDirective(IDVal, ELF::SHT_NOBITS); return false; } if (IDVal == ".sdata") { parseSSectionDirective(IDVal, ELF::SHT_PROGBITS); return false; } return true; } bool MipsAsmParser::parseInternalDirectiveReallowModule() { // If this is not the end of the statement, report an error. if (getLexer().isNot(AsmToken::EndOfStatement)) { reportParseError("unexpected token, expected end of statement"); return false; } getTargetStreamer().reallowModuleDirective(); getParser().Lex(); // Eat EndOfStatement token. return false; } extern "C" void LLVMInitializeMipsAsmParser() { RegisterMCAsmParser<MipsAsmParser> X(TheMipsTarget); RegisterMCAsmParser<MipsAsmParser> Y(TheMipselTarget); RegisterMCAsmParser<MipsAsmParser> A(TheMips64Target); RegisterMCAsmParser<MipsAsmParser> B(TheMips64elTarget); } #define GET_REGISTER_MATCHER #define GET_MATCHER_IMPLEMENTATION #include "MipsGenAsmMatcher.inc"
sawenzel/root
interpreter/llvm/src/lib/Target/Mips/AsmParser/MipsAsmParser.cpp
C++
lgpl-2.1
222,254
/* -------------------------------------------------------------------------- libmusicbrainz4 - Client library to access MusicBrainz Copyright (C) 2011 Andrew Hawkins This file is part of libmusicbrainz4. This library is free software; you can redistribute it and/or modify it under the terms of v2 of the GNU Lesser General Public License as published by the Free Software Foundation. libmusicbrainz4 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. $Id$ ----------------------------------------------------------------------------*/ #include "musicbrainz4/FreeDBDisc.h" #include "musicbrainz4/NonMBTrackList.h" #include "musicbrainz4/NonMBTrack.h" class MusicBrainz4::CFreeDBDiscPrivate { public: CFreeDBDiscPrivate() : m_NonMBTrackList(0) { } std::string m_ID; std::string m_Title; std::string m_Artist; std::string m_Category; std::string m_Year; CNonMBTrackList *m_NonMBTrackList; }; MusicBrainz4::CFreeDBDisc::CFreeDBDisc(const XMLNode& Node) : CEntity(), m_d(new CFreeDBDiscPrivate) { if (!Node.isEmpty()) { //std::cout << "FreeDBDisc node: " << std::endl << Node.createXMLString(true) << std::endl; Parse(Node); } } MusicBrainz4::CFreeDBDisc::CFreeDBDisc(const CFreeDBDisc& Other) : CEntity(), m_d(new CFreeDBDiscPrivate) { *this=Other; } MusicBrainz4::CFreeDBDisc& MusicBrainz4::CFreeDBDisc::operator =(const CFreeDBDisc& Other) { if (this!=&Other) { Cleanup(); CEntity::operator =(Other); m_d->m_ID=Other.m_d->m_ID; m_d->m_Title=Other.m_d->m_Title; m_d->m_Artist=Other.m_d->m_Artist; m_d->m_Category=Other.m_d->m_Category; m_d->m_Year=Other.m_d->m_Year; if (Other.m_d->m_NonMBTrackList) m_d->m_NonMBTrackList=new CNonMBTrackList(*Other.m_d->m_NonMBTrackList); } return *this; } MusicBrainz4::CFreeDBDisc::~CFreeDBDisc() { Cleanup(); delete m_d; } void MusicBrainz4::CFreeDBDisc::Cleanup() { delete m_d->m_NonMBTrackList; m_d->m_NonMBTrackList=0; } MusicBrainz4::CFreeDBDisc *MusicBrainz4::CFreeDBDisc::Clone() { return new CFreeDBDisc(*this); } bool MusicBrainz4::CFreeDBDisc::ParseAttribute(const std::string& Name, const std::string& Value) { bool RetVal=true; if ("id"==Name) m_d->m_ID=Value; else { std::cerr << "Unrecognised freedb disc attribute: '" << Name << "'" << std::endl; RetVal=false; } return RetVal; } bool MusicBrainz4::CFreeDBDisc::ParseElement(const XMLNode& Node) { bool RetVal=true; std::string NodeName=Node.getName(); if ("title"==NodeName) { RetVal=ProcessItem(Node,m_d->m_Title); } else if ("artist"==NodeName) { RetVal=ProcessItem(Node,m_d->m_Artist); } else if ("category"==NodeName) { RetVal=ProcessItem(Node,m_d->m_Category); } else if ("year"==NodeName) { RetVal=ProcessItem(Node,m_d->m_Year); } else if ("nonmb-track-list"==NodeName) { RetVal=ProcessItem(Node,m_d->m_NonMBTrackList); } else { std::cerr << "Unrecognised freedb disc element: '" << NodeName << "'" << std::endl; RetVal=false; } return RetVal; } std::string MusicBrainz4::CFreeDBDisc::GetElementName() { return "freedb-disc"; } std::string MusicBrainz4::CFreeDBDisc::ID() const { return m_d->m_ID; } std::string MusicBrainz4::CFreeDBDisc::Title() const { return m_d->m_Title; } std::string MusicBrainz4::CFreeDBDisc::Artist() const { return m_d->m_Artist; } std::string MusicBrainz4::CFreeDBDisc::Category() const { return m_d->m_Category; } std::string MusicBrainz4::CFreeDBDisc::Year() const { return m_d->m_Year; } MusicBrainz4::CNonMBTrackList *MusicBrainz4::CFreeDBDisc::NonMBTrackList() const { return m_d->m_NonMBTrackList; } std::ostream& MusicBrainz4::CFreeDBDisc::Serialise(std::ostream& os) const { os << "FreeDBDisc:" << std::endl; CEntity::Serialise(os); os << "\tID: " << ID() << std::endl; os << "\tTitle: " << Title() << std::endl; os << "\tArtist: " << Artist() << std::endl; os << "\tCategory: " << Category() << std::endl; os << "\tYear: " << Year() << std::endl; if (NonMBTrackList()) os << *NonMBTrackList() << std::endl; return os; }
ianmcorvidae/libmusicbrainz
src/FreeDBDisc.cc
C++
lgpl-2.1
4,400
#region LGPL License /* Axiom Graphics Engine Library Copyright © 2003-2011 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion #region SVN Version Information // <file> // <license see="http://axiom3d.net/wiki/index.php/license.txt"/> // <id value="$Id$"/> // </file> #endregion SVN Version Information #region Namespace Declarations using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Axiom.Core; using Axiom.Scripting.Compiler.AST; using Axiom.Scripting.Compiler.Parser; #endregion Namespace Declarations namespace Axiom.Scripting.Compiler { /// <summary> /// This is the main class for the compiler. It calls the parser /// and processes the CST into an AST and then uses translators /// to translate the AST into the final resources. /// </summary> public partial class ScriptCompiler { // This enum are built-in word id values enum BuiltIn : uint { ID_ON = 1, ID_OFF = 2, ID_TRUE = 1, ID_FALSE = 2, ID_YES = 1, ID_NO = 2 }; private List<CompileError> _errors = new List<CompileError>(); private String _resourceGroup; public String ResourceGroup { get { return _resourceGroup; } } private Dictionary<string, string> _environment = new Dictionary<string, string>(); public Dictionary<string, string> Environment { get { return _environment; } } private Dictionary<string, uint> _keywordMap = new Dictionary<string, uint>(); public Dictionary<string, uint> KeywordMap { get { return _keywordMap; } } /// <summary> /// The set of imported scripts to avoid circular dependencies /// </summary> private Dictionary<string, IList<AbstractNode>> _imports = new Dictionary<string, IList<AbstractNode>>(); /// <summary> /// This holds the target objects for each script to be imported /// </summary> private Dictionary<string, string> _importRequests = new Dictionary<string, string>(); /// <summary> /// This stores the imports of the scripts, so they are separated and can be treated specially /// </summary> private List<AbstractNode> _importTable = new List<AbstractNode>(); private ScriptCompilerListener _listener; public ScriptCompilerListener Listener { get { return _listener; } set { _listener = value; } } #region Events /// <see cref="ScriptCompilerManager.OnImportFile"/> public event ScriptCompilerManager.ImportFileHandler OnImportFile; /// <see cref="ScriptCompilerManager.OnPreConversion"/> public event ScriptCompilerManager.PreConversionHandler OnPreConversion; /// <see cref="ScriptCompilerManager.OnPostConversion"/> public event ScriptCompilerManager.PostConversionHandler OnPostConversion; /// <see cref="ScriptCompilerManager.OnCompileError"/> public event ScriptCompilerManager.CompilerErrorHandler OnCompileError; /// <see cref="ScriptCompilerManager.OnCompilerEvent"/> public event ScriptCompilerManager.TransationEventHandler OnCompilerEvent; #endregion Events public ScriptCompiler() { InitializeWordMap(); this.OnPreConversion = null; this.OnPostConversion = null; this.OnImportFile = null; this.OnCompileError = null; this.OnCompilerEvent = null; } /// <summary> /// Takes in a string of script code and compiles it into resources /// </summary> /// <param name="script">The script code</param> /// <param name="source">The source of the script code (e.g. a script file)</param> /// <param name="group">The resource group to place the compiled resources into</param> /// <returns></returns> public bool Compile( String script, String source, String group ) { ScriptLexer lexer = new ScriptLexer(); ScriptParser parser = new ScriptParser(); IList<ScriptToken> tokens = lexer.Tokenize( script, source ); IList<ConcreteNode> nodes = parser.Parse( tokens ); return Compile( nodes, group ); } /// <see cref="ScriptCompiler.Compile(IList&lt;AbstractNode&gt;, string, bool, bool, bool)"/> public bool Compile( IList<AbstractNode> nodes, string group ) { return this.Compile( nodes, group, true, true, true ); } /// <see cref="ScriptCompiler.Compile(IList&lt;AbstractNode&gt;, string, bool, bool, bool)"/> public bool Compile( IList<AbstractNode> nodes, string group, bool doImports ) { return this.Compile( nodes, group, doImports, true, true ); } /// <see cref="ScriptCompiler.Compile(IList&lt;AbstractNode&gt;, string, bool, bool, bool)"/> public bool Compile( IList<AbstractNode> nodes, string group, bool doImports, bool doObjects ) { return this.Compile( nodes, group, doImports, doObjects, true ); } /// <summary> /// Compiles the given abstract syntax tree /// </summary> /// <param name="nodes"></param> /// <param name="group"></param> /// <param name="doImports"></param> /// <param name="doObjects"></param> /// <param name="doVariables"></param> /// <returns></returns> public bool Compile( IList<AbstractNode> nodes, string group, bool doImports, bool doObjects, bool doVariables ) { // Save the group _resourceGroup = group; // Clear the past errors _errors.Clear(); // Clear the environment _environment.Clear(); // Processes the imports for this script if ( doImports ) _processImports( ref nodes ); // Process object inheritance if ( doObjects ) _processObjects( ref nodes, nodes ); // Process variable expansion if ( doVariables ) _processVariables( ref nodes ); // Translate the nodes foreach ( AbstractNode currentNode in nodes ) { //logAST(0, *i); if ( currentNode is ObjectAbstractNode && ( (ObjectAbstractNode)currentNode ).IsAbstract ) continue; ScriptCompiler.Translator translator = ScriptCompilerManager.Instance.GetTranslator( currentNode ); if ( translator != null ) translator.Translate( this, currentNode ); } return _errors.Count == 0; } /// <summary> /// Compiles resources from the given concrete node list /// </summary> /// <param name="nodes">The list of nodes to compile</param> /// <param name="group">The resource group to place the compiled resources into</param> /// <returns></returns> private bool Compile( IList<ConcreteNode> nodes, string group ) { // Save the group _resourceGroup = group; // Clear the past errors _errors.Clear(); // Clear the environment _environment.Clear(); if ( this.OnPreConversion != null ) this.OnPreConversion( this, nodes ); // Convert our nodes to an AST IList<AbstractNode> ast = _convertToAST( nodes ); // Processes the imports for this script _processImports( ref ast ); // Process object inheritance _processObjects( ref ast, ast ); // Process variable expansion _processVariables( ref ast ); // Allows early bail-out through the listener if ( this.OnPostConversion != null && !this.OnPostConversion( this, ast ) ) return _errors.Count == 0; // Translate the nodes foreach ( AbstractNode currentNode in ast ) { //logAST(0, *i); if ( currentNode is ObjectAbstractNode && ( (ObjectAbstractNode)currentNode ).IsAbstract ) continue; ScriptCompiler.Translator translator = ScriptCompilerManager.Instance.GetTranslator( currentNode ); if ( translator != null ) translator.Translate( this, currentNode ); } _imports.Clear(); _importRequests.Clear(); _importTable.Clear(); return _errors.Count == 0; } internal void AddError( CompileErrorCode code, string file, uint line ) { this.AddError( code, file, line, string.Empty ); } /// <summary> /// Adds the given error to the compiler's list of errors /// </summary> /// <param name="code"></param> /// <param name="file"></param> /// <param name="line"></param> /// <param name="msg"></param> internal void AddError( CompileErrorCode code, string file, uint line, string msg ) { CompileError error = new CompileError( code, file, line, msg ); if ( this.OnCompileError != null ) { this.OnCompileError( this, error ); } else { string str = string.Format( "Compiler error: {0} in {1}({2})", ScriptEnumAttribute.GetScriptAttribute( (int)code, typeof( CompileErrorCode ) ), file, line ); if ( !string.IsNullOrEmpty( msg ) ) str += ": " + msg; LogManager.Instance.Write( str ); } _errors.Add( error ); } /// <see cref="ScriptCompiler._fireEvent(ref ScriptCompilerEvent, out object)"/> internal bool _fireEvent( ref ScriptCompilerEvent evt ) { object o; return _fireEvent( ref evt, out o ); } /// <summary> /// Internal method for firing the handleEvent method /// </summary> /// <param name="evt"></param> /// <param name="retVal"></param> /// <returns></returns> internal bool _fireEvent( ref ScriptCompilerEvent evt, out object retVal ) { retVal = null; if ( this.OnCompilerEvent != null ) return this.OnCompilerEvent( this, ref evt, out retVal ); return false; } private IList<AbstractNode> _convertToAST( IList<ConcreteNode> nodes ) { AbstractTreeBuilder builder = new AbstractTreeBuilder( this ); AbstractTreeBuilder.Visit( builder, nodes ); return builder.Result; } /// <summary> /// Returns true if the given class is name excluded /// </summary> /// <param name="cls"></param> /// <param name="parent"></param> /// <returns></returns> private bool _isNameExcluded( string cls, AbstractNode parent ) { // Run past the listener object excludeObj; bool excludeName = false; ScriptCompilerEvent evt = new ProcessNameExclusionScriptCompilerEvent( cls, parent ); bool processed = _fireEvent( ref evt, out excludeObj ); if ( !processed ) { // Process the built-in name exclusions if ( cls == "emitter" || cls == "affector" ) { // emitters or affectors inside a particle_system are excluded while ( parent != null && parent is ObjectAbstractNode ) { ObjectAbstractNode obj = (ObjectAbstractNode)parent; if ( obj.Cls == "particle_system" ) return true; parent = obj.Parent; } return false; } else if ( cls == "pass" ) { // passes inside compositors are excluded while ( parent != null && parent is ObjectAbstractNode ) { ObjectAbstractNode obj = (ObjectAbstractNode)parent; if ( obj.Cls == "compositor" ) return true; parent = obj.Parent; } return false; } else if ( cls == "texture_source" ) { // Parent must be texture_unit while ( parent != null && parent is ObjectAbstractNode ) { ObjectAbstractNode obj = (ObjectAbstractNode)parent; if ( obj.Cls == "texture_unit" ) return true; parent = obj.Parent; } return false; } } else { excludeObj = (bool)excludeObj; return excludeName; } return false; } /// <summary> /// This built-in function processes import nodes /// </summary> /// <param name="nodes"></param> private void _processImports( ref IList<AbstractNode> nodes ) { // We only need to iterate over the top-level of nodes for ( int i = 1; i < nodes.Count; i++ ) { AbstractNode cur = nodes[ i ]; if ( cur is ImportAbstractNode ) { ImportAbstractNode import = (ImportAbstractNode)cur; // Only process if the file's contents haven't been loaded if ( !_imports.ContainsKey( import.Source ) ) { // Load the script IList<AbstractNode> importedNodes = _loadImportPath( import.Source ); if ( importedNodes != null && importedNodes.Count != 0 ) { _processImports( ref importedNodes ); _processObjects( ref importedNodes, importedNodes ); } if ( importedNodes != null && importedNodes.Count != 0 ) _imports.Add( import.Source, importedNodes ); } // Handle the target request now // If it is a '*' import we remove all previous requests and just use the '*' // Otherwise, ensure '*' isn't already registered and register our request if ( import.Target == "*" ) { throw new NotImplementedException(); //_importRequests.Remove( // mImportRequests.erase(mImportRequests.lower_bound(import->source), // mImportRequests.upper_bound(import->source)); //_importRequests.Add( import.Source, "*" ); } else { throw new NotImplementedException(); // ImportRequestMap::iterator iter = mImportRequests.lower_bound(import->source), // end = mImportRequests.upper_bound(import->source); // if(iter == end || iter->second != "*") //{ // _importRequests.Add( import.Source, import.Target ); //} } #if UNREACHABLE_CODE nodes.RemoveAt( i ); i--; #endif } } // All import nodes are removed // We have cached the code blocks from all the imported scripts // We can process all import requests now foreach ( KeyValuePair<string, IList<AbstractNode>> it in _imports ) { if ( _importRequests.ContainsKey( it.Key ) ) { string j = _importRequests[ it.Key ]; if ( j == "*" ) { // Insert the entire AST into the import table _importTable.InsertRange( 0, it.Value ); continue; // Skip ahead to the next file } else { // Locate this target and insert it into the import table IList<AbstractNode> newNodes = _locateTarget( it.Value, j ); if ( newNodes != null && newNodes.Count > 0 ) _importTable.InsertRange( 0, newNodes ); } } } } /// <summary> /// Handles processing the variables /// </summary> /// <param name="nodes"></param> private void _processVariables( ref IList<AbstractNode> nodes ) { for ( int i = 0; i < nodes.Count; ++i ) { AbstractNode cur = nodes[ i ]; if ( cur is ObjectAbstractNode ) { // Only process if this object is not abstract ObjectAbstractNode obj = (ObjectAbstractNode)cur; if ( !obj.IsAbstract ) { _processVariables( ref obj.Children ); _processVariables( ref obj.Values ); } } else if ( cur is PropertyAbstractNode ) { PropertyAbstractNode prop = (PropertyAbstractNode)cur; _processVariables( ref prop.Values ); } else if ( cur is VariableGetAbstractNode ) { VariableGetAbstractNode var = (VariableGetAbstractNode)cur; // Look up the enclosing scope ObjectAbstractNode scope = null; AbstractNode temp = var.Parent; while ( temp != null ) { if ( temp is ObjectAbstractNode ) { scope = (ObjectAbstractNode)temp; break; } temp = temp.Parent; } // Look up the variable in the environment KeyValuePair<bool, string> varAccess = new KeyValuePair<bool, string>( false, string.Empty ); if ( scope != null ) varAccess = scope.GetVariable( var.Name ); if ( scope == null || !varAccess.Key ) { bool found = _environment.ContainsKey( var.Name ); if ( found ) varAccess = new KeyValuePair<bool, string>( true, _environment[ var.Name ] ); else varAccess = new KeyValuePair<bool, string>( false, varAccess.Value ); } if ( varAccess.Key ) { // Found the variable, so process it and insert it into the tree ScriptLexer lexer = new ScriptLexer(); IList<ScriptToken> tokens = lexer.Tokenize( varAccess.Value, var.File ); ScriptParser parser = new ScriptParser(); IList<ConcreteNode> cst = parser.ParseChunk( tokens ); IList<AbstractNode> ast = _convertToAST( cst ); // Set up ownership for these nodes foreach ( AbstractNode currentNode in ast ) currentNode.Parent = var.Parent; // Recursively handle variable accesses within the variable expansion _processVariables( ref ast ); // Insert the nodes in place of the variable for ( int j = 0; j < ast.Count; j++ ) nodes.Insert( j, ast[ j ] ); } else { // Error AddError( CompileErrorCode.UndefinedVariable, var.File, var.Line ); } // Remove the variable node nodes.RemoveAt( i ); i--; } } } /// <summary> /// Handles object inheritance and variable expansion /// </summary> /// <param name="nodes"></param> /// <param name="top"></param> private void _processObjects( ref IList<AbstractNode> nodes, IList<AbstractNode> top ) { foreach ( AbstractNode node in nodes ) { if ( node is ObjectAbstractNode ) { ObjectAbstractNode obj = (ObjectAbstractNode)node; // Overlay base classes in order. foreach ( string currentBase in obj.Bases ) { // Check the top level first, then check the import table List<AbstractNode> newNodes = _locateTarget( top, currentBase ); if ( newNodes.Count == 0 ) newNodes = _locateTarget( _importTable, currentBase ); if ( newNodes.Count != 0 ) { foreach ( AbstractNode j in newNodes ) _overlayObject( j, obj ); } else { AddError( CompileErrorCode.ObjectBaseNotFound, obj.File, obj.Line ); } } // Recurse into children _processObjects( ref obj.Children, top ); // Overrides now exist in obj's overrides list. These are non-object nodes which must now // Be placed in the children section of the object node such that overriding from parents // into children works properly. for ( int i = 0; i < obj.Overrides.Count; i++ ) obj.Children.Insert( i, obj.Overrides[ i ] ); } } } /// <summary> /// Loads the requested script and converts it to an AST /// </summary> /// <param name="name"></param> /// <returns></returns> private IList<AbstractNode> _loadImportPath( string name ) { IList<AbstractNode> retval = null; IList<ConcreteNode> nodes = null; if ( this.OnImportFile != null ) this.OnImportFile( this, name ); if ( nodes != null && ResourceGroupManager.Instance != null ) { using ( Stream stream = ResourceGroupManager.Instance.OpenResource( name, _resourceGroup ) ) { if ( stream != null ) { ScriptLexer lexer = new ScriptLexer(); ScriptParser parser = new ScriptParser(); IList<ScriptToken> tokens = null; using ( StreamReader reader = new StreamReader( stream ) ) { tokens = lexer.Tokenize( reader.ReadToEnd(), name ); } nodes = parser.Parse( tokens ); } } } if ( nodes != null ) retval = _convertToAST( nodes ); return retval; } /// <summary> /// Returns the abstract nodes from the given tree which represent the target /// </summary> /// <param name="nodes"></param> /// <param name="target"></param> /// <returns></returns> private List<AbstractNode> _locateTarget( IList<AbstractNode> nodes, string target ) { AbstractNode iter = null; // Search for a top-level object node foreach ( AbstractNode node in nodes ) { if ( node is ObjectAbstractNode ) { ObjectAbstractNode impl = (ObjectAbstractNode)node; if ( impl.Name == target ) iter = node; } } List<AbstractNode> newNodes = new List<AbstractNode>(); if ( iter != null ) { newNodes.Add( iter ); } return newNodes; } private void _overlayObject( AbstractNode source, ObjectAbstractNode dest ) { if ( source is ObjectAbstractNode ) { ObjectAbstractNode src = (ObjectAbstractNode)source; // Overlay the environment of one on top the other first foreach ( KeyValuePair<string, string> i in src.Variables ) { KeyValuePair<bool, string> var = dest.GetVariable( i.Key ); if ( !var.Key ) dest.SetVariable( i.Key, i.Value ); } // Create a vector storing each pairing of override between source and destination List<KeyValuePair<AbstractNode, AbstractNode>> overrides = new List<KeyValuePair<AbstractNode, AbstractNode>>(); // A list of indices for each destination node tracks the minimum // source node they can index-match against Dictionary<ObjectAbstractNode, int> indices = new Dictionary<ObjectAbstractNode, int>(); // A map storing which nodes have overridden from the destination node Dictionary<ObjectAbstractNode, bool> overridden = new Dictionary<ObjectAbstractNode, bool>(); // Fill the vector with objects from the source node (base) // And insert non-objects into the overrides list of the destination int insertPos = 0; foreach ( AbstractNode i in src.Children ) { if ( i is ObjectAbstractNode ) { overrides.Add( new KeyValuePair<AbstractNode, AbstractNode>( i, null ) ); } else { AbstractNode newNode = i.Clone(); newNode.Parent = dest; dest.Overrides.Add( newNode ); } } // Track the running maximum override index in the name-matching phase int maxOverrideIndex = 0; // Loop through destination children searching for name-matching overrides for ( int i = 0; i < dest.Children.Count; i++ ) { if ( dest.Children[ i ] is ObjectAbstractNode ) { // Start tracking the override index position for this object int overrideIndex = 0; ObjectAbstractNode node = (ObjectAbstractNode)dest.Children[ i ]; indices[ node ] = maxOverrideIndex; overridden[ node ] = false; // special treatment for materials with * in their name bool nodeHasWildcard = ( !string.IsNullOrEmpty( node.Name ) && node.Name.Contains( "*" ) ); // Find the matching name node for ( int j = 0; j < overrides.Count; ++j ) { ObjectAbstractNode temp = (ObjectAbstractNode)overrides[ j ].Key; // Consider a match a node that has a wildcard and matches an input name bool wildcardMatch = nodeHasWildcard && ( ( new Regex( node.Name ) ).IsMatch( temp.Name ) || ( node.Name.Length == 1 && string.IsNullOrEmpty( temp.Name ) ) ); if ( temp.Cls == node.Cls && !string.IsNullOrEmpty( node.Name ) && ( temp.Name == node.Name || wildcardMatch ) ) { // Pair these two together unless it's already paired if ( overrides[ j ].Value == null ) { int currentIterator = i; ObjectAbstractNode currentNode = node; if ( wildcardMatch ) { //If wildcard is matched, make a copy of current material and put it before the iterator, matching its name to the parent. Use same reinterpret cast as above when node is set AbstractNode newNode = dest.Children[ i ].Clone(); dest.Children.Insert( currentIterator, newNode ); currentNode = (ObjectAbstractNode)dest.Children[ currentIterator ]; currentNode.Name = temp.Name;//make the regex match its matcher } overrides[ j ] = new KeyValuePair<AbstractNode, AbstractNode>( overrides[ j ].Key, dest.Children[ currentIterator ] ); // Store the max override index for this matched pair overrideIndex = j; overrideIndex = maxOverrideIndex = System.Math.Max( overrideIndex, maxOverrideIndex ); indices[ currentNode ] = overrideIndex; overridden[ currentNode ] = true; } else { AddError( CompileErrorCode.DuplicateOverride, node.File, node.Line ); } if ( !wildcardMatch ) break; } } if ( nodeHasWildcard ) { //if the node has a wildcard it will be deleted since it was duplicated for every match dest.Children.RemoveAt( i ); i--; } } } // Now make matches based on index // Loop through destination children searching for name-matching overrides foreach ( AbstractNode i in dest.Children ) { if ( i is ObjectAbstractNode ) { ObjectAbstractNode node = (ObjectAbstractNode)i; if ( !overridden[ node ] ) { // Retrieve the minimum override index from the map int overrideIndex = indices[ node ]; if ( overrideIndex < overrides.Count ) { // Search for minimum matching override for ( int j = overrideIndex; j < overrides.Count; ++j ) { ObjectAbstractNode temp = (ObjectAbstractNode)overrides[ j ].Key; if ( string.IsNullOrEmpty( temp.Name ) && temp.Cls == node.Cls && overrides[ j ].Value == null ) { overrides[ j ] = new KeyValuePair<AbstractNode, AbstractNode>( overrides[ j ].Key, i ); break; } } } } } } // Loop through overrides, either inserting source nodes or overriding for ( int i = 0; i < overrides.Count; ++i ) { if ( overrides[ i ].Value != null ) { // Override the destination with the source (base) object _overlayObject( overrides[ i ].Key, (ObjectAbstractNode)overrides[ i ].Value ); insertPos = dest.Children.IndexOf( overrides[ i ].Value ); insertPos++; } else { // No override was possible, so insert this node at the insert position // into the destination (child) object AbstractNode newNode = overrides[ i ].Key.Clone(); newNode.Parent = dest; if ( insertPos != dest.Children.Count - 1 ) { dest.Children.Insert( insertPos, newNode ); } else { dest.Children.Add( newNode ); } } } } } private void InitializeWordMap() { _keywordMap[ "on" ] = (uint)BuiltIn.ID_ON; _keywordMap[ "off" ] = (uint)BuiltIn.ID_OFF; _keywordMap[ "true" ] = (uint)BuiltIn.ID_TRUE; _keywordMap[ "false" ] = (uint)BuiltIn.ID_FALSE; _keywordMap[ "yes" ] = (uint)BuiltIn.ID_YES; _keywordMap[ "no" ] = (uint)BuiltIn.ID_NO; // Material ids _keywordMap[ "material" ] = (uint)Keywords.ID_MATERIAL; _keywordMap[ "vertex_program" ] = (uint)Keywords.ID_VERTEX_PROGRAM; _keywordMap[ "geometry_program" ] = (uint)Keywords.ID_GEOMETRY_PROGRAM; _keywordMap[ "fragment_program" ] = (uint)Keywords.ID_FRAGMENT_PROGRAM; _keywordMap[ "technique" ] = (uint)Keywords.ID_TECHNIQUE; _keywordMap[ "pass" ] = (uint)Keywords.ID_PASS; _keywordMap[ "texture_unit" ] = (uint)Keywords.ID_TEXTURE_UNIT; _keywordMap[ "vertex_program_ref" ] = (uint)Keywords.ID_VERTEX_PROGRAM_REF; _keywordMap[ "geometry_program_ref" ] = (uint)Keywords.ID_GEOMETRY_PROGRAM_REF; _keywordMap[ "fragment_program_ref" ] = (uint)Keywords.ID_FRAGMENT_PROGRAM_REF; _keywordMap[ "shadow_caster_vertex_program_ref" ] = (uint)Keywords.ID_SHADOW_CASTER_VERTEX_PROGRAM_REF; _keywordMap[ "shadow_receiver_vertex_program_ref" ] = (uint)Keywords.ID_SHADOW_RECEIVER_VERTEX_PROGRAM_REF; _keywordMap[ "shadow_receiver_fragment_program_ref" ] = (uint)Keywords.ID_SHADOW_RECEIVER_FRAGMENT_PROGRAM_REF; _keywordMap[ "lod_values" ] = (uint)Keywords.ID_LOD_VALUES; _keywordMap[ "lod_strategy" ] = (uint)Keywords.ID_LOD_STRATEGY; _keywordMap[ "lod_distances" ] = (uint)Keywords.ID_LOD_DISTANCES; _keywordMap[ "receive_shadows" ] = (uint)Keywords.ID_RECEIVE_SHADOWS; _keywordMap[ "transparency_casts_shadows" ] = (uint)Keywords.ID_TRANSPARENCY_CASTS_SHADOWS; _keywordMap[ "set_texture_alias" ] = (uint)Keywords.ID_SET_TEXTURE_ALIAS; _keywordMap[ "source" ] = (uint)Keywords.ID_SOURCE; _keywordMap[ "syntax" ] = (uint)Keywords.ID_SYNTAX; _keywordMap[ "default_params" ] = (uint)Keywords.ID_DEFAULT_PARAMS; _keywordMap[ "param_indexed" ] = (uint)Keywords.ID_PARAM_INDEXED; _keywordMap[ "param_named" ] = (uint)Keywords.ID_PARAM_NAMED; _keywordMap[ "param_indexed_auto" ] = (uint)Keywords.ID_PARAM_INDEXED_AUTO; _keywordMap[ "param_named_auto" ] = (uint)Keywords.ID_PARAM_NAMED_AUTO; _keywordMap[ "scheme" ] = (uint)Keywords.ID_SCHEME; _keywordMap[ "lod_index" ] = (uint)Keywords.ID_LOD_INDEX; _keywordMap[ "shadow_caster_material" ] = (uint)Keywords.ID_SHADOW_CASTER_MATERIAL; _keywordMap[ "shadow_receiver_material" ] = (uint)Keywords.ID_SHADOW_RECEIVER_MATERIAL; _keywordMap[ "gpu_vendor_rule" ] = (uint)Keywords.ID_GPU_VENDOR_RULE; _keywordMap[ "gpu_device_rule" ] = (uint)Keywords.ID_GPU_DEVICE_RULE; _keywordMap[ "include" ] = (uint)Keywords.ID_INCLUDE; _keywordMap[ "exclude" ] = (uint)Keywords.ID_EXCLUDE; _keywordMap[ "ambient" ] = (uint)Keywords.ID_AMBIENT; _keywordMap[ "diffuse" ] = (uint)Keywords.ID_DIFFUSE; _keywordMap[ "specular" ] = (uint)Keywords.ID_SPECULAR; _keywordMap[ "emissive" ] = (uint)Keywords.ID_EMISSIVE; _keywordMap[ "vertexcolour" ] = (uint)Keywords.ID_VERTEX_COLOUR; _keywordMap[ "scene_blend" ] = (uint)Keywords.ID_SCENE_BLEND; _keywordMap[ "colour_blend" ] = (uint)Keywords.ID_COLOUR_BLEND; _keywordMap[ "one" ] = (uint)Keywords.ID_ONE; _keywordMap[ "zero" ] = (uint)Keywords.ID_ZERO; _keywordMap[ "dest_colour" ] = (uint)Keywords.ID_DEST_COLOUR; _keywordMap[ "src_colour" ] = (uint)Keywords.ID_SRC_COLOUR; _keywordMap[ "one_minus_src_colour" ] = (uint)Keywords.ID_ONE_MINUS_SRC_COLOUR; _keywordMap[ "one_minus_dest_colour" ] = (uint)Keywords.ID_ONE_MINUS_DEST_COLOUR; _keywordMap[ "dest_alpha" ] = (uint)Keywords.ID_DEST_ALPHA; _keywordMap[ "src_alpha" ] = (uint)Keywords.ID_SRC_ALPHA; _keywordMap[ "one_minus_dest_alpha" ] = (uint)Keywords.ID_ONE_MINUS_DEST_ALPHA; _keywordMap[ "one_minus_src_alpha" ] = (uint)Keywords.ID_ONE_MINUS_SRC_ALPHA; _keywordMap[ "separate_scene_blend" ] = (uint)Keywords.ID_SEPARATE_SCENE_BLEND; _keywordMap[ "scene_blend_op" ] = (uint)Keywords.ID_SCENE_BLEND_OP; _keywordMap[ "reverse_subtract" ] = (uint)Keywords.ID_REVERSE_SUBTRACT; _keywordMap[ "min" ] = (uint)Keywords.ID_MIN; _keywordMap[ "max" ] = (uint)Keywords.ID_MAX; _keywordMap[ "separate_scene_blend_op" ] = (uint)Keywords.ID_SEPARATE_SCENE_BLEND_OP; _keywordMap[ "depth_check" ] = (uint)Keywords.ID_DEPTH_CHECK; _keywordMap[ "depth_write" ] = (uint)Keywords.ID_DEPTH_WRITE; _keywordMap[ "depth_func" ] = (uint)Keywords.ID_DEPTH_FUNC; _keywordMap[ "depth_bias" ] = (uint)Keywords.ID_DEPTH_BIAS; _keywordMap[ "iteration_depth_bias" ] = (uint)Keywords.ID_ITERATION_DEPTH_BIAS; _keywordMap[ "always_fail" ] = (uint)Keywords.ID_ALWAYS_FAIL; _keywordMap[ "always_pass" ] = (uint)Keywords.ID_ALWAYS_PASS; _keywordMap[ "less_equal" ] = (uint)Keywords.ID_LESS_EQUAL; _keywordMap[ "less" ] = (uint)Keywords.ID_LESS; _keywordMap[ "equal" ] = (uint)Keywords.ID_EQUAL; _keywordMap[ "not_equal" ] = (uint)Keywords.ID_NOT_EQUAL; _keywordMap[ "greater_equal" ] = (uint)Keywords.ID_GREATER_EQUAL; _keywordMap[ "greater" ] = (uint)Keywords.ID_GREATER; _keywordMap[ "alpha_rejection" ] = (uint)Keywords.ID_ALPHA_REJECTION; _keywordMap[ "alpha_to_coverage" ] = (uint)Keywords.ID_ALPHA_TO_COVERAGE; _keywordMap[ "light_scissor" ] = (uint)Keywords.ID_LIGHT_SCISSOR; _keywordMap[ "light_clip_planes" ] = (uint)Keywords.ID_LIGHT_CLIP_PLANES; _keywordMap[ "transparent_sorting" ] = (uint)Keywords.ID_TRANSPARENT_SORTING; _keywordMap[ "illumination_stage" ] = (uint)Keywords.ID_ILLUMINATION_STAGE; _keywordMap[ "decal" ] = (uint)Keywords.ID_DECAL; _keywordMap[ "cull_hardware" ] = (uint)Keywords.ID_CULL_HARDWARE; _keywordMap[ "clockwise" ] = (uint)Keywords.ID_CLOCKWISE; _keywordMap[ "anticlockwise" ] = (uint)Keywords.ID_ANTICLOCKWISE; _keywordMap[ "cull_software" ] = (uint)Keywords.ID_CULL_SOFTWARE; _keywordMap[ "back" ] = (uint)Keywords.ID_BACK; _keywordMap[ "front" ] = (uint)Keywords.ID_FRONT; _keywordMap[ "normalise_normals" ] = (uint)Keywords.ID_NORMALISE_NORMALS; _keywordMap[ "lighting" ] = (uint)Keywords.ID_LIGHTING; _keywordMap[ "shading" ] = (uint)Keywords.ID_SHADING; _keywordMap[ "flat" ] = (uint)Keywords.ID_FLAT; _keywordMap[ "gouraud" ] = (uint)Keywords.ID_GOURAUD; _keywordMap[ "phong" ] = (uint)Keywords.ID_PHONG; _keywordMap[ "polygon_mode" ] = (uint)Keywords.ID_POLYGON_MODE; _keywordMap[ "solid" ] = (uint)Keywords.ID_SOLID; _keywordMap[ "wireframe" ] = (uint)Keywords.ID_WIREFRAME; _keywordMap[ "points" ] = (uint)Keywords.ID_POINTS; _keywordMap[ "polygon_mode_overrideable" ] = (uint)Keywords.ID_POLYGON_MODE_OVERRIDEABLE; _keywordMap[ "fog_override" ] = (uint)Keywords.ID_FOG_OVERRIDE; _keywordMap[ "none" ] = (uint)Keywords.ID_NONE; _keywordMap[ "linear" ] = (uint)Keywords.ID_LINEAR; _keywordMap[ "exp" ] = (uint)Keywords.ID_EXP; _keywordMap[ "exp2" ] = (uint)Keywords.ID_EXP2; _keywordMap[ "colour_write" ] = (uint)Keywords.ID_COLOUR_WRITE; _keywordMap[ "max_lights" ] = (uint)Keywords.ID_MAX_LIGHTS; _keywordMap[ "start_light" ] = (uint)Keywords.ID_START_LIGHT; _keywordMap[ "iteration" ] = (uint)Keywords.ID_ITERATION; _keywordMap[ "once" ] = (uint)Keywords.ID_ONCE; _keywordMap[ "once_per_light" ] = (uint)Keywords.ID_ONCE_PER_LIGHT; _keywordMap[ "per_n_lights" ] = (uint)Keywords.ID_PER_N_LIGHTS; _keywordMap[ "per_light" ] = (uint)Keywords.ID_PER_LIGHT; _keywordMap[ "point" ] = (uint)Keywords.ID_POINT; _keywordMap[ "spot" ] = (uint)Keywords.ID_SPOT; _keywordMap[ "directional" ] = (uint)Keywords.ID_DIRECTIONAL; _keywordMap[ "point_size" ] = (uint)Keywords.ID_POINT_SIZE; _keywordMap[ "point_sprites" ] = (uint)Keywords.ID_POINT_SPRITES; _keywordMap[ "point_size_min" ] = (uint)Keywords.ID_POINT_SIZE_MIN; _keywordMap[ "point_size_max" ] = (uint)Keywords.ID_POINT_SIZE_MAX; _keywordMap[ "point_size_attenuation" ] = (uint)Keywords.ID_POINT_SIZE_ATTENUATION; _keywordMap[ "texture_alias" ] = (uint)Keywords.ID_TEXTURE_ALIAS; _keywordMap[ "texture" ] = (uint)Keywords.ID_TEXTURE; _keywordMap[ "1d" ] = (uint)Keywords.ID_1D; _keywordMap[ "2d" ] = (uint)Keywords.ID_2D; _keywordMap[ "3d" ] = (uint)Keywords.ID_3D; _keywordMap[ "cubic" ] = (uint)Keywords.ID_CUBIC; _keywordMap[ "unlimited" ] = (uint)Keywords.ID_UNLIMITED; _keywordMap[ "alpha" ] = (uint)Keywords.ID_ALPHA; _keywordMap[ "gamma" ] = (uint)Keywords.ID_GAMMA; _keywordMap[ "anim_texture" ] = (uint)Keywords.ID_ANIM_TEXTURE; _keywordMap[ "cubic_texture" ] = (uint)Keywords.ID_CUBIC_TEXTURE; _keywordMap[ "separateUV" ] = (uint)Keywords.ID_SEPARATE_UV; _keywordMap[ "combinedUVW" ] = (uint)Keywords.ID_COMBINED_UVW; _keywordMap[ "tex_coord_set" ] = (uint)Keywords.ID_TEX_COORD_SET; _keywordMap[ "tex_address_mode" ] = (uint)Keywords.ID_TEX_ADDRESS_MODE; _keywordMap[ "wrap" ] = (uint)Keywords.ID_WRAP; _keywordMap[ "clamp" ] = (uint)Keywords.ID_CLAMP; _keywordMap[ "mirror" ] = (uint)Keywords.ID_MIRROR; _keywordMap[ "border" ] = (uint)Keywords.ID_BORDER; _keywordMap[ "tex_border_colour" ] = (uint)Keywords.ID_TEX_BORDER_COLOUR; _keywordMap[ "filtering" ] = (uint)Keywords.ID_FILTERING; _keywordMap[ "bilinear" ] = (uint)Keywords.ID_BILINEAR; _keywordMap[ "trilinear" ] = (uint)Keywords.ID_TRILINEAR; _keywordMap[ "anisotropic" ] = (uint)Keywords.ID_ANISOTROPIC; _keywordMap[ "max_anisotropy" ] = (uint)Keywords.ID_MAX_ANISOTROPY; _keywordMap[ "mipmap_bias" ] = (uint)Keywords.ID_MIPMAP_BIAS; _keywordMap[ "colour_op" ] = (uint)Keywords.ID_COLOUR_OP; _keywordMap[ "replace" ] = (uint)Keywords.ID_REPLACE; _keywordMap[ "add" ] = (uint)Keywords.ID_ADD; _keywordMap[ "modulate" ] = (uint)Keywords.ID_MODULATE; _keywordMap[ "alpha_blend" ] = (uint)Keywords.ID_ALPHA_BLEND; _keywordMap[ "colour_op_ex" ] = (uint)Keywords.ID_COLOUR_OP_EX; _keywordMap[ "source1" ] = (uint)Keywords.ID_SOURCE1; _keywordMap[ "source2" ] = (uint)Keywords.ID_SOURCE2; _keywordMap[ "modulate" ] = (uint)Keywords.ID_MODULATE; _keywordMap[ "modulate_x2" ] = (uint)Keywords.ID_MODULATE_X2; _keywordMap[ "modulate_x4" ] = (uint)Keywords.ID_MODULATE_X4; _keywordMap[ "add" ] = (uint)Keywords.ID_ADD; _keywordMap[ "add_signed" ] = (uint)Keywords.ID_ADD_SIGNED; _keywordMap[ "add_smooth" ] = (uint)Keywords.ID_ADD_SMOOTH; _keywordMap[ "subtract" ] = (uint)Keywords.ID_SUBTRACT; _keywordMap[ "blend_diffuse_alpha" ] = (uint)Keywords.ID_BLEND_DIFFUSE_ALPHA; _keywordMap[ "blend_texture_alpha" ] = (uint)Keywords.ID_BLEND_TEXTURE_ALPHA; _keywordMap[ "blend_current_alpha" ] = (uint)Keywords.ID_BLEND_CURRENT_ALPHA; _keywordMap[ "blend_manual" ] = (uint)Keywords.ID_BLEND_MANUAL; _keywordMap[ "dotproduct" ] = (uint)Keywords.ID_DOT_PRODUCT; _keywordMap[ "blend_diffuse_colour" ] = (uint)Keywords.ID_BLEND_DIFFUSE_COLOUR; _keywordMap[ "src_current" ] = (uint)Keywords.ID_SRC_CURRENT; _keywordMap[ "src_texture" ] = (uint)Keywords.ID_SRC_TEXTURE; _keywordMap[ "src_diffuse" ] = (uint)Keywords.ID_SRC_DIFFUSE; _keywordMap[ "src_specular" ] = (uint)Keywords.ID_SRC_SPECULAR; _keywordMap[ "src_manual" ] = (uint)Keywords.ID_SRC_MANUAL; _keywordMap[ "colour_op_multipass_fallback" ] = (uint)Keywords.ID_COLOUR_OP_MULTIPASS_FALLBACK; _keywordMap[ "alpha_op_ex" ] = (uint)Keywords.ID_ALPHA_OP_EX; _keywordMap[ "env_map" ] = (uint)Keywords.ID_ENV_MAP; _keywordMap[ "spherical" ] = (uint)Keywords.ID_SPHERICAL; _keywordMap[ "planar" ] = (uint)Keywords.ID_PLANAR; _keywordMap[ "cubic_reflection" ] = (uint)Keywords.ID_CUBIC_REFLECTION; _keywordMap[ "cubic_normal" ] = (uint)Keywords.ID_CUBIC_NORMAL; _keywordMap[ "scroll" ] = (uint)Keywords.ID_SCROLL; _keywordMap[ "scroll_anim" ] = (uint)Keywords.ID_SCROLL_ANIM; _keywordMap[ "rotate" ] = (uint)Keywords.ID_ROTATE; _keywordMap[ "rotate_anim" ] = (uint)Keywords.ID_ROTATE_ANIM; _keywordMap[ "scale" ] = (uint)Keywords.ID_SCALE; _keywordMap[ "wave_xform" ] = (uint)Keywords.ID_WAVE_XFORM; _keywordMap[ "scroll_x" ] = (uint)Keywords.ID_SCROLL_X; _keywordMap[ "scroll_y" ] = (uint)Keywords.ID_SCROLL_Y; _keywordMap[ "scale_x" ] = (uint)Keywords.ID_SCALE_X; _keywordMap[ "scale_y" ] = (uint)Keywords.ID_SCALE_Y; _keywordMap[ "sine" ] = (uint)Keywords.ID_SINE; _keywordMap[ "triangle" ] = (uint)Keywords.ID_TRIANGLE; _keywordMap[ "sawtooth" ] = (uint)Keywords.ID_SAWTOOTH; _keywordMap[ "square" ] = (uint)Keywords.ID_SQUARE; _keywordMap[ "inverse_sawtooth" ] = (uint)Keywords.ID_INVERSE_SAWTOOTH; _keywordMap[ "transform" ] = (uint)Keywords.ID_TRANSFORM; _keywordMap[ "binding_type" ] = (uint)Keywords.ID_BINDING_TYPE; _keywordMap[ "vertex" ] = (uint)Keywords.ID_VERTEX; _keywordMap[ "fragment" ] = (uint)Keywords.ID_FRAGMENT; _keywordMap[ "content_type" ] = (uint)Keywords.ID_CONTENT_TYPE; _keywordMap[ "named" ] = (uint)Keywords.ID_NAMED; _keywordMap[ "shadow" ] = (uint)Keywords.ID_SHADOW; _keywordMap[ "texture_source" ] = (uint)Keywords.ID_TEXTURE_SOURCE; _keywordMap[ "shared_params" ] = (uint)Keywords.ID_SHARED_PARAMS; _keywordMap[ "shared_param_named" ] = (uint)Keywords.ID_SHARED_PARAM_NAMED; _keywordMap[ "shared_params_ref" ] = (uint)Keywords.ID_SHARED_PARAMS_REF; // Particle system _keywordMap[ "particle_system" ] = (uint)Keywords.ID_PARTICLE_SYSTEM; _keywordMap[ "emitter" ] = (uint)Keywords.ID_EMITTER; _keywordMap[ "affector" ] = (uint)Keywords.ID_AFFECTOR; // Compositor _keywordMap[ "compositor" ] = (uint)Keywords.ID_COMPOSITOR; _keywordMap[ "target" ] = (uint)Keywords.ID_TARGET; _keywordMap[ "target_output" ] = (uint)Keywords.ID_TARGET_OUTPUT; _keywordMap[ "input" ] = (uint)Keywords.ID_INPUT; _keywordMap[ "none" ] = (uint)Keywords.ID_NONE; _keywordMap[ "previous" ] = (uint)Keywords.ID_PREVIOUS; _keywordMap[ "target_width" ] = (uint)Keywords.ID_TARGET_WIDTH; _keywordMap[ "target_height" ] = (uint)Keywords.ID_TARGET_HEIGHT; _keywordMap[ "target_width_scaled" ] = (uint)Keywords.ID_TARGET_WIDTH_SCALED; _keywordMap[ "target_height_scaled" ] = (uint)Keywords.ID_TARGET_HEIGHT_SCALED; _keywordMap[ "pooled" ] = (uint)Keywords.ID_POOLED; //mIds["gamma"] = ID_GAMMA; - already registered _keywordMap[ "no_fsaa" ] = (uint)Keywords.ID_NO_FSAA; _keywordMap[ "texture_ref" ] = (uint)Keywords.ID_TEXTURE_REF; _keywordMap[ "local_scope" ] = (uint)Keywords.ID_SCOPE_LOCAL; _keywordMap[ "chain_scope" ] = (uint)Keywords.ID_SCOPE_CHAIN; _keywordMap[ "global_scope" ] = (uint)Keywords.ID_SCOPE_GLOBAL; _keywordMap[ "compositor_logic" ] = (uint)Keywords.ID_COMPOSITOR_LOGIC; _keywordMap[ "only_initial" ] = (uint)Keywords.ID_ONLY_INITIAL; _keywordMap[ "visibility_mask" ] = (uint)Keywords.ID_VISIBILITY_MASK; _keywordMap[ "lod_bias" ] = (uint)Keywords.ID_LOD_BIAS; _keywordMap[ "material_scheme" ] = (uint)Keywords.ID_MATERIAL_SCHEME; _keywordMap[ "shadows" ] = (uint)Keywords.ID_SHADOWS_ENABLED; _keywordMap[ "clear" ] = (uint)Keywords.ID_CLEAR; _keywordMap[ "stencil" ] = (uint)Keywords.ID_STENCIL; _keywordMap[ "render_scene" ] = (uint)Keywords.ID_RENDER_SCENE; _keywordMap[ "render_quad" ] = (uint)Keywords.ID_RENDER_QUAD; _keywordMap[ "identifier" ] = (uint)Keywords.ID_IDENTIFIER; _keywordMap[ "first_render_queue" ] = (uint)Keywords.ID_FIRST_RENDER_QUEUE; _keywordMap[ "last_render_queue" ] = (uint)Keywords.ID_LAST_RENDER_QUEUE; _keywordMap[ "quad_normals" ] = (uint)Keywords.ID_QUAD_NORMALS; _keywordMap[ "camera_far_corners_view_space" ] = (uint)Keywords.ID_CAMERA_FAR_CORNERS_VIEW_SPACE; _keywordMap[ "camera_far_corners_world_space" ] = (uint)Keywords.ID_CAMERA_FAR_CORNERS_WORLD_SPACE; _keywordMap[ "buffers" ] = (uint)Keywords.ID_BUFFERS; _keywordMap[ "colour" ] = (uint)Keywords.ID_COLOUR; _keywordMap[ "depth" ] = (uint)Keywords.ID_DEPTH; _keywordMap[ "colour_value" ] = (uint)Keywords.ID_COLOUR_VALUE; _keywordMap[ "depth_value" ] = (uint)Keywords.ID_DEPTH_VALUE; _keywordMap[ "stencil_value" ] = (uint)Keywords.ID_STENCIL_VALUE; _keywordMap[ "check" ] = (uint)Keywords.ID_CHECK; _keywordMap[ "comp_func" ] = (uint)Keywords.ID_COMP_FUNC; _keywordMap[ "ref_value" ] = (uint)Keywords.ID_REF_VALUE; _keywordMap[ "mask" ] = (uint)Keywords.ID_MASK; _keywordMap[ "fail_op" ] = (uint)Keywords.ID_FAIL_OP; _keywordMap[ "keep" ] = (uint)Keywords.ID_KEEP; _keywordMap[ "increment" ] = (uint)Keywords.ID_INCREMENT; _keywordMap[ "decrement" ] = (uint)Keywords.ID_DECREMENT; _keywordMap[ "increment_wrap" ] = (uint)Keywords.ID_INCREMENT_WRAP; _keywordMap[ "decrement_wrap" ] = (uint)Keywords.ID_DECREMENT_WRAP; _keywordMap[ "invert" ] = (uint)Keywords.ID_INVERT; _keywordMap[ "depth_fail_op" ] = (uint)Keywords.ID_DEPTH_FAIL_OP; _keywordMap[ "pass_op" ] = (uint)Keywords.ID_PASS_OP; _keywordMap[ "two_sided" ] = (uint)Keywords.ID_TWO_SIDED; } } }
mono-soc-2011/axiom
Projects/Axiom/Engine/Scripting/Compiler/ScriptCompiler.cs
C#
lgpl-2.1
44,720
# -*- Mode: Python; py-indent-offset: 4 -*- # coding=utf-8 # vim: tabstop=4 shiftwidth=4 expandtab import sys import unittest import tempfile import shutil import os import locale import subprocess from gi.repository import GObject import gobject from gi.repository import GIMarshallingTests from compathelper import _bytes if sys.version_info < (3, 0): CONSTANT_UTF8 = "const \xe2\x99\xa5 utf8" PY2_UNICODE_UTF8 = unicode(CONSTANT_UTF8, 'UTF-8') CHAR_255='\xff' else: CONSTANT_UTF8 = "const ♥ utf8" CHAR_255=bytes([255]) CONSTANT_NUMBER = 42 class Number(object): def __init__(self, value): self.value = value def __int__(self): return int(self.value) def __float__(self): return float(self.value) class Sequence(object): def __init__(self, sequence): self.sequence = sequence def __len__(self): return len(self.sequence) def __getitem__(self, key): return self.sequence[key] class TestConstant(unittest.TestCase): # Blocked by https://bugzilla.gnome.org/show_bug.cgi?id=595773 # def test_constant_utf8(self): # self.assertEquals(CONSTANT_UTF8, GIMarshallingTests.CONSTANT_UTF8) def test_constant_number(self): self.assertEquals(CONSTANT_NUMBER, GIMarshallingTests.CONSTANT_NUMBER) class TestBoolean(unittest.TestCase): def test_boolean_return(self): self.assertEquals(True, GIMarshallingTests.boolean_return_true()) self.assertEquals(False, GIMarshallingTests.boolean_return_false()) def test_boolean_in(self): GIMarshallingTests.boolean_in_true(True) GIMarshallingTests.boolean_in_false(False) GIMarshallingTests.boolean_in_true(1) GIMarshallingTests.boolean_in_false(0) def test_boolean_out(self): self.assertEquals(True, GIMarshallingTests.boolean_out_true()) self.assertEquals(False, GIMarshallingTests.boolean_out_false()) def test_boolean_inout(self): self.assertEquals(False, GIMarshallingTests.boolean_inout_true_false(True)) self.assertEquals(True, GIMarshallingTests.boolean_inout_false_true(False)) class TestInt8(unittest.TestCase): MAX = GObject.G_MAXINT8 MIN = GObject.G_MININT8 def test_int8_return(self): self.assertEquals(self.MAX, GIMarshallingTests.int8_return_max()) self.assertEquals(self.MIN, GIMarshallingTests.int8_return_min()) def test_int8_in(self): max = Number(self.MAX) min = Number(self.MIN) GIMarshallingTests.int8_in_max(max) GIMarshallingTests.int8_in_min(min) max.value += 1 min.value -= 1 self.assertRaises(ValueError, GIMarshallingTests.int8_in_max, max) self.assertRaises(ValueError, GIMarshallingTests.int8_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.int8_in_max, "self.MAX") def test_int8_out(self): self.assertEquals(self.MAX, GIMarshallingTests.int8_out_max()) self.assertEquals(self.MIN, GIMarshallingTests.int8_out_min()) def test_int8_inout(self): self.assertEquals(self.MIN, GIMarshallingTests.int8_inout_max_min(Number(self.MAX))) self.assertEquals(self.MAX, GIMarshallingTests.int8_inout_min_max(Number(self.MIN))) class TestUInt8(unittest.TestCase): MAX = GObject.G_MAXUINT8 def test_uint8_return(self): self.assertEquals(self.MAX, GIMarshallingTests.uint8_return()) def test_uint8_in(self): number = Number(self.MAX) GIMarshallingTests.uint8_in(number) GIMarshallingTests.uint8_in(CHAR_255) number.value += 1 self.assertRaises(ValueError, GIMarshallingTests.uint8_in, number) self.assertRaises(ValueError, GIMarshallingTests.uint8_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.uint8_in, "self.MAX") def test_uint8_out(self): self.assertEquals(self.MAX, GIMarshallingTests.uint8_out()) def test_uint8_inout(self): self.assertEquals(0, GIMarshallingTests.uint8_inout(Number(self.MAX))) class TestInt16(unittest.TestCase): MAX = GObject.G_MAXINT16 MIN = GObject.G_MININT16 def test_int16_return(self): self.assertEquals(self.MAX, GIMarshallingTests.int16_return_max()) self.assertEquals(self.MIN, GIMarshallingTests.int16_return_min()) def test_int16_in(self): max = Number(self.MAX) min = Number(self.MIN) GIMarshallingTests.int16_in_max(max) GIMarshallingTests.int16_in_min(min) max.value += 1 min.value -= 1 self.assertRaises(ValueError, GIMarshallingTests.int16_in_max, max) self.assertRaises(ValueError, GIMarshallingTests.int16_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.int16_in_max, "self.MAX") def test_int16_out(self): self.assertEquals(self.MAX, GIMarshallingTests.int16_out_max()) self.assertEquals(self.MIN, GIMarshallingTests.int16_out_min()) def test_int16_inout(self): self.assertEquals(self.MIN, GIMarshallingTests.int16_inout_max_min(Number(self.MAX))) self.assertEquals(self.MAX, GIMarshallingTests.int16_inout_min_max(Number(self.MIN))) class TestUInt16(unittest.TestCase): MAX = GObject.G_MAXUINT16 def test_uint16_return(self): self.assertEquals(self.MAX, GIMarshallingTests.uint16_return()) def test_uint16_in(self): number = Number(self.MAX) GIMarshallingTests.uint16_in(number) number.value += 1 self.assertRaises(ValueError, GIMarshallingTests.uint16_in, number) self.assertRaises(ValueError, GIMarshallingTests.uint16_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.uint16_in, "self.MAX") def test_uint16_out(self): self.assertEquals(self.MAX, GIMarshallingTests.uint16_out()) def test_uint16_inout(self): self.assertEquals(0, GIMarshallingTests.uint16_inout(Number(self.MAX))) class TestInt32(unittest.TestCase): MAX = GObject.G_MAXINT32 MIN = GObject.G_MININT32 def test_int32_return(self): self.assertEquals(self.MAX, GIMarshallingTests.int32_return_max()) self.assertEquals(self.MIN, GIMarshallingTests.int32_return_min()) def test_int32_in(self): max = Number(self.MAX) min = Number(self.MIN) GIMarshallingTests.int32_in_max(max) GIMarshallingTests.int32_in_min(min) max.value += 1 min.value -= 1 self.assertRaises(ValueError, GIMarshallingTests.int32_in_max, max) self.assertRaises(ValueError, GIMarshallingTests.int32_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.int32_in_max, "self.MAX") def test_int32_out(self): self.assertEquals(self.MAX, GIMarshallingTests.int32_out_max()) self.assertEquals(self.MIN, GIMarshallingTests.int32_out_min()) def test_int32_inout(self): self.assertEquals(self.MIN, GIMarshallingTests.int32_inout_max_min(Number(self.MAX))) self.assertEquals(self.MAX, GIMarshallingTests.int32_inout_min_max(Number(self.MIN))) class TestUInt32(unittest.TestCase): MAX = GObject.G_MAXUINT32 def test_uint32_return(self): self.assertEquals(self.MAX, GIMarshallingTests.uint32_return()) def test_uint32_in(self): number = Number(self.MAX) GIMarshallingTests.uint32_in(number) number.value += 1 self.assertRaises(ValueError, GIMarshallingTests.uint32_in, number) self.assertRaises(ValueError, GIMarshallingTests.uint32_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.uint32_in, "self.MAX") def test_uint32_out(self): self.assertEquals(self.MAX, GIMarshallingTests.uint32_out()) def test_uint32_inout(self): self.assertEquals(0, GIMarshallingTests.uint32_inout(Number(self.MAX))) class TestInt64(unittest.TestCase): MAX = 2 ** 63 - 1 MIN = - (2 ** 63) def test_int64_return(self): self.assertEquals(self.MAX, GIMarshallingTests.int64_return_max()) self.assertEquals(self.MIN, GIMarshallingTests.int64_return_min()) def test_int64_in(self): max = Number(self.MAX) min = Number(self.MIN) GIMarshallingTests.int64_in_max(max) GIMarshallingTests.int64_in_min(min) max.value += 1 min.value -= 1 self.assertRaises(ValueError, GIMarshallingTests.int64_in_max, max) self.assertRaises(ValueError, GIMarshallingTests.int64_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.int64_in_max, "self.MAX") def test_int64_out(self): self.assertEquals(self.MAX, GIMarshallingTests.int64_out_max()) self.assertEquals(self.MIN, GIMarshallingTests.int64_out_min()) def test_int64_inout(self): self.assertEquals(self.MIN, GIMarshallingTests.int64_inout_max_min(Number(self.MAX))) self.assertEquals(self.MAX, GIMarshallingTests.int64_inout_min_max(Number(self.MIN))) class TestUInt64(unittest.TestCase): MAX = 2 ** 64 - 1 def test_uint64_return(self): self.assertEquals(self.MAX, GIMarshallingTests.uint64_return()) def test_uint64_in(self): number = Number(self.MAX) GIMarshallingTests.uint64_in(number) number.value += 1 self.assertRaises(ValueError, GIMarshallingTests.uint64_in, number) self.assertRaises(ValueError, GIMarshallingTests.uint64_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.uint64_in, "self.MAX") def test_uint64_out(self): self.assertEquals(self.MAX, GIMarshallingTests.uint64_out()) def test_uint64_inout(self): self.assertEquals(0, GIMarshallingTests.uint64_inout(Number(self.MAX))) class TestShort(unittest.TestCase): MAX = GObject.constants.G_MAXSHORT MIN = GObject.constants.G_MINSHORT def test_short_return(self): self.assertEquals(self.MAX, GIMarshallingTests.short_return_max()) self.assertEquals(self.MIN, GIMarshallingTests.short_return_min()) def test_short_in(self): max = Number(self.MAX) min = Number(self.MIN) GIMarshallingTests.short_in_max(max) GIMarshallingTests.short_in_min(min) max.value += 1 min.value -= 1 self.assertRaises(ValueError, GIMarshallingTests.short_in_max, max) self.assertRaises(ValueError, GIMarshallingTests.short_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.short_in_max, "self.MAX") def test_short_out(self): self.assertEquals(self.MAX, GIMarshallingTests.short_out_max()) self.assertEquals(self.MIN, GIMarshallingTests.short_out_min()) def test_short_inout(self): self.assertEquals(self.MIN, GIMarshallingTests.short_inout_max_min(Number(self.MAX))) self.assertEquals(self.MAX, GIMarshallingTests.short_inout_min_max(Number(self.MIN))) class TestUShort(unittest.TestCase): MAX = GObject.constants.G_MAXUSHORT def test_ushort_return(self): self.assertEquals(self.MAX, GIMarshallingTests.ushort_return()) def test_ushort_in(self): number = Number(self.MAX) GIMarshallingTests.ushort_in(number) number.value += 1 self.assertRaises(ValueError, GIMarshallingTests.ushort_in, number) self.assertRaises(ValueError, GIMarshallingTests.ushort_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.ushort_in, "self.MAX") def test_ushort_out(self): self.assertEquals(self.MAX, GIMarshallingTests.ushort_out()) def test_ushort_inout(self): self.assertEquals(0, GIMarshallingTests.ushort_inout(Number(self.MAX))) class TestInt(unittest.TestCase): MAX = GObject.constants.G_MAXINT MIN = GObject.constants.G_MININT def test_int_return(self): self.assertEquals(self.MAX, GIMarshallingTests.int_return_max()) self.assertEquals(self.MIN, GIMarshallingTests.int_return_min()) def test_int_in(self): max = Number(self.MAX) min = Number(self.MIN) GIMarshallingTests.int_in_max(max) GIMarshallingTests.int_in_min(min) max.value += 1 min.value -= 1 self.assertRaises(ValueError, GIMarshallingTests.int_in_max, max) self.assertRaises(ValueError, GIMarshallingTests.int_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.int_in_max, "self.MAX") def test_int_out(self): self.assertEquals(self.MAX, GIMarshallingTests.int_out_max()) self.assertEquals(self.MIN, GIMarshallingTests.int_out_min()) def test_int_inout(self): self.assertEquals(self.MIN, GIMarshallingTests.int_inout_max_min(Number(self.MAX))) self.assertEquals(self.MAX, GIMarshallingTests.int_inout_min_max(Number(self.MIN))) self.assertRaises(TypeError, GIMarshallingTests.int_inout_min_max, Number(self.MIN), CONSTANT_NUMBER) class TestUInt(unittest.TestCase): MAX = GObject.constants.G_MAXUINT def test_uint_return(self): self.assertEquals(self.MAX, GIMarshallingTests.uint_return()) def test_uint_in(self): number = Number(self.MAX) GIMarshallingTests.uint_in(number) number.value += 1 self.assertRaises(ValueError, GIMarshallingTests.uint_in, number) self.assertRaises(ValueError, GIMarshallingTests.uint_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.uint_in, "self.MAX") def test_uint_out(self): self.assertEquals(self.MAX, GIMarshallingTests.uint_out()) def test_uint_inout(self): self.assertEquals(0, GIMarshallingTests.uint_inout(Number(self.MAX))) class TestLong(unittest.TestCase): MAX = GObject.constants.G_MAXLONG MIN = GObject.constants.G_MINLONG def test_long_return(self): self.assertEquals(self.MAX, GIMarshallingTests.long_return_max()) self.assertEquals(self.MIN, GIMarshallingTests.long_return_min()) def test_long_in(self): max = Number(self.MAX) min = Number(self.MIN) GIMarshallingTests.long_in_max(max) GIMarshallingTests.long_in_min(min) max.value += 1 min.value -= 1 self.assertRaises(ValueError, GIMarshallingTests.long_in_max, max) self.assertRaises(ValueError, GIMarshallingTests.long_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.long_in_max, "self.MAX") def test_long_out(self): self.assertEquals(self.MAX, GIMarshallingTests.long_out_max()) self.assertEquals(self.MIN, GIMarshallingTests.long_out_min()) def test_long_inout(self): self.assertEquals(self.MIN, GIMarshallingTests.long_inout_max_min(Number(self.MAX))) self.assertEquals(self.MAX, GIMarshallingTests.long_inout_min_max(Number(self.MIN))) class TestULong(unittest.TestCase): MAX = GObject.constants.G_MAXULONG def test_ulong_return(self): self.assertEquals(self.MAX, GIMarshallingTests.ulong_return()) def test_ulong_in(self): number = Number(self.MAX) GIMarshallingTests.ulong_in(number) number.value += 1 self.assertRaises(ValueError, GIMarshallingTests.ulong_in, number) self.assertRaises(ValueError, GIMarshallingTests.ulong_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.ulong_in, "self.MAX") def test_ulong_out(self): self.assertEquals(self.MAX, GIMarshallingTests.ulong_out()) def test_ulong_inout(self): self.assertEquals(0, GIMarshallingTests.ulong_inout(Number(self.MAX))) class TestSSize(unittest.TestCase): MAX = GObject.constants.G_MAXLONG MIN = GObject.constants.G_MINLONG def test_ssize_return(self): self.assertEquals(self.MAX, GIMarshallingTests.ssize_return_max()) self.assertEquals(self.MIN, GIMarshallingTests.ssize_return_min()) def test_ssize_in(self): max = Number(self.MAX) min = Number(self.MIN) GIMarshallingTests.ssize_in_max(max) GIMarshallingTests.ssize_in_min(min) max.value += 1 min.value -= 1 self.assertRaises(ValueError, GIMarshallingTests.ssize_in_max, max) self.assertRaises(ValueError, GIMarshallingTests.ssize_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.ssize_in_max, "self.MAX") def test_ssize_out(self): self.assertEquals(self.MAX, GIMarshallingTests.ssize_out_max()) self.assertEquals(self.MIN, GIMarshallingTests.ssize_out_min()) def test_ssize_inout(self): self.assertEquals(self.MIN, GIMarshallingTests.ssize_inout_max_min(Number(self.MAX))) self.assertEquals(self.MAX, GIMarshallingTests.ssize_inout_min_max(Number(self.MIN))) class TestSize(unittest.TestCase): MAX = GObject.constants.G_MAXULONG def test_size_return(self): self.assertEquals(self.MAX, GIMarshallingTests.size_return()) def test_size_in(self): number = Number(self.MAX) GIMarshallingTests.size_in(number) number.value += 1 self.assertRaises(ValueError, GIMarshallingTests.size_in, number) self.assertRaises(ValueError, GIMarshallingTests.size_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.size_in, "self.MAX") def test_size_out(self): self.assertEquals(self.MAX, GIMarshallingTests.size_out()) def test_size_inout(self): self.assertEquals(0, GIMarshallingTests.size_inout(Number(self.MAX))) class TestFloat(unittest.TestCase): MAX = GObject.constants.G_MAXFLOAT MIN = GObject.constants.G_MINFLOAT def test_float_return(self): self.assertAlmostEquals(self.MAX, GIMarshallingTests.float_return()) def test_float_in(self): GIMarshallingTests.float_in(Number(self.MAX)) self.assertRaises(TypeError, GIMarshallingTests.float_in, "self.MAX") def test_float_out(self): self.assertAlmostEquals(self.MAX, GIMarshallingTests.float_out()) def test_float_inout(self): self.assertAlmostEquals(self.MIN, GIMarshallingTests.float_inout(Number(self.MAX))) class TestDouble(unittest.TestCase): MAX = GObject.constants.G_MAXDOUBLE MIN = GObject.constants.G_MINDOUBLE def test_double_return(self): self.assertAlmostEquals(self.MAX, GIMarshallingTests.double_return()) def test_double_in(self): GIMarshallingTests.double_in(Number(self.MAX)) self.assertRaises(TypeError, GIMarshallingTests.double_in, "self.MAX") def test_double_out(self): self.assertAlmostEquals(self.MAX, GIMarshallingTests.double_out()) def test_double_inout(self): self.assertAlmostEquals(self.MIN, GIMarshallingTests.double_inout(Number(self.MAX))) class TestGType(unittest.TestCase): def test_gtype_return(self): self.assertEquals(GObject.TYPE_NONE, GIMarshallingTests.gtype_return()) def test_gtype_in(self): GIMarshallingTests.gtype_in(GObject.TYPE_NONE) self.assertRaises(TypeError, GIMarshallingTests.gtype_in, "GObject.TYPE_NONE") def test_gtype_out(self): self.assertEquals(GObject.TYPE_NONE, GIMarshallingTests.gtype_out()) def test_gtype_inout(self): self.assertEquals(GObject.TYPE_INT, GIMarshallingTests.gtype_inout(GObject.TYPE_NONE)) class TestUtf8(unittest.TestCase): def test_utf8_none_return(self): self.assertEquals(CONSTANT_UTF8, GIMarshallingTests.utf8_none_return()) def test_utf8_full_return(self): self.assertEquals(CONSTANT_UTF8, GIMarshallingTests.utf8_full_return()) def test_utf8_none_in(self): GIMarshallingTests.utf8_none_in(CONSTANT_UTF8) if sys.version_info < (3, 0): GIMarshallingTests.utf8_none_in(PY2_UNICODE_UTF8) self.assertRaises(TypeError, GIMarshallingTests.utf8_none_in, CONSTANT_NUMBER) self.assertRaises(TypeError, GIMarshallingTests.utf8_none_in, None) def test_utf8_none_out(self): self.assertEquals(CONSTANT_UTF8, GIMarshallingTests.utf8_none_out()) def test_utf8_full_out(self): self.assertEquals(CONSTANT_UTF8, GIMarshallingTests.utf8_full_out()) def test_utf8_dangling_out(self): GIMarshallingTests.utf8_dangling_out() def test_utf8_none_inout(self): self.assertEquals("", GIMarshallingTests.utf8_none_inout(CONSTANT_UTF8)) def test_utf8_full_inout(self): self.assertEquals("", GIMarshallingTests.utf8_full_inout(CONSTANT_UTF8)) class TestArray(unittest.TestCase): def test_array_fixed_int_return(self): self.assertEquals([-1, 0, 1, 2], GIMarshallingTests.array_fixed_int_return()) def test_array_fixed_short_return(self): self.assertEquals([-1, 0, 1, 2], GIMarshallingTests.array_fixed_short_return()) def test_array_fixed_int_in(self): GIMarshallingTests.array_fixed_int_in(Sequence([-1, 0, 1, 2])) self.assertRaises(TypeError, GIMarshallingTests.array_fixed_int_in, Sequence([-1, '0', 1, 2])) self.assertRaises(TypeError, GIMarshallingTests.array_fixed_int_in, 42) self.assertRaises(TypeError, GIMarshallingTests.array_fixed_int_in, None) def test_array_fixed_short_in(self): GIMarshallingTests.array_fixed_short_in(Sequence([-1, 0, 1, 2])) def test_array_fixed_out(self): self.assertEquals([-1, 0, 1, 2], GIMarshallingTests.array_fixed_out()) def test_array_fixed_inout(self): self.assertEquals([2, 1, 0, -1], GIMarshallingTests.array_fixed_inout([-1, 0, 1, 2])) def test_array_return(self): self.assertEquals([-1, 0, 1, 2], GIMarshallingTests.array_return()) def test_array_in(self): GIMarshallingTests.array_in(Sequence([-1, 0, 1, 2])) def test_array_uint8_in(self): GIMarshallingTests.array_uint8_in(Sequence([97, 98, 99, 100])) GIMarshallingTests.array_uint8_in(_bytes("abcd")) def test_array_out(self): self.assertEquals([-1, 0, 1, 2], GIMarshallingTests.array_out()) def test_array_inout(self): self.assertEquals([-2, -1, 0, 1, 2], GIMarshallingTests.array_inout(Sequence([-1, 0, 1, 2]))) def test_method_array_in(self): object_ = GIMarshallingTests.Object() object_.method_array_in(Sequence([-1, 0, 1, 2])) def test_method_array_out(self): object_ = GIMarshallingTests.Object() self.assertEquals([-1, 0, 1, 2], object_.method_array_out()) def test_method_array_inout(self): object_ = GIMarshallingTests.Object() self.assertEquals([-2, -1, 0, 1, 2], object_.method_array_inout(Sequence([-1, 0, 1, 2]))) def test_method_array_return(self): object_ = GIMarshallingTests.Object() self.assertEquals([-1, 0, 1, 2], object_.method_array_return()) def test_array_fixed_out_struct(self): struct1, struct2 = GIMarshallingTests.array_fixed_out_struct() self.assertEquals(7, struct1.long_) self.assertEquals(6, struct1.int8) self.assertEquals(6, struct2.long_) self.assertEquals(7, struct2.int8) def test_array_zero_terminated_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.array_zero_terminated_return()) def test_array_zero_terminated_in(self): GIMarshallingTests.array_zero_terminated_in(Sequence(['0', '1', '2'])) def test_array_zero_terminated_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.array_zero_terminated_out()) def test_array_zero_terminated_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.array_zero_terminated_out()) def test_array_zero_terminated_inout(self): self.assertEquals(['-1', '0', '1', '2'], GIMarshallingTests.array_zero_terminated_inout(['0', '1', '2'])) def test_gstrv_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gstrv_return()) def test_gstrv_in(self): GIMarshallingTests.gstrv_in(Sequence(['0', '1', '2'])) def test_gstrv_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gstrv_out()) def test_gstrv_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gstrv_out()) def test_gstrv_inout(self): self.assertEquals(['-1', '0', '1', '2'], GIMarshallingTests.gstrv_inout(['0', '1', '2'])) class TestGArray(unittest.TestCase): def test_garray_int_none_return(self): self.assertEquals([-1, 0, 1, 2], GIMarshallingTests.garray_int_none_return()) def test_garray_utf8_none_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.garray_utf8_none_return()) def test_garray_utf8_container_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.garray_utf8_container_return()) def test_garray_utf8_full_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.garray_utf8_full_return()) def test_garray_int_none_in(self): GIMarshallingTests.garray_int_none_in(Sequence([-1, 0, 1, 2])) self.assertRaises(TypeError, GIMarshallingTests.garray_int_none_in, Sequence([-1, '0', 1, 2])) self.assertRaises(TypeError, GIMarshallingTests.garray_int_none_in, 42) self.assertRaises(TypeError, GIMarshallingTests.garray_int_none_in, None) def test_garray_utf8_none_in(self): GIMarshallingTests.garray_utf8_none_in(Sequence(['0', '1', '2'])) def test_garray_utf8_none_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.garray_utf8_none_out()) def test_garray_utf8_container_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.garray_utf8_container_out()) def test_garray_utf8_full_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.garray_utf8_full_out()) def test_garray_utf8_none_inout(self): self.assertEquals(['-2', '-1', '0', '1'], GIMarshallingTests.garray_utf8_none_inout(Sequence(('0', '1', '2')))) def test_garray_utf8_container_inout(self): self.assertEquals(['-2', '-1','0', '1'], GIMarshallingTests.garray_utf8_container_inout(['0', '1', '2'])) def test_garray_utf8_full_inout(self): self.assertEquals(['-2', '-1','0', '1'], GIMarshallingTests.garray_utf8_full_inout(['0', '1', '2'])) class TestGPtrArray(unittest.TestCase): def test_gptrarray_int_none_return(self): self.assertEquals([0, 1, 2, 3], GIMarshallingTests.gptrarray_int_none_return()) def test_gptrarray_utf8_none_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gptrarray_utf8_none_return()) def test_gptrarray_utf8_container_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gptrarray_utf8_container_return()) def test_gptrarray_utf8_full_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gptrarray_utf8_full_return()) def test_gptrarray_int_none_in(self): GIMarshallingTests.gptrarray_int_none_in(Sequence([0, 1, 2, 3])) self.assertRaises(TypeError, GIMarshallingTests.gptrarray_int_none_in, Sequence([-1, '0', 1, 2])) self.assertRaises(TypeError, GIMarshallingTests.gptrarray_int_none_in, 42) self.assertRaises(TypeError, GIMarshallingTests.gptrarray_int_none_in, None) def test_gptrarray_utf8_none_in(self): GIMarshallingTests.gptrarray_utf8_none_in(Sequence(['0', '1', '2'])) def test_gptrarray_utf8_none_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gptrarray_utf8_none_out()) def test_gptrarray_utf8_container_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gptrarray_utf8_container_out()) def test_gptrarray_utf8_full_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gptrarray_utf8_full_out()) def test_gptrarray_utf8_none_inout(self): self.assertEquals(['-2', '-1', '0', '1'], GIMarshallingTests.gptrarray_utf8_none_inout(Sequence(('0', '1', '2')))) def test_gptrarray_utf8_container_inout(self): self.assertEquals(['-2', '-1','0', '1'], GIMarshallingTests.gptrarray_utf8_container_inout(['0', '1', '2'])) def test_gptrarray_utf8_full_inout(self): self.assertEquals(['-2', '-1','0', '1'], GIMarshallingTests.gptrarray_utf8_full_inout(['0', '1', '2'])) class TestGList(unittest.TestCase): def test_glist_int_none_return(self): self.assertEquals([-1, 0, 1, 2], GIMarshallingTests.glist_int_none_return()) def test_glist_utf8_none_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.glist_utf8_none_return()) def test_glist_utf8_container_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.glist_utf8_container_return()) def test_glist_utf8_full_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.glist_utf8_full_return()) def test_glist_int_none_in(self): GIMarshallingTests.glist_int_none_in(Sequence((-1, 0, 1, 2))) self.assertRaises(TypeError, GIMarshallingTests.glist_int_none_in, Sequence((-1, '0', 1, 2))) self.assertRaises(TypeError, GIMarshallingTests.glist_int_none_in, 42) self.assertRaises(TypeError, GIMarshallingTests.glist_int_none_in, None) def test_glist_utf8_none_in(self): GIMarshallingTests.glist_utf8_none_in(Sequence(('0', '1', '2'))) def test_glist_utf8_none_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.glist_utf8_none_out()) def test_glist_utf8_container_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.glist_utf8_container_out()) def test_glist_utf8_full_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.glist_utf8_full_out()) def test_glist_utf8_none_inout(self): self.assertEquals(['-2', '-1', '0', '1'], GIMarshallingTests.glist_utf8_none_inout(Sequence(('0', '1', '2')))) def test_glist_utf8_container_inout(self): self.assertEquals(['-2', '-1','0', '1'], GIMarshallingTests.glist_utf8_container_inout(('0', '1', '2'))) def test_glist_utf8_full_inout(self): self.assertEquals(['-2', '-1','0', '1'], GIMarshallingTests.glist_utf8_full_inout(('0', '1', '2'))) class TestGSList(unittest.TestCase): def test_gslist_int_none_return(self): self.assertEquals([-1, 0, 1, 2], GIMarshallingTests.gslist_int_none_return()) def test_gslist_utf8_none_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gslist_utf8_none_return()) def test_gslist_utf8_container_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gslist_utf8_container_return()) def test_gslist_utf8_full_return(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gslist_utf8_full_return()) def test_gslist_int_none_in(self): GIMarshallingTests.gslist_int_none_in(Sequence((-1, 0, 1, 2))) self.assertRaises(TypeError, GIMarshallingTests.gslist_int_none_in, Sequence((-1, '0', 1, 2))) self.assertRaises(TypeError, GIMarshallingTests.gslist_int_none_in, 42) self.assertRaises(TypeError, GIMarshallingTests.gslist_int_none_in, None) def test_gslist_utf8_none_in(self): GIMarshallingTests.gslist_utf8_none_in(Sequence(('0', '1', '2'))) def test_gslist_utf8_none_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gslist_utf8_none_out()) def test_gslist_utf8_container_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gslist_utf8_container_out()) def test_gslist_utf8_full_out(self): self.assertEquals(['0', '1', '2'], GIMarshallingTests.gslist_utf8_full_out()) def test_gslist_utf8_none_inout(self): self.assertEquals(['-2', '-1', '0', '1'], GIMarshallingTests.gslist_utf8_none_inout(Sequence(('0', '1', '2')))) def test_gslist_utf8_container_inout(self): self.assertEquals(['-2', '-1','0', '1'], GIMarshallingTests.gslist_utf8_container_inout(('0', '1', '2'))) def test_gslist_utf8_full_inout(self): self.assertEquals(['-2', '-1','0', '1'], GIMarshallingTests.gslist_utf8_full_inout(('0', '1', '2'))) class TestGHashTable(unittest.TestCase): def test_ghashtable_int_none_return(self): self.assertEquals({-1: 1, 0: 0, 1: -1, 2: -2}, GIMarshallingTests.ghashtable_int_none_return()) def test_ghashtable_int_none_return(self): self.assertEquals({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_none_return()) def test_ghashtable_int_container_return(self): self.assertEquals({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_container_return()) def test_ghashtable_int_full_return(self): self.assertEquals({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_full_return()) def test_ghashtable_int_none_in(self): GIMarshallingTests.ghashtable_int_none_in({-1: 1, 0: 0, 1: -1, 2: -2}) self.assertRaises(TypeError, GIMarshallingTests.ghashtable_int_none_in, {-1: 1, '0': 0, 1: -1, 2: -2}) self.assertRaises(TypeError, GIMarshallingTests.ghashtable_int_none_in, {-1: 1, 0: '0', 1: -1, 2: -2}) self.assertRaises(TypeError, GIMarshallingTests.ghashtable_int_none_in, '{-1: 1, 0: 0, 1: -1, 2: -2}') self.assertRaises(TypeError, GIMarshallingTests.ghashtable_int_none_in, None) def test_ghashtable_utf8_none_in(self): GIMarshallingTests.ghashtable_utf8_none_in({'-1': '1', '0': '0', '1': '-1', '2': '-2'}) def test_ghashtable_utf8_none_out(self): self.assertEquals({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_none_out()) def test_ghashtable_utf8_container_out(self): self.assertEquals({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_container_out()) def test_ghashtable_utf8_full_out(self): self.assertEquals({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_full_out()) def test_ghashtable_utf8_none_inout(self): self.assertEquals({'-1': '1', '0': '0', '1': '1'}, GIMarshallingTests.ghashtable_utf8_none_inout({'-1': '1', '0': '0', '1': '-1', '2': '-2'})) def test_ghashtable_utf8_container_inout(self): self.assertEquals({'-1': '1', '0': '0', '1': '1'}, GIMarshallingTests.ghashtable_utf8_container_inout({'-1': '1', '0': '0', '1': '-1', '2': '-2'})) def test_ghashtable_utf8_full_inout(self): self.assertEquals({'-1': '1', '0': '0', '1': '1'}, GIMarshallingTests.ghashtable_utf8_full_inout({'-1': '1', '0': '0', '1': '-1', '2': '-2'})) class TestGValue(unittest.TestCase): def test_gvalue_return(self): self.assertEquals(42, GIMarshallingTests.gvalue_return()) def test_gvalue_in(self): GIMarshallingTests.gvalue_in(42) value = GObject.Value() value.init(GObject.TYPE_INT) value.set_int(42) GIMarshallingTests.gvalue_in(value) def test_gvalue_out(self): self.assertEquals(42, GIMarshallingTests.gvalue_out()) def test_gvalue_inout(self): self.assertEquals('42', GIMarshallingTests.gvalue_inout(42)) value = GObject.Value() value.init(GObject.TYPE_INT) value.set_int(42) self.assertEquals('42', GIMarshallingTests.gvalue_inout(value)) class TestGClosure(unittest.TestCase): def test_gclosure_in(self): GIMarshallingTests.gclosure_in(lambda: 42) # test passing a closure between two C calls closure = GIMarshallingTests.gclosure_return() GIMarshallingTests.gclosure_in(closure) self.assertRaises(TypeError, GIMarshallingTests.gclosure_in, 42) self.assertRaises(TypeError, GIMarshallingTests.gclosure_in, None) class TestPointer(unittest.TestCase): def test_pointer_in_return(self): self.assertEquals(GIMarshallingTests.pointer_in_return(42), 42) class TestEnum(unittest.TestCase): @classmethod def setUpClass(cls): '''Run tests under a test locale. Upper case conversion of member names should not be locale specific; e. g. in Turkish, "i".upper() == "i", which gives results like "iNVALiD" Run test under a locale which defines toupper('a') == 'a' ''' cls.locale_dir = tempfile.mkdtemp() subprocess.check_call(['localedef', '-i', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'te_ST@nouppera'), '-c', '-f', 'UTF-8', os.path.join(cls.locale_dir, 'te_ST.UTF-8@nouppera')]) os.environ['LOCPATH'] = cls.locale_dir locale.setlocale(locale.LC_ALL, 'te_ST.UTF-8@nouppera') @classmethod def tearDownClass(cls): locale.setlocale(locale.LC_ALL, 'C') shutil.rmtree(cls.locale_dir) try: del os.environ['LOCPATH'] except KeyError: pass def test_enum(self): self.assertTrue(issubclass(GIMarshallingTests.Enum, int)) self.assertTrue(isinstance(GIMarshallingTests.Enum.VALUE1, GIMarshallingTests.Enum)) self.assertTrue(isinstance(GIMarshallingTests.Enum.VALUE2, GIMarshallingTests.Enum)) self.assertTrue(isinstance(GIMarshallingTests.Enum.VALUE3, GIMarshallingTests.Enum)) self.assertEquals(42, GIMarshallingTests.Enum.VALUE3) def test_value_nick_and_name(self): self.assertEqual(GIMarshallingTests.Enum.VALUE1.value_nick, 'value1') self.assertEqual(GIMarshallingTests.Enum.VALUE2.value_nick, 'value2') self.assertEqual(GIMarshallingTests.Enum.VALUE3.value_nick, 'value3') self.assertEqual(GIMarshallingTests.Enum.VALUE1.value_name, 'GI_MARSHALLING_TESTS_ENUM_VALUE1') self.assertEqual(GIMarshallingTests.Enum.VALUE2.value_name, 'GI_MARSHALLING_TESTS_ENUM_VALUE2') self.assertEqual(GIMarshallingTests.Enum.VALUE3.value_name, 'GI_MARSHALLING_TESTS_ENUM_VALUE3') def test_enum_in(self): GIMarshallingTests.enum_in(GIMarshallingTests.Enum.VALUE3) GIMarshallingTests.enum_in(42) self.assertRaises(TypeError, GIMarshallingTests.enum_in, 43) self.assertRaises(TypeError, GIMarshallingTests.enum_in, 'GIMarshallingTests.Enum.VALUE3') def test_enum_out(self): enum = GIMarshallingTests.enum_out() self.assertTrue(isinstance(enum, GIMarshallingTests.Enum)) self.assertEquals(enum, GIMarshallingTests.Enum.VALUE3) def test_enum_inout(self): enum = GIMarshallingTests.enum_inout(GIMarshallingTests.Enum.VALUE3) self.assertTrue(isinstance(enum, GIMarshallingTests.Enum)) self.assertEquals(enum, GIMarshallingTests.Enum.VALUE1) def test_enum_second(self): # check for the bug where different non-gtype enums share the same class self.assertNotEqual(GIMarshallingTests.Enum, GIMarshallingTests.SecondEnum) # check that values are not being shared between different enums self.assertTrue(hasattr(GIMarshallingTests.SecondEnum, "SECONDVALUE1")) self.assertRaises(AttributeError, getattr, GIMarshallingTests.Enum, "SECONDVALUE1") self.assertTrue(hasattr(GIMarshallingTests.Enum, "VALUE1")) self.assertRaises(AttributeError, getattr, GIMarshallingTests.SecondEnum, "VALUE1") class TestGEnum(unittest.TestCase): def test_genum(self): self.assertTrue(issubclass(GIMarshallingTests.GEnum, GObject.GEnum)) self.assertTrue(isinstance(GIMarshallingTests.GEnum.VALUE1, GIMarshallingTests.GEnum)) self.assertTrue(isinstance(GIMarshallingTests.GEnum.VALUE2, GIMarshallingTests.GEnum)) self.assertTrue(isinstance(GIMarshallingTests.GEnum.VALUE3, GIMarshallingTests.GEnum)) self.assertEquals(42, GIMarshallingTests.GEnum.VALUE3) def test_value_nick_and_name(self): self.assertEqual(GIMarshallingTests.GEnum.VALUE1.value_nick, 'value1') self.assertEqual(GIMarshallingTests.GEnum.VALUE2.value_nick, 'value2') self.assertEqual(GIMarshallingTests.GEnum.VALUE3.value_nick, 'value3') self.assertEqual(GIMarshallingTests.GEnum.VALUE1.value_name, 'GI_MARSHALLING_TESTS_GENUM_VALUE1') self.assertEqual(GIMarshallingTests.GEnum.VALUE2.value_name, 'GI_MARSHALLING_TESTS_GENUM_VALUE2') self.assertEqual(GIMarshallingTests.GEnum.VALUE3.value_name, 'GI_MARSHALLING_TESTS_GENUM_VALUE3') def test_genum_in(self): GIMarshallingTests.genum_in(GIMarshallingTests.GEnum.VALUE3) GIMarshallingTests.genum_in(42) self.assertRaises(TypeError, GIMarshallingTests.genum_in, 43) self.assertRaises(TypeError, GIMarshallingTests.genum_in, 'GIMarshallingTests.GEnum.VALUE3') def test_genum_out(self): genum = GIMarshallingTests.genum_out() self.assertTrue(isinstance(genum, GIMarshallingTests.GEnum)) self.assertEquals(genum, GIMarshallingTests.GEnum.VALUE3) def test_genum_inout(self): genum = GIMarshallingTests.genum_inout(GIMarshallingTests.GEnum.VALUE3) self.assertTrue(isinstance(genum, GIMarshallingTests.GEnum)) self.assertEquals(genum, GIMarshallingTests.GEnum.VALUE1) class TestGFlags(unittest.TestCase): def test_flags(self): self.assertTrue(issubclass(GIMarshallingTests.Flags, GObject.GFlags)) self.assertTrue(isinstance(GIMarshallingTests.Flags.VALUE1, GIMarshallingTests.Flags)) self.assertTrue(isinstance(GIMarshallingTests.Flags.VALUE2, GIMarshallingTests.Flags)) self.assertTrue(isinstance(GIMarshallingTests.Flags.VALUE3, GIMarshallingTests.Flags)) # __or__() operation should still return an instance, not an int. self.assertTrue(isinstance(GIMarshallingTests.Flags.VALUE1 | GIMarshallingTests.Flags.VALUE2, GIMarshallingTests.Flags)) self.assertEquals(1 << 1, GIMarshallingTests.Flags.VALUE2) def test_value_nick_and_name(self): self.assertEqual(GIMarshallingTests.Flags.VALUE1.first_value_nick, 'value1') self.assertEqual(GIMarshallingTests.Flags.VALUE2.first_value_nick, 'value2') self.assertEqual(GIMarshallingTests.Flags.VALUE3.first_value_nick, 'value3') self.assertEqual(GIMarshallingTests.Flags.VALUE1.first_value_name, 'GI_MARSHALLING_TESTS_FLAGS_VALUE1') self.assertEqual(GIMarshallingTests.Flags.VALUE2.first_value_name, 'GI_MARSHALLING_TESTS_FLAGS_VALUE2') self.assertEqual(GIMarshallingTests.Flags.VALUE3.first_value_name, 'GI_MARSHALLING_TESTS_FLAGS_VALUE3') def test_flags_in(self): GIMarshallingTests.flags_in(GIMarshallingTests.Flags.VALUE2) # result of __or__() operation should still be valid instance, not an int. GIMarshallingTests.flags_in(GIMarshallingTests.Flags.VALUE2 | GIMarshallingTests.Flags.VALUE2) GIMarshallingTests.flags_in_zero(Number(0)) self.assertRaises(TypeError, GIMarshallingTests.flags_in, 1 << 1) self.assertRaises(TypeError, GIMarshallingTests.flags_in, 'GIMarshallingTests.Flags.VALUE2') def test_flags_out(self): flags = GIMarshallingTests.flags_out() self.assertTrue(isinstance(flags, GIMarshallingTests.Flags)) self.assertEquals(flags, GIMarshallingTests.Flags.VALUE2) def test_flags_inout(self): flags = GIMarshallingTests.flags_inout(GIMarshallingTests.Flags.VALUE2) self.assertTrue(isinstance(flags, GIMarshallingTests.Flags)) self.assertEquals(flags, GIMarshallingTests.Flags.VALUE1) class TestNoTypeFlags(unittest.TestCase): def test_flags(self): self.assertTrue(issubclass(GIMarshallingTests.NoTypeFlags, GObject.GFlags)) self.assertTrue(isinstance(GIMarshallingTests.NoTypeFlags.VALUE1, GIMarshallingTests.NoTypeFlags)) self.assertTrue(isinstance(GIMarshallingTests.NoTypeFlags.VALUE2, GIMarshallingTests.NoTypeFlags)) self.assertTrue(isinstance(GIMarshallingTests.NoTypeFlags.VALUE3, GIMarshallingTests.NoTypeFlags)) # __or__() operation should still return an instance, not an int. self.assertTrue(isinstance(GIMarshallingTests.NoTypeFlags.VALUE1 | GIMarshallingTests.NoTypeFlags.VALUE2, GIMarshallingTests.NoTypeFlags)) self.assertEquals(1 << 1, GIMarshallingTests.NoTypeFlags.VALUE2) def test_value_nick_and_name(self): self.assertEqual(GIMarshallingTests.NoTypeFlags.VALUE1.first_value_nick, 'value1') self.assertEqual(GIMarshallingTests.NoTypeFlags.VALUE2.first_value_nick, 'value2') self.assertEqual(GIMarshallingTests.NoTypeFlags.VALUE3.first_value_nick, 'value3') self.assertEqual(GIMarshallingTests.NoTypeFlags.VALUE1.first_value_name, 'GI_MARSHALLING_TESTS_NO_TYPE_FLAGS_VALUE1') self.assertEqual(GIMarshallingTests.NoTypeFlags.VALUE2.first_value_name, 'GI_MARSHALLING_TESTS_NO_TYPE_FLAGS_VALUE2') self.assertEqual(GIMarshallingTests.NoTypeFlags.VALUE3.first_value_name, 'GI_MARSHALLING_TESTS_NO_TYPE_FLAGS_VALUE3') def test_flags_in(self): GIMarshallingTests.no_type_flags_in(GIMarshallingTests.NoTypeFlags.VALUE2) GIMarshallingTests.no_type_flags_in(GIMarshallingTests.NoTypeFlags.VALUE2 | GIMarshallingTests.NoTypeFlags.VALUE2) GIMarshallingTests.no_type_flags_in_zero(Number(0)) self.assertRaises(TypeError, GIMarshallingTests.no_type_flags_in, 1 << 1) self.assertRaises(TypeError, GIMarshallingTests.no_type_flags_in, 'GIMarshallingTests.NoTypeFlags.VALUE2') def test_flags_out(self): flags = GIMarshallingTests.no_type_flags_out() self.assertTrue(isinstance(flags, GIMarshallingTests.NoTypeFlags)) self.assertEquals(flags, GIMarshallingTests.NoTypeFlags.VALUE2) def test_flags_inout(self): flags = GIMarshallingTests.no_type_flags_inout(GIMarshallingTests.NoTypeFlags.VALUE2) self.assertTrue(isinstance(flags, GIMarshallingTests.NoTypeFlags)) self.assertEquals(flags, GIMarshallingTests.NoTypeFlags.VALUE1) class TestStructure(unittest.TestCase): def test_simple_struct(self): self.assertTrue(issubclass(GIMarshallingTests.SimpleStruct, GObject.GPointer)) struct = GIMarshallingTests.SimpleStruct() self.assertTrue(isinstance(struct, GIMarshallingTests.SimpleStruct)) self.assertEquals(0, struct.long_) self.assertEquals(0, struct.int8) struct.long_ = 6 struct.int8 = 7 self.assertEquals(6, struct.long_) self.assertEquals(7, struct.int8) del struct def test_nested_struct(self): struct = GIMarshallingTests.NestedStruct() self.assertTrue(isinstance(struct.simple_struct, GIMarshallingTests.SimpleStruct)) struct.simple_struct.long_ = 42 self.assertEquals(42, struct.simple_struct.long_) del struct def test_not_simple_struct(self): struct = GIMarshallingTests.NotSimpleStruct() self.assertEquals(None, struct.pointer) def test_simple_struct_return(self): struct = GIMarshallingTests.simple_struct_returnv() self.assertTrue(isinstance(struct, GIMarshallingTests.SimpleStruct)) self.assertEquals(6, struct.long_) self.assertEquals(7, struct.int8) del struct def test_simple_struct_in(self): struct = GIMarshallingTests.SimpleStruct() struct.long_ = 6 struct.int8 = 7 GIMarshallingTests.SimpleStruct.inv(struct) del struct struct = GIMarshallingTests.NestedStruct() self.assertRaises(TypeError, GIMarshallingTests.SimpleStruct.inv, struct) del struct self.assertRaises(TypeError, GIMarshallingTests.SimpleStruct.inv, None) def test_simple_struct_method(self): struct = GIMarshallingTests.SimpleStruct() struct.long_ = 6 struct.int8 = 7 struct.method() del struct self.assertRaises(TypeError, GIMarshallingTests.SimpleStruct.method) def test_pointer_struct(self): self.assertTrue(issubclass(GIMarshallingTests.PointerStruct, GObject.GPointer)) struct = GIMarshallingTests.PointerStruct() self.assertTrue(isinstance(struct, GIMarshallingTests.PointerStruct)) del struct def test_pointer_struct_return(self): struct = GIMarshallingTests.pointer_struct_returnv() self.assertTrue(isinstance(struct, GIMarshallingTests.PointerStruct)) self.assertEquals(42, struct.long_) del struct def test_pointer_struct_in(self): struct = GIMarshallingTests.PointerStruct() struct.long_ = 42 struct.inv() del struct def test_boxed_struct(self): self.assertTrue(issubclass(GIMarshallingTests.BoxedStruct, GObject.GBoxed)) struct = GIMarshallingTests.BoxedStruct() self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct)) self.assertEquals(0, struct.long_) self.assertEquals([], struct.g_strv) del struct def test_boxed_struct_new(self): struct = GIMarshallingTests.BoxedStruct.new() self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct)) del struct def test_boxed_struct_copy(self): struct = GIMarshallingTests.BoxedStruct() new_struct = struct.copy() self.assertTrue(isinstance(new_struct, GIMarshallingTests.BoxedStruct)) del new_struct del struct def test_boxed_struct_return(self): struct = GIMarshallingTests.boxed_struct_returnv() self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct)) self.assertEquals(42, struct.long_) self.assertEquals(['0', '1', '2'], struct.g_strv) del struct def test_boxed_struct_in(self): struct = GIMarshallingTests.BoxedStruct() struct.long_ = 42 struct.inv() del struct def test_boxed_struct_out(self): struct = GIMarshallingTests.boxed_struct_out() self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct)) self.assertEquals(42, struct.long_) del struct def test_boxed_struct_inout(self): in_struct = GIMarshallingTests.BoxedStruct() in_struct.long_ = 42 out_struct = GIMarshallingTests.boxed_struct_inout(in_struct) self.assertTrue(isinstance(out_struct, GIMarshallingTests.BoxedStruct)) self.assertEquals(0, out_struct.long_) del in_struct del out_struct def test_union(self): union = GIMarshallingTests.Union() self.assertTrue(isinstance(union, GIMarshallingTests.Union)) new_union = union.copy() self.assertTrue(isinstance(new_union, GIMarshallingTests.Union)) del union del new_union def test_union_return(self): union = GIMarshallingTests.union_returnv() self.assertTrue(isinstance(union, GIMarshallingTests.Union)) self.assertEquals(42, union.long_) del union def test_union_in(self): union = GIMarshallingTests.Union() union.long_ = 42 union.inv() del union def test_union_method(self): union = GIMarshallingTests.Union() union.long_ = 42 union.method() del union self.assertRaises(TypeError, GIMarshallingTests.Union.method) class TestGObject(unittest.TestCase): def test_object(self): self.assertTrue(issubclass(GIMarshallingTests.Object, GObject.GObject)) object_ = GIMarshallingTests.Object() self.assertTrue(isinstance(object_, GIMarshallingTests.Object)) self.assertEquals(object_.__grefcount__, 1) def test_object_new(self): object_ = GIMarshallingTests.Object.new(42) self.assertTrue(isinstance(object_, GIMarshallingTests.Object)) self.assertEquals(object_.__grefcount__, 1) def test_object_int(self): object_ = GIMarshallingTests.Object(int = 42) self.assertEquals(object_.int_, 42) # FIXME: Don't work yet. # object_.int_ = 0 # self.assertEquals(object_.int_, 0) def test_object_static_method(self): GIMarshallingTests.Object.static_method() def test_object_method(self): GIMarshallingTests.Object(int = 42).method() self.assertRaises(TypeError, GIMarshallingTests.Object.method, GObject.GObject()) self.assertRaises(TypeError, GIMarshallingTests.Object.method) def test_sub_object(self): self.assertTrue(issubclass(GIMarshallingTests.SubObject, GIMarshallingTests.Object)) object_ = GIMarshallingTests.SubObject() self.assertTrue(isinstance(object_, GIMarshallingTests.SubObject)) def test_sub_object_new(self): self.assertRaises(TypeError, GIMarshallingTests.SubObject.new, 42) def test_sub_object_static_method(self): object_ = GIMarshallingTests.SubObject() object_.static_method() def test_sub_object_method(self): object_ = GIMarshallingTests.SubObject(int = 42) object_.method() def test_sub_object_sub_method(self): object_ = GIMarshallingTests.SubObject() object_.sub_method() def test_sub_object_overwritten_method(self): object_ = GIMarshallingTests.SubObject() object_.overwritten_method() self.assertRaises(TypeError, GIMarshallingTests.SubObject.overwritten_method, GIMarshallingTests.Object()) def test_sub_object_int(self): object_ = GIMarshallingTests.SubObject() self.assertEquals(object_.int_, 0) # FIXME: Don't work yet. # object_.int_ = 42 # self.assertEquals(object_.int_, 42) def test_object_none_return(self): object_ = GIMarshallingTests.Object.none_return() self.assertTrue(isinstance(object_, GIMarshallingTests.Object)) self.assertEquals(object_.__grefcount__, 2) def test_object_full_return(self): object_ = GIMarshallingTests.Object.full_return() self.assertTrue(isinstance(object_, GIMarshallingTests.Object)) self.assertEquals(object_.__grefcount__, 1) def test_object_none_in(self): object_ = GIMarshallingTests.Object(int = 42) GIMarshallingTests.Object.none_in(object_) self.assertEquals(object_.__grefcount__, 1) object_ = GIMarshallingTests.SubObject(int = 42) GIMarshallingTests.Object.none_in(object_) object_ = GObject.GObject() self.assertRaises(TypeError, GIMarshallingTests.Object.none_in, object_) self.assertRaises(TypeError, GIMarshallingTests.Object.none_in, None) def test_object_none_out(self): object_ = GIMarshallingTests.Object.none_out() self.assertTrue(isinstance(object_, GIMarshallingTests.Object)) self.assertEquals(object_.__grefcount__, 2) new_object = GIMarshallingTests.Object.none_out() self.assertTrue(new_object is object_) def test_object_full_out(self): object_ = GIMarshallingTests.Object.full_out() self.assertTrue(isinstance(object_, GIMarshallingTests.Object)) self.assertEquals(object_.__grefcount__, 1) def test_object_none_inout(self): object_ = GIMarshallingTests.Object(int = 42) new_object = GIMarshallingTests.Object.none_inout(object_) self.assertTrue(isinstance(new_object, GIMarshallingTests.Object)) self.assertFalse(object_ is new_object) self.assertEquals(object_.__grefcount__, 1) self.assertEquals(new_object.__grefcount__, 2) new_new_object = GIMarshallingTests.Object.none_inout(object_) self.assertTrue(new_new_object is new_object) GIMarshallingTests.Object.none_inout(GIMarshallingTests.SubObject(int = 42)) def test_object_full_inout(self): object_ = GIMarshallingTests.Object(int = 42) new_object = GIMarshallingTests.Object.full_inout(object_) self.assertTrue(isinstance(new_object, GIMarshallingTests.Object)) self.assertFalse(object_ is new_object) self.assertEquals(object_.__grefcount__, 2) self.assertEquals(new_object.__grefcount__, 1) # FIXME: Doesn't actually return the same object. # def test_object_inout_same(self): # object_ = GIMarshallingTests.Object() # new_object = GIMarshallingTests.object_full_inout(object_) # self.assertTrue(object_ is new_object) # self.assertEquals(object_.__grefcount__, 1) class TestPythonGObject(unittest.TestCase): class Object(GIMarshallingTests.Object): def __init__(self, int): GIMarshallingTests.Object.__init__(self) self.val = None def method(self): # Don't call super, which asserts that self.int == 42. pass def do_method_int8_in(self, int8): self.val = int8 def do_method_int8_out(self): return 42 def do_method_with_default_implementation(self, int8): GIMarshallingTests.Object.do_method_with_default_implementation(self, int8) self.props.int += int8 class SubObject(GIMarshallingTests.SubObject): def __init__(self, int): GIMarshallingTests.SubObject.__init__(self) self.val = None def do_method_with_default_implementation(self, int8): self.val = int8 def test_object(self): self.assertTrue(issubclass(self.Object, GIMarshallingTests.Object)) object_ = self.Object(int = 42) self.assertTrue(isinstance(object_, self.Object)) def test_object_method(self): self.Object(int = 0).method() def test_object_vfuncs(self): object_ = self.Object(int = 42) object_.method_int8_in(84) self.assertEqual(object_.val, 84) self.assertEqual(object_.method_int8_out(), 42) object_.method_with_default_implementation(42) self.assertEqual(object_.props.int, 84) class ObjectWithoutVFunc(GIMarshallingTests.Object): def __init__(self, int): GIMarshallingTests.Object.__init__(self) object_ = ObjectWithoutVFunc(int = 42) object_.method_with_default_implementation(84) self.assertEqual(object_.props.int, 84) def test_subobject_parent_vfunc(self): object_ = self.SubObject(int = 81) object_.method_with_default_implementation(87) self.assertEquals(object_.val, 87) def test_dynamic_module(self): from gi.module import DynamicGObjectModule self.assertTrue(isinstance(GObject, DynamicGObjectModule)) # compare the same enum from both the pygobject attrs and gi GObject attrs self.assertEquals(GObject.SIGNAL_ACTION, GObject.SignalFlags.ACTION) # compare a static gobject attr with a dynamic GObject attr self.assertEquals(GObject.GObject, gobject.GObject) def test_subobject_non_vfunc_do_method(self): class PythonObjectWithNonVFuncDoMethod: def do_not_a_vfunc(self): return 5 class ObjectOverrideNonVFuncDoMethod(GIMarshallingTests.Object, PythonObjectWithNonVFuncDoMethod): def do_not_a_vfunc(self): value = super(ObjectOverrideNonVFuncDoMethod, self).do_not_a_vfunc() return 13 + value object_ = ObjectOverrideNonVFuncDoMethod() self.assertEquals(18, object_.do_not_a_vfunc()) def test_native_function_not_set_in_subclass_dict(self): # Previously, GI was setting virtual functions on the class as well # as any *native* class that subclasses it. Here we check that it is only # set on the class that the method is originally from. self.assertTrue('do_method_with_default_implementation' in GIMarshallingTests.Object.__dict__) self.assertTrue('do_method_with_default_implementation' not in GIMarshallingTests.SubObject.__dict__) # Here we check that accessing a vfunc from the subclass returns the same wrapper object, # meaning that multiple wrapper objects have not been created for the same vfunc. func1 = GIMarshallingTests.Object.do_method_with_default_implementation func2 = GIMarshallingTests.SubObject.do_method_with_default_implementation if sys.version_info < (3,0): func1 = func1.im_func func2 = func2.im_func self.assertTrue(func1 is func2) def test_subobject_with_interface_and_non_vfunc_do_method(self): # There was a bug for searching for vfuncs in interfaces. It was # triggered by having a do_* method that wasn't overriding # a native vfunc, as well as inheriting from an interface. class GObjectSubclassWithInterface(GObject.GObject, GIMarshallingTests.Interface): def do_method_not_a_vfunc(self): pass class TestMultiOutputArgs(unittest.TestCase): def test_int_out_out(self): self.assertEquals((6, 7), GIMarshallingTests.int_out_out()) def test_int_return_out(self): self.assertEquals((6, 7), GIMarshallingTests.int_return_out()) class TestGErrorException(unittest.TestCase): def test_gerror_exception(self): self.assertRaises(GObject.GError, GIMarshallingTests.gerror) try: GIMarshallingTests.gerror() except Exception: etype, e = sys.exc_info()[:2] self.assertEquals(e.domain, GIMarshallingTests.CONSTANT_GERROR_DOMAIN) self.assertEquals(e.code, GIMarshallingTests.CONSTANT_GERROR_CODE) self.assertEquals(e.message, GIMarshallingTests.CONSTANT_GERROR_MESSAGE) # Interface class TestInterfaces(unittest.TestCase): def test_wrapper(self): self.assertTrue(issubclass(GIMarshallingTests.Interface, GObject.GInterface)) self.assertEquals(GIMarshallingTests.Interface.__gtype__.name, 'GIMarshallingTestsInterface') self.assertRaises(NotImplementedError, GIMarshallingTests.Interface) def test_implementation(self): class TestInterfaceImpl(GObject.GObject, GIMarshallingTests.Interface): def __init__(self): GObject.GObject.__init__(self) self.val = None def do_test_int8_in(self, int8): self.val = int8 self.assertTrue(issubclass(TestInterfaceImpl, GIMarshallingTests.Interface)) instance = TestInterfaceImpl() self.assertTrue(isinstance(instance, GIMarshallingTests.Interface)) GIMarshallingTests.test_interface_test_int8_in(instance, 42) self.assertEquals(instance.val, 42) class TestInterfaceImplA(TestInterfaceImpl): pass class TestInterfaceImplB(TestInterfaceImplA): pass instance = TestInterfaceImplA() GIMarshallingTests.test_interface_test_int8_in(instance, 42) self.assertEquals(instance.val, 42) def test_mro(self): # there was a problem with Python bailing out because of # http://en.wikipedia.org/wiki/Diamond_problem with interfaces, # which shouldn't really be a problem. class TestInterfaceImpl(GObject.GObject, GIMarshallingTests.Interface): pass class TestInterfaceImpl2(GIMarshallingTests.Interface, TestInterfaceImpl): pass class TestInterfaceImpl3(TestInterfaceImpl, GIMarshallingTests.Interface2): pass class TestInterfaceClash(unittest.TestCase): def test_clash(self): def create_clash(): class TestClash(GObject.GObject, GIMarshallingTests.Interface, GIMarshallingTests.Interface2): def do_test_int8_in(self, int8): pass TestClash() self.assertRaises(TypeError, create_clash) class TestOverrides(unittest.TestCase): def test_constant(self): self.assertEquals(GIMarshallingTests.OVERRIDES_CONSTANT, 7) def test_struct(self): # Test that the constructor has been overridden. struct = GIMarshallingTests.OverridesStruct(42) self.assertTrue(isinstance(struct, GIMarshallingTests.OverridesStruct)) # Test that the method has been overridden. self.assertEquals(6, struct.method()) del struct # Test that the overrides wrapper has been registered. struct = GIMarshallingTests.overrides_struct_returnv() self.assertTrue(isinstance(struct, GIMarshallingTests.OverridesStruct)) del struct def test_object(self): # Test that the constructor has been overridden. object_ = GIMarshallingTests.OverridesObject(42) self.assertTrue(isinstance(object_, GIMarshallingTests.OverridesObject)) # Test that the alternate constructor has been overridden. object_ = GIMarshallingTests.OverridesObject.new(42) self.assertTrue(isinstance(object_, GIMarshallingTests.OverridesObject)) # Test that the method has been overridden. self.assertEquals(6, object_.method()) # Test that the overrides wrapper has been registered. object_ = GIMarshallingTests.OverridesObject.returnv() self.assertTrue(isinstance(object_, GIMarshallingTests.OverridesObject)) def test_module_name(self): self.assertEquals(GIMarshallingTests.OverridesStruct.__module__, 'gi.overrides.GIMarshallingTests') self.assertEquals(GObject.InitiallyUnowned.__module__, 'gi.repository.GObject') class TestDir(unittest.TestCase): def test_members_list(self): list = dir(GIMarshallingTests) self.assertTrue('OverridesStruct' in list) self.assertTrue('BoxedStruct' in list) self.assertTrue('OVERRIDES_CONSTANT' in list) self.assertTrue('GEnum' in list) self.assertTrue('int32_return_max' in list) def test_modules_list(self): import gi.repository list = dir(gi.repository) self.assertTrue('GIMarshallingTests' in list) # FIXME: test to see if a module which was not imported is in the list # we should be listing every typelib we find, not just the ones # which are imported # # to test this I recommend we compile a fake module which # our tests would never import and check to see if it is # in the list: # # self.assertTrue('DoNotImportDummyTests' in list) class TestGErrorArrayInCrash(unittest.TestCase): # Previously there was a bug in invoke, in which C arrays were unwrapped # from inside GArrays to be passed to the C function. But when a GError was # set, invoke would attempt to free the C array as if it were a GArray. # This crash is only for C arrays. It does not happen for C functions which # take in GArrays. See https://bugzilla.gnome.org/show_bug.cgi?id=642708 def test_gerror_array_in_crash(self): self.assertRaises(GObject.GError, GIMarshallingTests.gerror_array_in, [1, 2, 3])
alexef/pygobject
tests/test_gi.py
Python
lgpl-2.1
67,093
package org.skyve.persistence; /** * */ public interface BizQL extends BeanQuery, ProjectedQuery, ScalarQuery, TupleQuery, PagedQuery, DMLQuery { public BizQL putParameter(String name, Object value); @Override public BizQL setFirstResult(int first); @Override public BizQL setMaxResults(int max); public int getTimeoutInSeconds(); public void setTimeoutInSeconds(int timeoutInSeconds); }
skyvers/wildcat
skyve-core/src/main/java/org/skyve/persistence/BizQL.java
Java
lgpl-2.1
405
package peersim.dht.base.Quarantine; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; import org.junit.runners.model.InitializationError; /** * Uses {@code QuarantiningUrlClassLoader} to load the test class, meaning the * {@code Quarantine} annotation can be used to ensure certain classes are * loaded separately. * * Use of a separate class loader allows classes to be reloaded for each test * class, which is handy when you're testing frameworks that make use of static * members. * * The selective quarantining is required because if the test class and its * 'children' are all loaded by a different class loader, then the {@code Test} * annotations yield different {@code Class} instances. JUnit then thinks there * are no runnable methods, because it looks them up by Class. */ public class QuarantiningRunner extends Runner { private final Object innerRunner; private final Class<?> innerRunnerClass; private final DelegateRunningToDiscoverer delegateRunningToDiscoverer; private final QuarantinedPatternDiscoverer quarantinedPatternDiscoverer; public QuarantiningRunner(Class<?> testFileClass) throws InitializationError { delegateRunningToDiscoverer = new DelegateRunningToDiscoverer(); quarantinedPatternDiscoverer = new QuarantinedPatternDiscoverer(); Class<? extends Runner> delegateRunningTo = delegateRunningToDiscoverer.getDelegateRunningToOn(testFileClass); String testFileClassName = testFileClass.getName(); String delegateRunningToClassName = delegateRunningTo.getName(); String[] quarantinedPatterns = quarantinedPatternDiscoverer.getQuarantinedPatternsOn(testFileClass); String[] allPatterns = Arrays.copyOf(quarantinedPatterns, quarantinedPatterns.length + 2); allPatterns[quarantinedPatterns.length] = testFileClassName; allPatterns[quarantinedPatterns.length + 1] = delegateRunningToClassName; QuarantiningUrlClassLoader classLoader = new QuarantiningUrlClassLoader(allPatterns); try { innerRunnerClass = classLoader.loadClass(delegateRunningToClassName); Class<?> testClass = classLoader.loadClass(testFileClassName); innerRunner = innerRunnerClass.cast(innerRunnerClass.getConstructor(Class.class).newInstance(testClass)); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) { throw new InitializationError(e); } } @Override public Description getDescription() { try { return (Description) innerRunnerClass.getMethod("getDescription").invoke(innerRunner); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new RuntimeException("Could not get description", e); } } @Override public void run(RunNotifier notifier) { try { innerRunnerClass.getMethod("run", RunNotifier.class).invoke(innerRunner, notifier); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { notifier.fireTestFailure(new Failure(getDescription(), e)); } } }
tbaumeist/peersim-generic-DHT
test/peersim/dht/base/Quarantine/QuarantiningRunner.java
Java
lgpl-2.1
3,396
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH & Co. KG, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.db; import org.opencms.ade.publish.CmsTooManyPublishResourcesException; import org.opencms.configuration.CmsConfigurationManager; import org.opencms.configuration.CmsSystemConfiguration; import org.opencms.db.generic.CmsPublishHistoryCleanupFilter; import org.opencms.db.log.CmsLogEntry; import org.opencms.db.log.CmsLogFilter; import org.opencms.db.urlname.CmsUrlNameMappingEntry; import org.opencms.db.urlname.CmsUrlNameMappingFilter; import org.opencms.file.CmsDataAccessException; import org.opencms.file.CmsFile; import org.opencms.file.CmsFolder; import org.opencms.file.CmsGroup; import org.opencms.file.CmsObject; import org.opencms.file.CmsProject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsRequestContext; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.CmsUser; import org.opencms.file.CmsUserSearchParameters; import org.opencms.file.CmsVfsException; import org.opencms.file.CmsVfsResourceAlreadyExistsException; import org.opencms.file.CmsVfsResourceNotFoundException; import org.opencms.file.history.CmsHistoryPrincipal; import org.opencms.file.history.CmsHistoryProject; import org.opencms.file.history.I_CmsHistoryResource; import org.opencms.file.types.CmsResourceTypeJsp; import org.opencms.gwt.shared.alias.CmsAliasImportResult; import org.opencms.gwt.shared.alias.CmsAliasMode; import org.opencms.i18n.CmsMessageContainer; import org.opencms.lock.CmsLock; import org.opencms.lock.CmsLockException; import org.opencms.lock.CmsLockFilter; import org.opencms.lock.CmsLockManager; import org.opencms.lock.CmsLockType; import org.opencms.main.CmsEvent; import org.opencms.main.CmsException; import org.opencms.main.CmsIllegalArgumentException; import org.opencms.main.CmsInitException; import org.opencms.main.CmsLog; import org.opencms.main.CmsMultiException; import org.opencms.main.I_CmsEventListener; import org.opencms.main.OpenCms; import org.opencms.publish.CmsPublishEngine; import org.opencms.relations.CmsLink; import org.opencms.relations.CmsRelation; import org.opencms.relations.CmsRelationFilter; import org.opencms.relations.CmsRelationType; import org.opencms.report.I_CmsReport; import org.opencms.security.CmsAccessControlEntry; import org.opencms.security.CmsAccessControlList; import org.opencms.security.CmsDefaultPermissionHandler; import org.opencms.security.CmsOrganizationalUnit; import org.opencms.security.CmsPermissionSet; import org.opencms.security.CmsPermissionSetCustom; import org.opencms.security.CmsPermissionViolationException; import org.opencms.security.CmsPrincipal; import org.opencms.security.CmsRole; import org.opencms.security.CmsRoleViolationException; import org.opencms.security.CmsSecurityException; import org.opencms.security.I_CmsPermissionHandler; import org.opencms.security.I_CmsPermissionHandler.LockCheck; import org.opencms.security.I_CmsPrincipal; import org.opencms.util.CmsFileUtil; import org.opencms.util.CmsStringUtil; import org.opencms.util.CmsUUID; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; /** * The OpenCms security manager.<p> * * The security manager checks the permissions required for a user action invoke by the Cms object. If permissions * are granted, the security manager invokes a method on the OpenCms driver manager to access the database.<p> * * @since 6.0.0 */ public final class CmsSecurityManager { /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsSecurityManager.class); /** The factory to create runtime info objects. */ protected I_CmsDbContextFactory m_dbContextFactory; /** The initialized OpenCms driver manager to access the database. */ protected CmsDriverManager m_driverManager; /** The lock manager. */ private CmsLockManager m_lockManager; /** Permission handler implementation. */ private I_CmsPermissionHandler m_permissionHandler; /** * Default constructor.<p> */ private CmsSecurityManager() { // intentionally left blank } /** * Creates a new instance of the OpenCms security manager.<p> * * @param configurationManager the configuration manager * @param runtimeInfoFactory the initialized OpenCms runtime info factory * @param publishEngine the publish engine * * @return a new instance of the OpenCms security manager * * @throws CmsInitException if the security manager could not be initialized */ public static CmsSecurityManager newInstance( CmsConfigurationManager configurationManager, I_CmsDbContextFactory runtimeInfoFactory, CmsPublishEngine publishEngine) throws CmsInitException { if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_2_INITIALIZING) { // OpenCms is already initialized throw new CmsInitException( org.opencms.main.Messages.get().container(org.opencms.main.Messages.ERR_ALREADY_INITIALIZED_0)); } CmsSecurityManager securityManager = new CmsSecurityManager(); securityManager.init(configurationManager, runtimeInfoFactory, publishEngine); return securityManager; } /** * Adds an alias.<p> * * @param context the current request context * @param alias the alias to add * @throws CmsException if something goes wrong */ public void addAlias(CmsRequestContext context, CmsAlias alias) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.addAlias(dbc, context.getCurrentProject(), alias); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); } finally { dbc.clear(); } } /** * Adds a new relation to a given resource.<p> * * @param context the request context * @param resource the resource to add the relation to * @param target the target of the relation * @param type the type of the relation * @param importCase if importing relations * * @throws CmsException if something goes wrong * * @see #deleteRelationsForResource(CmsRequestContext, CmsResource, CmsRelationFilter) * @see CmsObject#addRelationToResource(String, String, String) */ public void addRelationToResource( CmsRequestContext context, CmsResource resource, CmsResource target, CmsRelationType type, boolean importCase) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.addRelationToResource(dbc, resource, target, type, importCase); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_ADD_RELATION_TO_RESOURCE_3, context.getSitePath(resource), context.getSitePath(target), type), e); } finally { dbc.clear(); } } /** * Adds a resource to the given organizational unit.<p> * * @param context the current request context * @param orgUnit the organizational unit to add the resource to * @param resource the resource that is to be added to the organizational unit * * @throws CmsException if something goes wrong * * @see org.opencms.security.CmsOrgUnitManager#addResourceToOrgUnit(CmsObject, String, String) * @see org.opencms.security.CmsOrgUnitManager#removeResourceFromOrgUnit(CmsObject, String, String) */ public void addResourceToOrgUnit(CmsRequestContext context, CmsOrganizationalUnit orgUnit, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkRole(dbc, CmsRole.ADMINISTRATOR.forOrgUnit(orgUnit.getName())); m_driverManager.addResourceToOrgUnit(dbc, orgUnit, resource); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_ADD_RESOURCE_TO_ORGUNIT_2, orgUnit.getName(), dbc.removeSiteRoot(resource.getRootPath())), e); } finally { dbc.clear(); } } /** * Adds a user to a group.<p> * * @param context the current request context * @param username the name of the user that is to be added to the group * @param groupname the name of the group * @param readRoles if reading roles or groups * * @throws CmsException if operation was not successful */ public void addUserToGroup(CmsRequestContext context, String username, String groupname, boolean readRoles) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsRole role = CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(username)); checkRoleForUserModification(dbc, username, role); m_driverManager.addUserToGroup( dbc, CmsOrganizationalUnit.removeLeadingSeparator(username), CmsOrganizationalUnit.removeLeadingSeparator(groupname), readRoles); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_ADD_USER_GROUP_FAILED_2, username, groupname), e); } finally { dbc.clear(); } } /** * Changes the lock of a resource to the current user, that is "steals" the lock from another user.<p> * * @param context the current request context * @param resource the resource to change the lock for * * @throws CmsException if something goes wrong * * @see org.opencms.file.types.I_CmsResourceType#changeLock(CmsObject, CmsSecurityManager, CmsResource) */ public void changeLock(CmsRequestContext context, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); checkOfflineProject(dbc); try { m_driverManager.changeLock(dbc, resource, CmsLockType.EXCLUSIVE); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_CHANGE_LOCK_OF_RESOURCE_2, context.getSitePath(resource), " - " + e.getMessage()), e); } finally { dbc.clear(); } } /** * Returns a list with all sub resources of a given folder that have set the given property, * matching the current property's value with the given old value and replacing it by a given new value.<p> * * @param context the current request context * @param resource the resource on which property definition values are changed * @param propertyDefinition the name of the property definition to change the value * @param oldValue the old value of the property definition * @param newValue the new value of the property definition * @param recursive if true, change recursively all property values on sub-resources (only for folders) * * @return a list with the <code>{@link CmsResource}</code>'s where the property value has been changed * * @throws CmsVfsException for now only when the search for the old value fails * @throws CmsException if operation was not successful */ public synchronized List<CmsResource> changeResourcesInFolderWithProperty( CmsRequestContext context, CmsResource resource, String propertyDefinition, String oldValue, String newValue, boolean recursive) throws CmsException, CmsVfsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsResource> result = null; try { result = m_driverManager.changeResourcesInFolderWithProperty( dbc, resource, propertyDefinition, oldValue, newValue, recursive); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_CHANGE_RESOURCES_IN_FOLDER_WITH_PROP_4, new Object[] {propertyDefinition, oldValue, newValue, context.getSitePath(resource)}), e); } finally { dbc.clear(); } return result; } /** * Checks if the current user has management access to the given project.<p> * * @param dbc the current database context * @param project the project to check * * @throws CmsRoleViolationException if the user does not have the required role permissions */ public void checkManagerOfProjectRole(CmsDbContext dbc, CmsProject project) throws CmsRoleViolationException { boolean hasRole = false; try { if (hasRole(dbc, dbc.currentUser(), CmsRole.ROOT_ADMIN)) { return; } hasRole = m_driverManager.getAllManageableProjects( dbc, m_driverManager.readOrganizationalUnit(dbc, project.getOuFqn()), false).contains(project); } catch (CmsException e) { // should never happen if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } } if (!hasRole) { throw new CmsRoleViolationException( org.opencms.security.Messages.get().container( org.opencms.security.Messages.ERR_NOT_MANAGER_OF_PROJECT_2, dbc.currentUser().getName(), dbc.currentProject().getName())); } } /** * Checks if the project in the given database context is not the "Online" project, * and throws an Exception if this is the case.<p> * * This is used to ensure a user is in an "Offline" project * before write access to VFS resources is granted.<p> * * @param dbc the current OpenCms users database context * * @throws CmsVfsException if the project in the given database context is the "Online" project */ public void checkOfflineProject(CmsDbContext dbc) throws CmsVfsException { if (dbc.currentProject().isOnlineProject()) { throw new CmsVfsException( org.opencms.file.Messages.get().container( org.opencms.file.Messages.ERR_NOT_ALLOWED_IN_ONLINE_PROJECT_0)); } } /** * Performs a blocking permission check on a resource.<p> * * If the required permissions are not satisfied by the permissions the user has on the resource, * an exception is thrown.<p> * * @param context the current request context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required to access the resource * @param checkLock if true, the lock status of the resource is also checked * @param filter the filter for the resource * * @throws CmsException in case of any i/o error * @throws CmsSecurityException if the required permissions are not satisfied * * @see #checkPermissions(CmsRequestContext, CmsResource, CmsPermissionSet, I_CmsPermissionHandler.CmsPermissionCheckResult) */ public void checkPermissions( CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions, boolean checkLock, CmsResourceFilter filter) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check the access permissions checkPermissions(dbc, resource, requiredPermissions, checkLock, filter); } finally { dbc.clear(); } } /** * Checks if the current user has the permissions to publish the given publish list * (which contains the information about the resources / project to publish).<p> * * @param dbc the current OpenCms users database context * @param publishList the publish list to check (contains the information about the resources / project to publish) * * @throws CmsException if the user does not have the required permissions because of project lock state * @throws CmsMultiException if issues occur like a direct publish is attempted on a resource * whose parent folder is new or deleted in the offline project, * or if the current user has no management access to the current project */ public void checkPublishPermissions(CmsDbContext dbc, CmsPublishList publishList) throws CmsException, CmsMultiException { // is the current project an "offline" project? checkOfflineProject(dbc); // check if this is a "direct publish" attempt if (!publishList.isDirectPublish()) { // check if the user is a manager of the current project, in this case he has publish permissions checkManagerOfProjectRole(dbc, dbc.getRequestContext().getCurrentProject()); } else { // direct publish, create exception containers CmsMultiException resourceIssues = new CmsMultiException(); CmsMultiException permissionIssues = new CmsMultiException(); // iterate all resources in the direct publish list Iterator<CmsResource> it = publishList.getDirectPublishResources().iterator(); List<String> parentFolders = new ArrayList<String>(); while (it.hasNext()) { CmsResource res = it.next(); // the parent folder must not be new or deleted String parentFolder = CmsResource.getParentFolder(res.getRootPath()); if ((parentFolder != null) && !parentFolders.contains(parentFolder)) { // check each parent folder only once CmsResource parent = readResource(dbc, parentFolder, CmsResourceFilter.ALL); if (parent.getState().isDeleted()) { if (!(publishList.isUserPublishList() && publishList.getDeletedFolderList().contains(parent))) { // parent folder is deleted - direct publish not allowed resourceIssues.addException( new CmsVfsException( Messages.get().container( Messages.ERR_DIRECT_PUBLISH_PARENT_DELETED_2, dbc.getRequestContext().removeSiteRoot(res.getRootPath()), parentFolder))); } } if (parent.getState().isNew()) { if (!(publishList.isUserPublishList() && publishList.getFolderList().contains(parent))) { // parent folder is new - direct publish not allowed resourceIssues.addException( new CmsVfsException( Messages.get().container( Messages.ERR_DIRECT_PUBLISH_PARENT_NEW_2, dbc.removeSiteRoot(res.getRootPath()), parentFolder))); } } // add checked parent folder to prevent duplicate checks parentFolders.add(parentFolder); } // check if the user has the explicit permission to direct publish the selected resource if (I_CmsPermissionHandler.PERM_ALLOWED != hasPermissions( dbc.getRequestContext(), res, CmsPermissionSet.ACCESS_DIRECT_PUBLISH, true, CmsResourceFilter.ALL)) { // the user has no "direct publish" permissions on the resource permissionIssues.addException( new CmsSecurityException( Messages.get().container( Messages.ERR_DIRECT_PUBLISH_NO_PERMISSIONS_1, dbc.removeSiteRoot(res.getRootPath())))); } } if (resourceIssues.hasExceptions() || permissionIssues.hasExceptions()) { // there are issues, permission check has failed resourceIssues.addExceptions(permissionIssues.getExceptions()); throw resourceIssues; } } // no issues have been found , permissions are granted } /** * Checks if the user of the current database context has permissions to impersonate the given role * in the given organizational unit.<p> * * If the organizational unit is <code>null</code>, this method will check if the * given user has the given role for at least one organizational unit.<p> * * @param dbc the current OpenCms users database context * @param role the role to check * * @throws CmsRoleViolationException if the user does not have the required role permissions * * @see org.opencms.security.CmsRoleManager#checkRole(CmsObject, CmsRole) */ public void checkRole(CmsDbContext dbc, CmsRole role) throws CmsRoleViolationException { if (!hasRole(dbc, dbc.currentUser(), role)) { if (role.getOuFqn() != null) { throw role.createRoleViolationExceptionForOrgUnit(dbc.getRequestContext(), role.getOuFqn()); } else { throw role.createRoleViolationException(dbc.getRequestContext()); } } } /** * Checks if the user of the current context has permissions to impersonate the given role.<p> * * If the organizational unit is <code>null</code>, this method will check if the * given user has the given role for at least one organizational unit.<p> * * @param context the current request context * @param role the role to check * * @throws CmsRoleViolationException if the user does not have the required role permissions */ public void checkRole(CmsRequestContext context, CmsRole role) throws CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, role); } finally { dbc.clear(); } } /** * Checks if the user of the current database context has permissions to impersonate the given role * for the given resource.<p> * * @param dbc the current OpenCms users database context * @param role the role to check * @param resource the resource to check the role for * * @throws CmsRoleViolationException if the user does not have the required role permissions * * @see org.opencms.security.CmsRoleManager#checkRole(CmsObject, CmsRole) */ public void checkRoleForResource(CmsDbContext dbc, CmsRole role, CmsResource resource) throws CmsRoleViolationException { if (!hasRoleForResource(dbc, dbc.currentUser(), role, resource)) { throw role.createRoleViolationExceptionForResource(dbc.getRequestContext(), resource); } } /** * Checks if the user of the current context has permissions to impersonate the given role * for the given resource.<p> * * @param context the current request context * @param role the role to check * @param resource the resource to check the role for * * @throws CmsRoleViolationException if the user does not have the required role permissions */ public void checkRoleForResource(CmsRequestContext context, CmsRole role, CmsResource resource) throws CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRoleForResource(dbc, role, resource); } finally { dbc.clear(); } } /** * Changes the resource flags of a resource.<p> * * The resource flags are used to indicate various "special" conditions * for a resource. Most notably, the "internal only" setting which signals * that a resource can not be directly requested with it's URL.<p> * * @param context the current request context * @param resource the resource to change the flags for * @param flags the new resource flags for this resource * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (({@link CmsPermissionSet#ACCESS_WRITE} required) * * @see org.opencms.file.types.I_CmsResourceType#chflags(CmsObject, CmsSecurityManager, CmsResource, int) */ public void chflags(CmsRequestContext context, CmsResource resource, int flags) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.chflags(dbc, resource, flags); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_CHANGE_RESOURCE_FLAGS_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Changes the resource type of a resource.<p> * * OpenCms handles resources according to the resource type, * not the file suffix. This is e.g. why a JSP in OpenCms can have the * suffix ".html" instead of ".jsp" only. Changing the resource type * makes sense e.g. if you want to make a plain text file a JSP resource, * or a binary file an image, etc.<p> * * @param context the current request context * @param resource the resource to change the type for * @param type the new resource type for this resource * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (({@link CmsPermissionSet#ACCESS_WRITE} required)) * * @see org.opencms.file.types.I_CmsResourceType#chtype(CmsObject, CmsSecurityManager, CmsResource, int) * @see CmsObject#chtype(String, int) */ @SuppressWarnings("javadoc") public void chtype(CmsRequestContext context, CmsResource resource, int type) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); if (CmsResourceTypeJsp.isJspTypeId(type)) { // security check preventing the creation of a jsp file without permissions checkRoleForResource(dbc, CmsRole.VFS_MANAGER, resource); } m_driverManager.chtype(dbc, resource, type); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_CHANGE_RESOURCE_TYPE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Cleans up publish history entries according to the given filter object. * * @param context the request context * @param filter the filter describing what to clean up * @return the number of cleaned up rows * @throws CmsException if something goes wrong */ public int cleanupPublishHistory(CmsRequestContext context, CmsPublishHistoryCleanupFilter filter) throws CmsException { checkRole(context, CmsRole.VFS_MANAGER); CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { return m_driverManager.cleanupPublishHistory(dbc, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); return 0; } finally { dbc.clear(); } } /** * Copies the access control entries of a given resource to a destination resource.<p> * * Already existing access control entries of the destination resource are removed.<p> * * @param context the current request context * @param source the resource to copy the access control entries from * @param destination the resource to which the access control entries are copied * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_CONTROL} required) */ public void copyAccessControlEntries(CmsRequestContext context, CmsResource source, CmsResource destination) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, source, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); checkPermissions(dbc, destination, CmsPermissionSet.ACCESS_CONTROL, true, CmsResourceFilter.ALL); m_driverManager.copyAccessControlEntries(dbc, source, destination, true); } catch (Exception e) { CmsRequestContext rc = context; dbc.report( null, Messages.get().container( Messages.ERR_COPY_ACE_2, rc.removeSiteRoot(source.getRootPath()), rc.removeSiteRoot(destination.getRootPath())), e); } finally { dbc.clear(); } } /** * Copies a resource.<p> * * You must ensure that the destination path is an absolute, valid and * existing VFS path. Relative paths from the source are currently not supported.<p> * * The copied resource will always be locked to the current user * after the copy operation.<p> * * In case the target resource already exists, it is overwritten with the * source resource.<p> * * The <code>siblingMode</code> parameter controls how to handle siblings * during the copy operation.<br> * Possible values for this parameter are: <br> * <ul> * <li><code>{@link org.opencms.file.CmsResource#COPY_AS_NEW}</code></li> * <li><code>{@link org.opencms.file.CmsResource#COPY_AS_SIBLING}</code></li> * <li><code>{@link org.opencms.file.CmsResource#COPY_PRESERVE_SIBLING}</code></li> * </ul><p> * * @param context the current request context * @param source the resource to copy * @param destination the name of the copy destination with complete path * @param siblingMode indicates how to handle siblings during copy * * @throws CmsException if something goes wrong * @throws CmsSecurityException if resource could not be copied * * @see CmsObject#copyResource(String, String, CmsResource.CmsResourceCopyMode) * @see org.opencms.file.types.I_CmsResourceType#copyResource(CmsObject, CmsSecurityManager, CmsResource, String, CmsResource.CmsResourceCopyMode) */ public void copyResource( CmsRequestContext context, CmsResource source, String destination, CmsResource.CmsResourceCopyMode siblingMode) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, source, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); if (source.isFolder() && destination.startsWith(source.getRootPath())) { throw new CmsVfsException( Messages.get().container( Messages.ERR_RECURSIVE_INCLUSION_2, dbc.removeSiteRoot(source.getRootPath()), dbc.removeSiteRoot(destination))); } // target permissions will be checked later m_driverManager.copyResource(dbc, source, destination, siblingMode); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_COPY_RESOURCE_2, dbc.removeSiteRoot(source.getRootPath()), dbc.removeSiteRoot(destination)), e); } finally { dbc.clear(); } } /** * Copies a resource to the current project of the user.<p> * * @param context the current request context * @param resource the resource to apply this operation to * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not have management access to the project * * @see org.opencms.file.types.I_CmsResourceType#copyResourceToProject(CmsObject, CmsSecurityManager, CmsResource) */ public void copyResourceToProject(CmsRequestContext context, CmsResource resource) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkManagerOfProjectRole(dbc, context.getCurrentProject()); m_driverManager.copyResourceToProject(dbc, resource); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_COPY_RESOURCE_TO_PROJECT_2, context.getSitePath(resource), context.getCurrentProject().getName()), e); } finally { dbc.clear(); } } /** * Counts the locked resources in this project.<p> * * @param context the current request context * @param id the id of the project * * @return the amount of locked resources in this project * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not have management access to the project */ public int countLockedResources(CmsRequestContext context, CmsUUID id) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject project = null; int result = 0; try { project = m_driverManager.readProject(dbc, id); checkManagerOfProjectRole(dbc, project); result = m_driverManager.countLockedResources(project); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_COUNT_LOCKED_RESOURCES_PROJECT_2, (project == null) ? "<failed to read>" : project.getName(), id), e); } finally { dbc.clear(); } return result; } /** * Counts the total number of users which match the given search criteria.<p> * * @param requestContext the request context * @param searchParams the search criteria object * * @return the number of users which match the search criteria * @throws CmsException if something goes wrong */ public long countUsers(CmsRequestContext requestContext, CmsUserSearchParameters searchParams) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(requestContext); try { return m_driverManager.countUsers(dbc, searchParams); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_COUNT_USERS_0), e); return -1; } finally { dbc.clear(); } } /** * Creates a new user group.<p> * * @param context the current request context * @param name the name of the new group * @param description the description for the new group * @param flags the flags for the new group * @param parent the name of the parent group (or <code>null</code>) * * @return a <code>{@link CmsGroup}</code> object representing the newly created group * * @throws CmsException if operation was not successful. * @throws CmsRoleViolationException if the role {@link CmsRole#ACCOUNT_MANAGER} is not owned by the current user */ public CmsGroup createGroup(CmsRequestContext context, String name, String description, int flags, String parent) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { checkRole(dbc, CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(name))); result = m_driverManager.createGroup(dbc, new CmsUUID(), name, description, flags, parent); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_GROUP_1, name), e); } finally { dbc.clear(); } return result; } /** * Creates a new organizational unit.<p> * * @param context the current request context * @param ouFqn the fully qualified name of the new organizational unit * @param description the description of the new organizational unit * @param flags the flags for the new organizational unit * @param resource the first associated resource * * @return a <code>{@link CmsOrganizationalUnit}</code> object representing * the newly created organizational unit * * @throws CmsException if operation was not successful * * @see org.opencms.security.CmsOrgUnitManager#createOrganizationalUnit(CmsObject, String, String, int, String) */ public CmsOrganizationalUnit createOrganizationalUnit( CmsRequestContext context, String ouFqn, String description, int flags, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsOrganizationalUnit result = null; try { checkRole(dbc, CmsRole.ADMINISTRATOR.forOrgUnit(getParentOrganizationalUnit(ouFqn))); checkOfflineProject(dbc); result = m_driverManager.createOrganizationalUnit( dbc, CmsOrganizationalUnit.removeLeadingSeparator(ouFqn), description, flags, resource); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_ORGUNIT_1, ouFqn), e); } finally { dbc.clear(); } return result; } /** * Creates a project.<p> * * @param context the current request context * @param name the name of the project to create * @param description the description of the project * @param groupname the project user group to be set * @param managergroupname the project manager group to be set * @param projecttype the type of the project * * @return the created project * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#PROJECT_MANAGER} */ public CmsProject createProject( CmsRequestContext context, String name, String description, String groupname, String managergroupname, CmsProject.CmsProjectType projecttype) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject result = null; try { checkRole(dbc, CmsRole.PROJECT_MANAGER.forOrgUnit(getParentOrganizationalUnit(name))); result = m_driverManager.createProject( dbc, CmsOrganizationalUnit.removeLeadingSeparator(name), description, CmsOrganizationalUnit.removeLeadingSeparator(groupname), CmsOrganizationalUnit.removeLeadingSeparator(managergroupname), projecttype); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_PROJECT_1, name), e); } finally { dbc.clear(); } return result; } /** * Creates a property definition.<p> * * Property definitions are valid for all resource types.<p> * * @param context the current request context * @param name the name of the property definition to create * * @return the created property definition * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the current project is online. * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#WORKPLACE_MANAGER} */ public CmsPropertyDefinition createPropertyDefinition(CmsRequestContext context, String name) throws CmsException, CmsSecurityException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsPropertyDefinition result = null; try { checkOfflineProject(dbc); checkRole(dbc, CmsRole.WORKPLACE_MANAGER.forOrgUnit(null)); result = m_driverManager.createPropertyDefinition(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_PROPDEF_1, name), e); } finally { dbc.clear(); } return result; } /** * Creates a new resource with the provided content and properties.<p> * An exception is thrown if a resource with the given name already exists.<p> * * @param context the current request context * @param resourcePath the name of the resource to create (full path) * @param resource the new resource to create * @param content the content for the new resource * @param properties the properties for the new resource * * @return the created resource * * @throws CmsVfsResourceAlreadyExistsException if a resource with the given name already exists * @throws CmsVfsException if the project in the given database context is the "Online" project * @throws CmsException if something goes wrong */ public CmsResource createResource( CmsRequestContext context, String resourcePath, CmsResource resource, byte[] content, List<CmsProperty> properties) throws CmsVfsResourceAlreadyExistsException, CmsVfsException, CmsException { if (existsResource(context, resourcePath, CmsResourceFilter.IGNORE_EXPIRATION)) { // check if the resource already exists by name throw new CmsVfsResourceAlreadyExistsException( org.opencms.db.generic.Messages.get().container( org.opencms.db.generic.Messages.ERR_RESOURCE_WITH_NAME_ALREADY_EXISTS_1, resource.getRootPath())); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsResource newResource = null; try { checkOfflineProject(dbc); newResource = m_driverManager.createResource(dbc, resourcePath, resource, content, properties, false); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_IMPORT_RESOURCE_2, context.getSitePath(resource), resourcePath), e); } finally { dbc.clear(); } return newResource; } /** * Creates a new resource of the given resource type with the provided content and properties.<p> * * If the provided content is null and the resource is not a folder, the content will be set to an empty byte array.<p> * * @param context the current request context * @param resourcename the name of the resource to create (full path) * @param type the type of the resource to create * @param content the content for the new resource * @param properties the properties for the new resource * * @return the created resource * * @throws CmsException if something goes wrong * * @see org.opencms.file.types.I_CmsResourceType#createResource(CmsObject, CmsSecurityManager, String, byte[], List) */ public synchronized CmsResource createResource( CmsRequestContext context, String resourcename, int type, byte[] content, List<CmsProperty> properties) throws CmsException { String checkExistsPath = "/".equals(resourcename) ? "/" : CmsFileUtil.removeTrailingSeparator(resourcename); // We use checkExistsPath instead of resourcename because when creating a folder /foo/bar/, we want to fail // if a file /foo/bar already exists. if (existsResource(context, checkExistsPath, CmsResourceFilter.ALL)) { // check if the resource already exists by name throw new CmsVfsResourceAlreadyExistsException( org.opencms.db.generic.Messages.get().container( org.opencms.db.generic.Messages.ERR_RESOURCE_WITH_NAME_ALREADY_EXISTS_1, resourcename)); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsResource newResource = null; try { checkOfflineProject(dbc); newResource = m_driverManager.createResource(dbc, resourcename, type, content, properties); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_RESOURCE_1, resourcename), e); } finally { dbc.clear(); } return newResource; } /** * Creates a new sibling of the source resource.<p> * * @param context the current request context * @param source the resource to create a sibling for * @param destination the name of the sibling to create with complete path * @param properties the individual properties for the new sibling * * @return the new created sibling * * @throws CmsException if something goes wrong * * @see org.opencms.file.types.I_CmsResourceType#createSibling(CmsObject, CmsSecurityManager, CmsResource, String, List) */ public CmsResource createSibling( CmsRequestContext context, CmsResource source, String destination, List<CmsProperty> properties) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsResource sibling = null; try { checkOfflineProject(dbc); sibling = m_driverManager.createSibling(dbc, source, destination, properties); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_CREATE_SIBLING_1, context.removeSiteRoot(source.getRootPath())), e); } finally { dbc.clear(); } return sibling; } /** * Creates the project for the temporary workplace files.<p> * * @param context the current request context * * @return the created project for the temporary workplace files * * @throws CmsException if something goes wrong */ public CmsProject createTempfileProject(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject result = null; try { checkRole(dbc, CmsRole.PROJECT_MANAGER.forOrgUnit(null)); result = m_driverManager.createTempfileProject(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_TEMPFILE_PROJECT_0), e); } finally { dbc.clear(); } return result; } /** * Creates a new user.<p> * * @param context the current request context * @param name the name for the new user * @param password the password for the new user * @param description the description for the new user * @param additionalInfos the additional infos for the user * * @return the created user * * @see CmsObject#createUser(String, String, String, Map) * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#ACCOUNT_MANAGER} */ public CmsUser createUser( CmsRequestContext context, String name, String password, String description, Map<String, Object> additionalInfos) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { checkRole(dbc, CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(name))); result = m_driverManager.createUser( dbc, CmsOrganizationalUnit.removeLeadingSeparator(name), password, description, additionalInfos); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_CREATE_USER_1, name), e); } finally { dbc.clear(); } return result; } /** * Deletes alias entries matching a filter.<p> * * @param context the request context * @param filter the alias filter * * @throws CmsException if something goes wrong */ public void deleteAliases(CmsRequestContext context, CmsAliasFilter filter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.deleteAliases(dbc, context.getCurrentProject(), filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); } finally { dbc.clear(); } } /** * Deletes all entries in the published resource table.<p> * * @param context the current request context * @param linkType the type of resource deleted (0= non-parameter, 1=parameter) * * @throws CmsException if something goes wrong */ public void deleteAllStaticExportPublishedResources(CmsRequestContext context, int linkType) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.deleteAllStaticExportPublishedResources(dbc, linkType); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_STATEXP_PUBLISHED_RESOURCES_0), e); } finally { dbc.clear(); } } /** * Deletes a group, where all permissions, users and children of the group * are transfered to a replacement group.<p> * * @param context the current request context * @param groupId the id of the group to be deleted * @param replacementId the id of the group to be transfered, can be <code>null</code> * * @throws CmsException if operation was not successful * @throws CmsSecurityException if the group is a default group. * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#ACCOUNT_MANAGER} */ public void deleteGroup(CmsRequestContext context, CmsUUID groupId, CmsUUID replacementId) throws CmsException, CmsRoleViolationException, CmsSecurityException { CmsGroup group = readGroup(context, groupId); if (group.isRole()) { throw new CmsSecurityException(Messages.get().container(Messages.ERR_DELETE_ROLE_GROUP_1, group.getName())); } CmsDbContext dbc = null; try { dbc = getDbContextForDeletePrincipal(context); // catch own exception as special cause for general "Error deleting group". checkRole(dbc, CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(group.getName()))); m_driverManager.deleteGroup(dbc, group, replacementId); } catch (Exception e) { CmsDbContext dbcForException = m_dbContextFactory.getDbContext(context); dbcForException.report(null, Messages.get().container(Messages.ERR_DELETE_GROUP_1, group.getName()), e); dbcForException.clear(); } finally { if (null != dbc) { dbc.clear(); } } } /** * Delete a user group.<p> * * Only groups that contain no subgroups can be deleted.<p> * * @param context the current request context * @param name the name of the group that is to be deleted * * @throws CmsException if operation was not successful * @throws CmsSecurityException if the group is a default group. * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#ACCOUNT_MANAGER} */ public void deleteGroup(CmsRequestContext context, String name) throws CmsException, CmsRoleViolationException, CmsSecurityException { CmsGroup group = readGroup(context, name); if (group.isRole()) { throw new CmsSecurityException(Messages.get().container(Messages.ERR_DELETE_ROLE_GROUP_1, name)); } CmsDbContext dbc = null; try { dbc = getDbContextForDeletePrincipal(context); // catch own exception as special cause for general "Error deleting group". checkRole(dbc, CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(name))); m_driverManager.deleteGroup(dbc, group, null); } catch (Exception e) { CmsDbContext dbcForException = m_dbContextFactory.getDbContext(context); dbcForException.report(null, Messages.get().container(Messages.ERR_DELETE_GROUP_1, name), e); dbcForException.clear(); } finally { if (null != dbc) { dbc.clear(); } } } /** * Deletes the versions from the history tables, keeping the given number of versions per resource.<p> * * @param context the current request context * @param versionsToKeep number of versions to keep, is ignored if negative * @param versionsDeleted number of versions to keep for deleted resources, is ignored if negative * @param timeDeleted deleted resources older than this will also be deleted, is ignored if negative * @param report the report for output logging * * @throws CmsException if operation was not successful * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#WORKPLACE_MANAGER} */ public void deleteHistoricalVersions( CmsRequestContext context, int versionsToKeep, int versionsDeleted, long timeDeleted, I_CmsReport report) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsFolder root = readFolder(dbc, "/", CmsResourceFilter.ALL); checkRole(dbc, CmsRole.WORKPLACE_MANAGER.forOrgUnit(null)); checkPermissions(dbc, root, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); m_driverManager.deleteHistoricalVersions(dbc, versionsToKeep, versionsDeleted, timeDeleted, report); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_DELETE_HISTORY_4, new Object[] { "/", new Integer(versionsToKeep), new Integer(versionsDeleted), new Date(timeDeleted)}), e); } finally { dbc.clear(); } } /** * Deletes all log entries matching the given filter.<p> * * @param context the current user context * @param filter the filter to use for deletion * * @throws CmsException if something goes wrong * * @see #getLogEntries(CmsRequestContext, CmsLogFilter) * @see CmsObject#deleteLogEntries(CmsLogFilter) */ public void deleteLogEntries(CmsRequestContext context, CmsLogFilter filter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.WORKPLACE_MANAGER); m_driverManager.deleteLogEntries(dbc, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_LOG_0), e); } finally { dbc.clear(); } } /** * Deletes an organizational unit.<p> * * Only organizational units that contain no sub organizational unit can be deleted.<p> * * The organizational unit can not be delete if it is used in the request context, * or if the current user belongs to it.<p> * * All users and groups in the given organizational unit will be deleted.<p> * * @param context the current request context * @param organizationalUnit the organizational unit to delete * * @throws CmsException if operation was not successful * * @see org.opencms.security.CmsOrgUnitManager#deleteOrganizationalUnit(CmsObject, String) */ public void deleteOrganizationalUnit(CmsRequestContext context, CmsOrganizationalUnit organizationalUnit) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check for root ou if (organizationalUnit.getParentFqn() == null) { throw new CmsDataAccessException( org.opencms.security.Messages.get().container( org.opencms.security.Messages.ERR_ORGUNIT_ROOT_EDITION_0)); } checkRole(dbc, CmsRole.ADMINISTRATOR.forOrgUnit(getParentOrganizationalUnit(organizationalUnit.getName()))); checkOfflineProject(dbc); m_driverManager.deleteOrganizationalUnit(dbc, organizationalUnit); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_ORGUNIT_1, organizationalUnit.getName()), e); } finally { dbc.clear(); } } /** * Deletes a project.<p> * * All modified resources currently inside this project will be reset to their online state.<p> * * @param context the current request context * @param projectId the ID of the project to be deleted * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not own management access to the project */ public void deleteProject(CmsRequestContext context, CmsUUID projectId) throws CmsException, CmsRoleViolationException { if (projectId.equals(CmsProject.ONLINE_PROJECT_ID)) { // online project must not be deleted throw new CmsVfsException( org.opencms.file.Messages.get().container( org.opencms.file.Messages.ERR_NOT_ALLOWED_IN_ONLINE_PROJECT_0)); } CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject deleteProject = null; try { // read the project that should be deleted deleteProject = m_driverManager.readProject(dbc, projectId); checkManagerOfProjectRole(dbc, deleteProject); m_driverManager.deleteProject(dbc, deleteProject); } catch (Exception e) { String projectName = (deleteProject == null ? String.valueOf(projectId) : deleteProject.getName()); dbc.report(null, Messages.get().container(Messages.ERR_DELETE_PROJECT_1, projectName), e); } finally { dbc.clear(); } } /** * Deletes a property definition.<p> * * @param context the current request context * @param name the name of the property definition to delete * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the project to delete is the "Online" project * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#WORKPLACE_MANAGER} */ public void deletePropertyDefinition(CmsRequestContext context, String name) throws CmsException, CmsSecurityException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkRole(dbc, CmsRole.WORKPLACE_MANAGER.forOrgUnit(null)); m_driverManager.deletePropertyDefinition(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DELETE_PROPERTY_1, name), e); } finally { dbc.clear(); } } /** * Deletes all relations for the given resource matching the given filter.<p> * * @param context the current user context * @param resource the resource to delete the relations for * @param filter the filter to use for deletion * * @throws CmsException if something goes wrong * * @see #addRelationToResource(CmsRequestContext, CmsResource, CmsResource, CmsRelationType, boolean) * @see CmsObject#deleteRelationsFromResource(String, CmsRelationFilter) */ public void deleteRelationsForResource(CmsRequestContext context, CmsResource resource, CmsRelationFilter filter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.deleteRelationsForResource(dbc, resource, filter); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_DELETE_RELATIONS_1, dbc.removeSiteRoot(resource.getRootPath())), e); } finally { dbc.clear(); } } /** * Deletes a resource given its name.<p> * * The <code>siblingMode</code> parameter controls how to handle siblings * during the delete operation.<br> * Possible values for this parameter are: <br> * <ul> * <li><code>{@link CmsResource#DELETE_REMOVE_SIBLINGS}</code></li> * <li><code>{@link CmsResource#DELETE_PRESERVE_SIBLINGS}</code></li> * </ul><p> * * @param context the current request context * @param resource the name of the resource to delete (full path) * @param siblingMode indicates how to handle siblings of the deleted resource * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user does not have {@link CmsPermissionSet#ACCESS_WRITE} on the given resource * * @see org.opencms.file.types.I_CmsResourceType#deleteResource(CmsObject, CmsSecurityManager, CmsResource, CmsResource.CmsResourceDeleteMode) */ public void deleteResource( CmsRequestContext context, CmsResource resource, CmsResource.CmsResourceDeleteMode siblingMode) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(context); final CmsUUID forbiddenFolderId = OpenCms.getPublishManager().getPublishListVerifier().addForbiddenParentFolder( resource.getRootPath(), Messages.get().getBundle(locale).key(Messages.ERR_FORBIDDEN_PARENT_CURRENTLY_DELETING_0)); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); checkSystemLocks(dbc, resource); // check write permissions for subresources in case of deleting a folder if (resource.isFolder()) { dbc.getRequestContext().setAttribute(I_CmsVfsDriver.REQ_ATTR_CHECK_PERMISSIONS, Boolean.TRUE); try { m_driverManager.getVfsDriver(dbc).removeFolder(dbc, dbc.currentProject(), resource); } catch (CmsDataAccessException e) { // unwrap the permission violation exception if (e.getCause() instanceof CmsPermissionViolationException) { throw (CmsPermissionViolationException)e.getCause(); } else { throw e; } } dbc.getRequestContext().removeAttribute(I_CmsVfsDriver.REQ_ATTR_CHECK_PERMISSIONS); } deleteResource(dbc, resource, siblingMode); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_DELETE_RESOURCE_1, context.getSitePath(resource)), e); } finally { OpenCms.getPublishManager().getPublishListVerifier().removeForbiddenParentFolder(forbiddenFolderId); dbc.clear(); } } /** * Deletes an entry in the published resource table.<p> * * @param context the current request context * @param resourceName The name of the resource to be deleted in the static export * @param linkType the type of resource deleted (0= non-parameter, 1=parameter) * @param linkParameter the parameters of the resource * * @throws CmsException if something goes wrong */ public void deleteStaticExportPublishedResource( CmsRequestContext context, String resourceName, int linkType, String linkParameter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.deleteStaticExportPublishedResource(dbc, resourceName, linkType, linkParameter); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_DELETE_STATEXP_PUBLISHES_RESOURCE_1, resourceName), e); } finally { dbc.clear(); } } /** * Deletes a user.<p> * * @param context the current request context * @param userId the Id of the user to be deleted * * @throws CmsException if something goes wrong */ public void deleteUser(CmsRequestContext context, CmsUUID userId) throws CmsException { CmsUser user = readUser(context, userId); deleteUser(context, user, null); } /** * Deletes a user, where all permissions and resources attributes of the user * were transfered to a replacement user.<p> * * @param context the current request context * @param userId the id of the user to be deleted * @param replacementId the id of the user to be transfered * * @throws CmsException if operation was not successful */ public void deleteUser(CmsRequestContext context, CmsUUID userId, CmsUUID replacementId) throws CmsException { CmsUser user = readUser(context, userId); CmsUser replacementUser = null; if ((replacementId != null) && !replacementId.isNullUUID()) { replacementUser = readUser(context, replacementId); } deleteUser(context, user, replacementUser); } /** * Deletes a user.<p> * * @param context the current request context * @param username the name of the user to be deleted * * @throws CmsException if something goes wrong */ public void deleteUser(CmsRequestContext context, String username) throws CmsException { CmsUser user = readUser(context, username); deleteUser(context, user, null); } /** * Destroys this security manager.<p> * * @throws Throwable if something goes wrong */ public synchronized void destroy() throws Throwable { try { if (m_driverManager != null) { if (m_driverManager.getLockManager() != null) { try { writeLocks(); } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error( org.opencms.lock.Messages.get().getBundle().key( org.opencms.lock.Messages.ERR_WRITE_LOCKS_FINAL_0), t); } } } m_driverManager.destroy(); } } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_ERR_DRIVER_MANAGER_CLOSE_0), t); } } m_driverManager = null; m_dbContextFactory = null; if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info( Messages.get().getBundle().key(Messages.INIT_SECURITY_MANAGER_SHUTDOWN_1, this.getClass().getName())); } } /** * Checks the availability of a resource in the VFS, * using the <code>{@link CmsResourceFilter#DEFAULT}</code> filter.<p> * * A resource may be of type <code>{@link CmsFile}</code> or * <code>{@link CmsFolder}</code>.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * This method also takes into account the user permissions, so if * the given resource exists, but the current user has not the required * permissions, then this method will return <code>false</code>.<p> * * @param context the current request context * @param structureId the structure id of the resource to check * @param filter the resource filter to use while reading * * @return <code>true</code> if the resource is available * * @see CmsObject#existsResource(CmsUUID, CmsResourceFilter) * @see CmsObject#existsResource(CmsUUID) */ public boolean existsResource(CmsRequestContext context, CmsUUID structureId, CmsResourceFilter filter) { boolean result = false; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { readResource(dbc, structureId, filter); result = true; } catch (Exception e) { result = false; } finally { dbc.clear(); } return result; } /** * Checks the availability of a resource in the VFS, * using the <code>{@link CmsResourceFilter#DEFAULT}</code> filter.<p> * * A resource may be of type <code>{@link CmsFile}</code> or * <code>{@link CmsFolder}</code>.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * This method also takes into account the user permissions, so if * the given resource exists, but the current user has not the required * permissions, then this method will return <code>false</code>.<p> * * @param context the current request context * @param resourcePath the name of the resource to read (full path) * @param filter the resource filter to use while reading * * @return <code>true</code> if the resource is available * * @see CmsObject#existsResource(String, CmsResourceFilter) * @see CmsObject#existsResource(String) */ public boolean existsResource(CmsRequestContext context, String resourcePath, CmsResourceFilter filter) { boolean result = false; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { readResource(dbc, resourcePath, filter); result = true; } catch (Exception e) { result = false; } finally { dbc.clear(); } return result; } /** * Fills the given publish list with the the VFS resources that actually get published.<p> * * Please refer to the source code of this method for the rules on how to decide whether a * new/changed/deleted <code>{@link CmsResource}</code> object can be published or not.<p> * * @param context the current request context * @param publishList must be initialized with basic publish information (Project or direct publish operation) * * @return the given publish list filled with all new/changed/deleted files from the current (offline) project * that will be published actually * * @throws CmsException if something goes wrong * * @see org.opencms.db.CmsPublishList */ public CmsPublishList fillPublishList(CmsRequestContext context, CmsPublishList publishList) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.fillPublishList(dbc, publishList); checkPublishPermissions(dbc, publishList); } catch (CmsTooManyPublishResourcesException e) { throw e; } catch (Exception e) { if (publishList.isDirectPublish()) { dbc.report( null, Messages.get().container( Messages.ERR_GET_PUBLISH_LIST_DIRECT_1, CmsFileUtil.formatResourceNames(context, publishList.getDirectPublishResources())), e); } else { dbc.report( null, Messages.get().container( Messages.ERR_GET_PUBLISH_LIST_PROJECT_1, context.getCurrentProject().getName()), e); } } finally { dbc.clear(); } return publishList; } /** * Returns the list of access control entries of a resource given its name.<p> * * @param context the current request context * @param resource the resource to read the access control entries for * @param getInherited true if the result should include all access control entries inherited by parent folders * * @return a list of <code>{@link CmsAccessControlEntry}</code> objects defining all permissions for the given resource * * @throws CmsException if something goes wrong */ public List<CmsAccessControlEntry> getAccessControlEntries( CmsRequestContext context, CmsResource resource, boolean getInherited) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsAccessControlEntry> result = null; try { result = m_driverManager.getAccessControlEntries(dbc, resource, getInherited); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_GET_ACL_ENTRIES_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns the access control list (summarized access control entries) of a given resource.<p> * * If <code>inheritedOnly</code> is set, only inherited access control entries are returned.<p> * * @param context the current request context * @param resource the resource * @param inheritedOnly skip non-inherited entries if set * * @return the access control list of the resource * * @throws CmsException if something goes wrong */ public CmsAccessControlList getAccessControlList( CmsRequestContext context, CmsResource resource, boolean inheritedOnly) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsAccessControlList result = null; try { result = m_driverManager.getAccessControlList(dbc, resource, inheritedOnly); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_GET_ACL_ENTRIES_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Gets the aliases for a given site.<p> * * @param requestContext the current request context * @param siteRoot the site root * * @return the list of aliases for the given site root * * @throws CmsException if something goes wrong */ public List<CmsAlias> getAliasesForSite(CmsRequestContext requestContext, String siteRoot) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(requestContext); try { List<CmsAlias> aliases = m_driverManager.readAliasesBySite( dbc, requestContext.getCurrentProject(), siteRoot); return aliases; } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); return null; // will never be executed } finally { dbc.clear(); } } /** * Gets all access control entries.<p> * * @param context the current request context * @return the list of all access control entries * * @throws CmsException if something goes wrong */ public List<CmsAccessControlEntry> getAllAccessControlEntries(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsAccessControlEntry> result = null; try { result = m_driverManager.getAllAccessControlEntries(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_ACL_ENTRIES_1, "<all resources>"), e); } finally { dbc.clear(); } return result; } /** * Returns all projects which are owned by the current user or which are * accessible for the group of the user.<p> * * @param context the current request context * @param orgUnit the organizational unit to search project in * @param includeSubOus if to include sub organizational units * * @return a list of objects of type <code>{@link CmsProject}</code> * * @throws CmsException if something goes wrong */ public List<CmsProject> getAllAccessibleProjects( CmsRequestContext context, CmsOrganizationalUnit orgUnit, boolean includeSubOus) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsProject> result = null; try { result = m_driverManager.getAllAccessibleProjects(dbc, orgUnit, includeSubOus); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_GET_ALL_ACCESSIBLE_PROJECTS_1, dbc.currentUser().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns a list with all projects from history.<p> * * @param context the current request context * * @return list of <code>{@link CmsHistoryProject}</code> objects * with all projects from history. * * @throws CmsException if operation was not successful */ public List<CmsHistoryProject> getAllHistoricalProjects(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsHistoryProject> result = null; try { result = m_driverManager.getAllHistoricalProjects(dbc); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_GET_ALL_ACCESSIBLE_PROJECTS_1, dbc.currentUser().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns all projects which are owned by the current user or which are manageable * for the group of the user.<p> * * @param context the current request context * @param orgUnit the organizational unit to search project in * @param includeSubOus if to include sub organizational units * * @return a list of objects of type <code>{@link CmsProject}</code> * * @throws CmsException if operation was not successful */ public List<CmsProject> getAllManageableProjects( CmsRequestContext context, CmsOrganizationalUnit orgUnit, boolean includeSubOus) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsProject> result = null; try { result = m_driverManager.getAllManageableProjects(dbc, orgUnit, includeSubOus); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_GET_ALL_MANAGEABLE_PROJECTS_1, dbc.currentUser().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns all child groups of a group.<p> * * This method also returns all sub-child groups of the current group.<p> * * @param context the current request context * @param groupname the name of the group * @param includeSubChildren if set also returns all sub-child groups of the given group * * @return a list of all child <code>{@link CmsGroup}</code> objects or <code>null</code> * * @throws CmsException if operation was not successful */ public List<CmsGroup> getChildren(CmsRequestContext context, String groupname, boolean includeSubChildren) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsGroup> result = null; try { result = m_driverManager.getChildren( dbc, m_driverManager.readGroup(dbc, CmsOrganizationalUnit.removeLeadingSeparator(groupname)), includeSubChildren); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_CHILD_GROUPS_TRANSITIVE_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Gets a connection from a connection pool.<p> * @param poolUrl the connection pool url * @return a new connection from the pool * * @throws SQLException if getting the connection fails */ public Connection getConnection(String poolUrl) throws SQLException { CmsDbPoolV11 pool = CmsDriverManager.m_pools.get(poolUrl); return pool.getConnection(); } /** * Returns the date when the resource was last visited by the user.<p> * * @param context the request context * @param poolName the name of the database pool to use * @param user the user to check the date * @param resource the resource to check the date * * @return the date when the resource was last visited by the user * * @throws CmsException if something goes wrong */ public long getDateLastVisitedBy(CmsRequestContext context, String poolName, CmsUser user, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); long result = 0; try { result = m_driverManager.getDateLastVisitedBy(dbc, poolName, user, resource); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_GET_DATE_LASTVISITED_2, user.getName(), context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns all groups of the given organizational unit.<p> * * @param context the current request context * @param orgUnit the organizational unit to get the groups for * @param includeSubOus if all groups of sub-organizational units should be retrieved too * @param readRoles if to read roles or groups * * @return all <code>{@link CmsGroup}</code> objects in the organizational unit * * @throws CmsException if operation was not successful * * @see org.opencms.security.CmsOrgUnitManager#getResourcesForOrganizationalUnit(CmsObject, String) * @see org.opencms.security.CmsOrgUnitManager#getGroups(CmsObject, String, boolean) * @see org.opencms.security.CmsOrgUnitManager#getUsers(CmsObject, String, boolean) */ public List<CmsGroup> getGroups( CmsRequestContext context, CmsOrganizationalUnit orgUnit, boolean includeSubOus, boolean readRoles) throws CmsException { List<CmsGroup> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.getGroups(dbc, orgUnit, includeSubOus, readRoles); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_ORGUNIT_GROUPS_1, orgUnit.getName()), e); } finally { dbc.clear(); } return result; } /** * Returns the list of groups to which the user directly belongs to.<p> * * @param context the current request context * @param username The name of the user * @param ouFqn the fully qualified name of the organizational unit to restrict the result set for * @param includeChildOus include groups of child organizational units * @param readRoles if to read roles or groups * @param directGroupsOnly if set only the direct assigned groups will be returned, if not also indirect roles * @param remoteAddress the IP address to filter the groups in the result list * * @return a list of <code>{@link CmsGroup}</code> objects filtered by the given IP address * * @throws CmsException if operation was not successful */ public List<CmsGroup> getGroupsOfUser( CmsRequestContext context, String username, String ouFqn, boolean includeChildOus, boolean readRoles, boolean directGroupsOnly, String remoteAddress) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsGroup> result = null; try { result = m_driverManager.getGroupsOfUser( dbc, CmsOrganizationalUnit.removeLeadingSeparator(username), CmsOrganizationalUnit.removeLeadingSeparator(ouFqn), includeChildOus, readRoles, directGroupsOnly, remoteAddress); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_GROUPS_OF_USER_2, username, remoteAddress), e); } finally { dbc.clear(); } return result; } /** * Returns the lock state of a resource.<p> * * @param context the current request context * @param resource the resource to return the lock state for * * @return the lock state of the resource * * @throws CmsException if something goes wrong */ public CmsLock getLock(CmsRequestContext context, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsLock result = null; try { result = m_driverManager.getLock(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_LOCK_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns all locked resources in a given folder.<p> * * @param context the current request context * @param resource the folder to search in * @param filter the lock filter * * @return a list of locked resource paths (relative to current site) * * @throws CmsException if something goes wrong */ public List<String> getLockedResources(CmsRequestContext context, CmsResource resource, CmsLockFilter filter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<String> result = null; try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_READ, false, CmsResourceFilter.ALL); result = m_driverManager.getLockedResources(dbc, resource, filter); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_COUNT_LOCKED_RESOURCES_FOLDER_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns all locked resources in a given folder.<p> * * @param context the current request context * @param resource the folder to search in * @param filter the lock filter * * @return a list of locked resource paths (relative to current site) * * @throws CmsException if something goes wrong */ public List<CmsResource> getLockedResourcesObjects( CmsRequestContext context, CmsResource resource, CmsLockFilter filter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsResource> result = null; try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_READ, false, CmsResourceFilter.ALL); result = m_driverManager.getLockedResourcesObjects(dbc, resource, filter); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_COUNT_LOCKED_RESOURCES_FOLDER_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns all locked resources in a given folder, but uses a cache for resource lookups.<p> * * @param context the current request context * @param resource the folder to search in * @param filter the lock filter * @param cache the cache to use * * @return a list of locked resource paths (relative to current site) * * @throws CmsException if something goes wrong */ public List<CmsResource> getLockedResourcesObjectsWithCache( CmsRequestContext context, CmsResource resource, CmsLockFilter filter, Map<String, CmsResource> cache) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsResource> result = null; try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_READ, false, CmsResourceFilter.ALL); result = m_driverManager.getLockedResourcesObjectsWithCache(dbc, resource, filter, cache); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_COUNT_LOCKED_RESOURCES_FOLDER_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns the lock manger.<p> * * @return the lock manager */ public CmsLockManager getLockManager() { return m_lockManager; } /** * Returns all log entries matching the given filter.<p> * * @param context the current user context * @param filter the filter to match the log entries * * @return all log entries matching the given filter * * @throws CmsException if something goes wrong * * @see CmsObject#getLogEntries(CmsLogFilter) */ public List<CmsLogEntry> getLogEntries(CmsRequestContext context, CmsLogFilter filter) throws CmsException { List<CmsLogEntry> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.getLogEntries(dbc, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_LOG_ENTRIES_0), e); } finally { dbc.clear(); } return result; } /** * Returns all resources of organizational units for which the current user has * the given role role.<p> * * @param context the current request context * @param role the role to check * * @return a list of {@link org.opencms.file.CmsResource} objects * * @throws CmsException if something goes wrong */ public List<CmsResource> getManageableResources(CmsRequestContext context, CmsRole role) throws CmsException { List<CmsResource> resources; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { resources = getManageableResources(dbc, role); } finally { dbc.clear(); } return resources; } /** * Returns all child organizational units of the given parent organizational unit including * hierarchical deeper organization units if needed.<p> * * @param context the current request context * @param parent the parent organizational unit * @param includeChildren if hierarchical deeper organization units should also be returned * * @return a list of <code>{@link CmsOrganizationalUnit}</code> objects * * @throws CmsException if operation was not successful * * @see org.opencms.security.CmsOrgUnitManager#getOrganizationalUnits(CmsObject, String, boolean) */ public List<CmsOrganizationalUnit> getOrganizationalUnits( CmsRequestContext context, CmsOrganizationalUnit parent, boolean includeChildren) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsOrganizationalUnit> result = null; try { result = m_driverManager.getOrganizationalUnits(dbc, parent, includeChildren); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_ORGUNITS_1, parent.getName()), e); } finally { dbc.clear(); } return result; } /** * Returns all the organizational units for which the current user has the given role.<p> * * @param requestContext the current request context * @param role the role to check * @param includeSubOus if sub organizational units should be included in the search * * @return a list of {@link org.opencms.security.CmsOrganizationalUnit} objects * * @throws CmsException if something goes wrong */ public List<CmsOrganizationalUnit> getOrgUnitsForRole( CmsRequestContext requestContext, CmsRole role, boolean includeSubOus) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(requestContext); List<CmsOrganizationalUnit> result = null; try { result = m_driverManager.getOrgUnitsForRole(dbc, role, includeSubOus); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_GET_ORGUNITS_ROLE_1, role.getName(requestContext.getLocale())), e); } finally { dbc.clear(); } return result; } /** * Returns the parent group of a group.<p> * * @param context the current request context * @param groupname the name of the group * * @return group the parent group or <code>null</code> * * @throws CmsException if operation was not successful */ public CmsGroup getParent(CmsRequestContext context, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.getParent(dbc, CmsOrganizationalUnit.removeLeadingSeparator(groupname)); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_PARENT_GROUP_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Returns the set of permissions of the current user for a given resource.<p> * * @param context the current request context * @param resource the resource * @param user the user * * @return bit set with allowed permissions * * @throws CmsException if something goes wrong */ public CmsPermissionSetCustom getPermissions(CmsRequestContext context, CmsResource resource, CmsUser user) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsPermissionSetCustom result = null; try { result = m_driverManager.getPermissions(dbc, resource, user); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_GET_PERMISSIONS_2, user.getName(), context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns the uuid id for the given id, * remove this method as soon as possible.<p> * * @param context the current cms context * @param id the old project id * * @return the new uuid for the given id * * @throws CmsException if something goes wrong */ public CmsUUID getProjectId(CmsRequestContext context, int id) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUUID result = null; try { result = m_driverManager.getProjectId(dbc, id); } catch (CmsException e) { dbc.report(null, e.getMessageContainer(), e); } finally { dbc.clear(); } return result; } /** * Returns a new publish list that contains the unpublished resources related * to all resources in the given publish list, the related resources exclude * all resources in the given publish list and also locked (by other users) resources.<p> * * @param context the current cms context * @param publishList the publish list to exclude from result * @param filter the relation filter to use to get the related resources * * @return a new publish list that contains the related resources * * @throws CmsException if something goes wrong * * @see org.opencms.publish.CmsPublishManager#getRelatedResourcesToPublish(CmsObject, CmsPublishList) */ public CmsPublishList getRelatedResourcesToPublish( CmsRequestContext context, CmsPublishList publishList, CmsRelationFilter filter) throws CmsException { if (!publishList.isDirectPublish()) { throw new CmsIllegalArgumentException( Messages.get().container(Messages.ERR_GET_RELATED_RESOURCES_PUBLISH_PROJECT_0)); } CmsPublishList ret = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { ret = m_driverManager.getRelatedResourcesToPublish(dbc, publishList, filter); checkPublishPermissions(dbc, ret); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_GET_RELATED_RESOURCES_PUBLISH_DIRECT_1, CmsFileUtil.formatResourceNames(context, publishList.getDirectPublishResources())), e); } finally { dbc.clear(); } return ret; } /** * Returns all relations for the given resource matching the given filter.<p> * * @param context the current user context * @param resource the resource to retrieve the relations for * @param filter the filter to match the relation * * @return all {@link org.opencms.relations.CmsRelation} objects for the given resource matching the given filter * * @throws CmsException if something goes wrong * * @see CmsObject#getRelationsForResource(String, CmsRelationFilter) */ public List<CmsRelation> getRelationsForResource( CmsRequestContext context, CmsResource resource, CmsRelationFilter filter) throws CmsException { List<CmsRelation> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check the access permissions if (resource != null) { checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_VIEW, false, CmsResourceFilter.ALL); } result = m_driverManager.getRelationsForResource(dbc, resource, filter); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_READ_RELATIONS_1, (resource != null) ? context.removeSiteRoot(resource.getRootPath()) : "null"), e); } finally { dbc.clear(); } return result; } /** * Returns all resources of the given organizational unit.<p> * * @param context the current request context * @param orgUnit the organizational unit to get all resources for * * @return all <code>{@link CmsResource}</code> objects in the organizational unit * * @throws CmsException if operation was not successful * * @see org.opencms.security.CmsOrgUnitManager#getResourcesForOrganizationalUnit(CmsObject, String) * @see org.opencms.security.CmsOrgUnitManager#getGroups(CmsObject, String, boolean) * @see org.opencms.security.CmsOrgUnitManager#getUsers(CmsObject, String, boolean) */ public List<CmsResource> getResourcesForOrganizationalUnit(CmsRequestContext context, CmsOrganizationalUnit orgUnit) throws CmsException { List<CmsResource> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.getResourcesForOrganizationalUnit(dbc, orgUnit); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_ORGUNIT_RESOURCES_1, orgUnit.getName()), e); } finally { dbc.clear(); } return result; } /** * Returns all resources associated to a given principal via an ACE with the given permissions.<p> * * If the <code>includeAttr</code> flag is set it returns also all resources associated to * a given principal through some of following attributes.<p> * * <ul> * <li>User Created</li> * <li>User Last Modified</li> * </ul><p> * * @param context the current request context * @param principalId the id of the principal * @param permissions a set of permissions to match, can be <code>null</code> for all ACEs * @param includeAttr a flag to include resources associated by attributes * * @return a set of <code>{@link CmsResource}</code> objects * * @throws CmsException if something goes wrong */ public Set<CmsResource> getResourcesForPrincipal( CmsRequestContext context, CmsUUID principalId, CmsPermissionSet permissions, boolean includeAttr) throws CmsException { Set<CmsResource> dependencies; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { dependencies = m_driverManager.getResourcesForPrincipal( dbc, dbc.currentProject(), principalId, permissions, includeAttr); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_RESOURCES_FOR_PRINCIPAL_LOG_1, principalId), e); dependencies = new HashSet<CmsResource>(); } finally { dbc.clear(); } return dependencies; } /** * Gets the rewrite aliases matching a given filter.<p> * * @param requestContext the current request context * @param filter the filter used for selecting the rewrite aliases * @return the rewrite aliases matching the given filter * * @throws CmsException if something goes wrong */ public List<CmsRewriteAlias> getRewriteAliases(CmsRequestContext requestContext, CmsRewriteAliasFilter filter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(requestContext); try { return m_driverManager.getRewriteAliases(dbc, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); return null; // will never be executed } finally { dbc.clear(); } } /** * Gets the groups which constitute a given role.<p> * * @param context the request context * @param role the role * @param directUsersOnly if true, only direct users of the role group will be returned * * @return the role's groups * * @throws CmsException if something goes wrong */ public Set<CmsGroup> getRoleGroups(CmsRequestContext context, CmsRole role, boolean directUsersOnly) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { return m_driverManager.getRoleGroups(dbc, role.getGroupName(), directUsersOnly); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_ROLE_GROUPS_1, role.toString()), e); return null; // will never be executed } finally { dbc.clear(); } } /** * Returns all roles the given user has for the given resource.<p> * * @param context the current request context * @param user the user to check * @param resource the resource to check the roles for * * @return a list of {@link CmsRole} objects * * @throws CmsException is something goes wrong */ public List<CmsRole> getRolesForResource(CmsRequestContext context, CmsUser user, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsRole> result = null; try { result = m_driverManager.getRolesForResource(dbc, user, resource); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_GET_ROLES_FOR_RESOURCE_2, user.getName(), context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns an instance of the common sql manager.<p> * * @return an instance of the common sql manager */ public CmsSqlManager getSqlManager() { return m_driverManager.getSqlManager(); } /** * Returns all users of the given organizational unit.<p> * * @param context the current request context * @param orgUnit the organizational unit to get the users for * @param recursive if all users of sub-organizational units should be retrieved too * * @return all <code>{@link CmsUser}</code> objects in the organizational unit * * @throws CmsException if operation was not successful * * @see org.opencms.security.CmsOrgUnitManager#getResourcesForOrganizationalUnit(CmsObject, String) * @see org.opencms.security.CmsOrgUnitManager#getGroups(CmsObject, String, boolean) * @see org.opencms.security.CmsOrgUnitManager#getUsers(CmsObject, String, boolean) */ public List<CmsUser> getUsers(CmsRequestContext context, CmsOrganizationalUnit orgUnit, boolean recursive) throws CmsException { List<CmsUser> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.getUsers(dbc, orgUnit, recursive); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_ORGUNIT_USERS_1, orgUnit.getName()), e); } finally { dbc.clear(); } return result; } /** * Returns a list of users in a group.<p> * * @param context the current request context * @param groupname the name of the group to list users from * @param includeOtherOuUsers include users of other organizational units * @param directUsersOnly if set only the direct assigned users will be returned, * if not also indirect users, ie. members of child groups * @param readRoles if to read roles or groups * * @return all <code>{@link CmsUser}</code> objects in the group * * @throws CmsException if operation was not successful */ public List<CmsUser> getUsersOfGroup( CmsRequestContext context, String groupname, boolean includeOtherOuUsers, boolean directUsersOnly, boolean readRoles) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsUser> result = null; try { result = m_driverManager.getUsersOfGroup( dbc, CmsOrganizationalUnit.removeLeadingSeparator(groupname), includeOtherOuUsers, directUsersOnly, readRoles); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_GET_USERS_OF_GROUP_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Returns the current user's publish list.<p> * * @param context the request context * * @return the current user's publish list * * @throws CmsException if something goes wrong */ public List<CmsResource> getUsersPubList(CmsRequestContext context) throws CmsException { List<CmsResource> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.getUsersPubList(dbc, context.getCurrentUser().getId()); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_USER_PUBLIST_1, context.getCurrentUser().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns all users of the given organizational unit.<p> * * @param context the current request context * @param orgUnit the organizational unit to get the users for * @param recursive if all users of sub-organizational units should be retrieved too * * @return all <code>{@link CmsUser}</code> objects in the organizational unit * * @throws CmsException if operation was not successful * * @see org.opencms.security.CmsOrgUnitManager#getResourcesForOrganizationalUnit(CmsObject, String) * @see org.opencms.security.CmsOrgUnitManager#getGroups(CmsObject, String, boolean) * @see org.opencms.security.CmsOrgUnitManager#getUsers(CmsObject, String, boolean) */ public List<CmsUser> getUsersWithoutAdditionalInfo( CmsRequestContext context, CmsOrganizationalUnit orgUnit, boolean recursive) throws CmsException { List<CmsUser> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.getUsersWithoutAdditionalInfo(dbc, orgUnit, recursive); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_ORGUNIT_USERS_1, orgUnit.getName()), e); } finally { dbc.clear(); } return result; } /** * Performs a non-blocking permission check on a resource.<p> * * This test will not throw an exception in case the required permissions are not * available for the requested operation. Instead, it will return one of the * following values:<ul> * <li><code>{@link I_CmsPermissionHandler#PERM_ALLOWED}</code></li> * <li><code>{@link I_CmsPermissionHandler#PERM_FILTERED}</code></li> * <li><code>{@link I_CmsPermissionHandler#PERM_DENIED}</code></li></ul><p> * * @param context the current request context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required for the operation * @param checkLock if true, a lock for the current user is required for * all write operations, if false it's ok to write as long as the resource * is not locked by another user * @param filter the resource filter to use * * @return <code>{@link I_CmsPermissionHandler#PERM_ALLOWED}</code> if the user has sufficient permissions on the resource * for the requested operation * * @throws CmsException in case of i/o errors (NOT because of insufficient permissions) * * @see #hasPermissions(CmsDbContext, CmsResource, CmsPermissionSet, boolean, CmsResourceFilter) */ public I_CmsPermissionHandler.CmsPermissionCheckResult hasPermissions( CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions, boolean checkLock, CmsResourceFilter filter) throws CmsException { I_CmsPermissionHandler.CmsPermissionCheckResult result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = hasPermissions( dbc, resource, requiredPermissions, checkLock ? LockCheck.yes : LockCheck.no, filter); } finally { dbc.clear(); } return result; } /** * Performs a non-blocking permission check on a resource.<p> * * This test will not throw an exception in case the required permissions are not * available for the requested operation. Instead, it will return one of the * following values:<ul> * <li><code>{@link I_CmsPermissionHandler#PERM_ALLOWED}</code></li> * <li><code>{@link I_CmsPermissionHandler#PERM_FILTERED}</code></li> * <li><code>{@link I_CmsPermissionHandler#PERM_DENIED}</code></li></ul><p> * * @param context the current request context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required for the operation * @param checkLock if true, a lock for the current user is required for * all write operations, if false it's ok to write as long as the resource * is not locked by another user * @param filter the resource filter to use * * @return <code>{@link I_CmsPermissionHandler#PERM_ALLOWED}</code> if the user has sufficient permissions on the resource * for the requested operation * * @throws CmsException in case of i/o errors (NOT because of insufficient permissions) * * @see #hasPermissions(CmsDbContext, CmsResource, CmsPermissionSet, boolean, CmsResourceFilter) */ public I_CmsPermissionHandler.CmsPermissionCheckResult hasPermissions( CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions, LockCheck checkLock, CmsResourceFilter filter) throws CmsException { I_CmsPermissionHandler.CmsPermissionCheckResult result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = hasPermissions(dbc, resource, requiredPermissions, checkLock, filter); } finally { dbc.clear(); } return result; } /** * Checks if the given user has the given role in the given organizational unit.<p> * * If the organizational unit is <code>null</code>, this method will check if the * given user has the given role for at least one organizational unit.<p> * * @param dbc the current OpenCms users database context * @param user the user to check the role for * @param role the role to check * * @return <code>true</code> if the given user has the given role in the given organizational unit */ public boolean hasRole(CmsDbContext dbc, CmsUser user, CmsRole role) { // try to read from cache String key = role.getGroupName() + "," + role.getOuFqn(); Boolean result = OpenCms.getMemoryMonitor().getGroupListCache().getHasRole(user.getId(), key); if (result != null) { return result.booleanValue(); } // read all roles of the current user List<CmsGroup> roles; try { roles = m_driverManager.getGroupsOfUser( dbc, user.getName(), "", true, true, false, dbc.getRequestContext().getRemoteAddress()); } catch (CmsException e) { if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } // any exception: return false return false; } boolean hasRole = hasRole(role, roles); // hack: require individual user based confirmation for certain roles // this is for updated older systems where content managers have been WORKPLACE_USER only // to prevent access to certain ADE management functions if (hasRole && ((CmsRole.CATEGORY_EDITOR.equals(role)) || (CmsRole.GALLERY_EDITOR.equals(role)))) { String info = CmsRole.CONFIRM_ROLE_PREFIX + role.getRoleName(); Object prop = OpenCms.getRuntimeProperty(info); if ((prop != null) && Boolean.valueOf(prop.toString()).booleanValue()) { // individual user based confirmation for the role is required // if the user is a WORKPLACE_USER Object val = user.getAdditionalInfo(info); if ((val == null) || !Boolean.valueOf(val.toString()).booleanValue()) { // no individual user confirmation present if (hasRole(CmsRole.WORKPLACE_USER, roles) && !hasRole(CmsRole.DEVELOPER, roles) && !hasRole(CmsRole.PROJECT_MANAGER, roles) && !hasRole(CmsRole.ACCOUNT_MANAGER, roles)) { // user is a WORKPLACE_USER, confirmation is required but not present hasRole = false; } } } } result = Boolean.valueOf(hasRole); OpenCms.getMemoryMonitor().getGroupListCache().setHasRole(user, key, result); return result.booleanValue(); } /** * Checks if the given user has the given role in the given organizational unit.<p> * * If the organizational unit is <code>null</code>, this method will check if the * given user has the given role for at least one organizational unit.<p> * * @param context the current request context * @param user the user to check the role for * @param role the role to check * * @return <code>true</code> if the given user has the given role in the given organizational unit */ public boolean hasRole(CmsRequestContext context, CmsUser user, CmsRole role) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); boolean result; try { result = hasRole(dbc, user, role); } finally { dbc.clear(); } return result; } /** * Checks if the given user has the given role for the given resource.<p> * * @param dbc the current OpenCms users database context * @param user the user to check the role for * @param role the role to check * @param resource the resource to check the role for * * @return <code>true</code> if the given user has the given role for the given resource */ public boolean hasRoleForResource(CmsDbContext dbc, CmsUser user, CmsRole role, CmsResource resource) { // guest user has no role if (user.isGuestUser()) { return false; } // try to read from cache // *** // NOTE: We do intentionally *not* use the new group list cache here, as we have no good way to limit it at the moment, and this might generate a large amount of entries // *** String key = user.getId().toString() + role.getGroupName() + resource.getRootPath(); Boolean result = OpenCms.getMemoryMonitor().getCachedRole(key); if (result != null) { return result.booleanValue(); } // read all roles of the current user List<CmsGroup> roles; try { roles = new ArrayList<CmsGroup>( m_driverManager.getGroupsOfUser( dbc, user.getName(), "", true, true, true, dbc.getRequestContext().getRemoteAddress())); } catch (CmsException e) { if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } // any exception: return false return false; } // first check the user has the role at all if (!hasRole(role.forOrgUnit(null), roles)) { result = Boolean.FALSE; } // then check if one applies to the given resource Iterator<CmsGroup> it = roles.iterator(); while ((result == null) && it.hasNext()) { CmsGroup group = it.next(); CmsRole givenRole = CmsRole.valueOf(group); if (hasRole(role.forOrgUnit(null), Collections.singletonList(group))) { // we have the same role, now check the resource if needed if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(givenRole.getOuFqn())) { try { CmsOrganizationalUnit orgUnit = m_driverManager.readOrganizationalUnit( dbc, givenRole.getOuFqn()); Iterator<CmsResource> itResources = m_driverManager.getResourcesForOrganizationalUnit( dbc, orgUnit).iterator(); while (itResources.hasNext()) { CmsResource givenResource = itResources.next(); if (resource.getRootPath().startsWith(givenResource.getRootPath())) { result = Boolean.TRUE; break; } } } catch (CmsException e) { if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } // ignore } } else { result = Boolean.TRUE; } } } if (result == null) { result = Boolean.FALSE; } OpenCms.getMemoryMonitor().cacheRole(key, result.booleanValue()); return result.booleanValue(); } /** * Checks if the given user has the given role for the given resource.<p> * * @param context the current request context * @param user the user to check * @param role the role to check * @param resource the resource to check the role for * * @return <code>true</code> if the given user has the given role for the given resource */ public boolean hasRoleForResource(CmsRequestContext context, CmsUser user, CmsRole role, CmsResource resource) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); boolean result; try { result = hasRoleForResource(dbc, user, role, resource); } finally { dbc.clear(); } return result; } /** * Writes a list of access control entries as new access control entries of a given resource.<p> * * Already existing access control entries of this resource are removed before.<p> * * Access is granted, if:<p> * <ul> * <li>the current user has control permission on the resource</li> * </ul><p> * * @param context the current request context * @param resource the resource * @param acEntries a list of <code>{@link CmsAccessControlEntry}</code> objects * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the required permissions are not satisfied */ public void importAccessControlEntries( CmsRequestContext context, CmsResource resource, List<CmsAccessControlEntry> acEntries) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_CONTROL, true, CmsResourceFilter.ALL); m_driverManager.importAccessControlEntries(dbc, resource, acEntries); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_IMPORT_ACL_ENTRIES_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Creates a new resource with the provided content and properties.<p> * * The <code>content</code> parameter may be null if the resource id already exists. * If so, the created resource will be made a sibling of the existing resource, * the existing content will remain unchanged. * This is used during file import for import of siblings as the * <code>manifest.xml</code> only contains one binary copy per file. * If the resource id exists but the <code>content</code> is not null, * the created resource will be made a sibling of the existing resource, * and both will share the new content.<p> * * @param context the current request context * @param resourcePath the name of the resource to create (full path) * @param resource the new resource to create * @param content the content for the new resource * @param properties the properties for the new resource * @param importCase if <code>true</code>, signals that this operation is done while importing resource, * causing different lock behavior and potential "lost and found" usage * * @return the created resource * * @throws CmsException if something goes wrong */ public CmsResource importResource( CmsRequestContext context, String resourcePath, CmsResource resource, byte[] content, List<CmsProperty> properties, boolean importCase) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsResource newResource = null; try { checkOfflineProject(dbc); newResource = m_driverManager.createResource(dbc, resourcePath, resource, content, properties, importCase); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_IMPORT_RESOURCE_2, context.getSitePath(resource), resourcePath), e); } finally { dbc.clear(); } return newResource; } /** * Imports a rewrite alias.<p> * * @param requestContext the current request context * @param siteRoot the site root * @param source the rewrite alias source * @param target the rewrite alias target * @param mode the alias mode * @return the import result * * @throws CmsException if something goes wrong */ public CmsAliasImportResult importRewriteAlias( CmsRequestContext requestContext, String siteRoot, String source, String target, CmsAliasMode mode) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(requestContext); try { return m_driverManager.importRewriteAlias(dbc, siteRoot, source, target, mode); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); return null; } finally { dbc.clear(); } } /** * Creates a new user by import.<p> * * @param context the current request context * @param id the id of the user * @param name the new name for the user * @param password the new password for the user * @param firstname the first name of the user * @param lastname the last name of the user * @param email the email of the user * @param flags the flags for a user (for example <code>{@link I_CmsPrincipal#FLAG_ENABLED}</code>) * @param dateCreated the creation date * @param additionalInfos the additional user infos * * @return the imported user * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the role {@link CmsRole#ACCOUNT_MANAGER} is not owned by the current user. */ public CmsUser importUser( CmsRequestContext context, String id, String name, String password, String firstname, String lastname, String email, int flags, long dateCreated, Map<String, Object> additionalInfos) throws CmsException, CmsRoleViolationException { CmsUser newUser = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(name))); newUser = m_driverManager.importUser( dbc, id, CmsOrganizationalUnit.removeLeadingSeparator(name), password, firstname, lastname, email, flags, dateCreated, additionalInfos); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_IMPORT_USER_7, new Object[] { name, firstname, lastname, email, new Integer(flags), new Date(dateCreated), additionalInfos}), e); } finally { dbc.clear(); } return newUser; } /** * Increments a counter and returns its old value.<p> * * @param context the request context * @param name the name of the counter * * @return the value of the counter before incrementing * * @throws CmsException if something goes wrong */ public int incrementCounter(CmsRequestContext context, String name) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { return m_driverManager.incrementCounter(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_INCREMENT_COUNTER_1, name), e); return -1; // will never be reached } finally { dbc.clear(); } } /** * Initializes this security manager with a given runtime info factory.<p> * * @param configurationManager the configurationManager * @param dbContextFactory the initialized OpenCms runtime info factory * @param publishEngine the publish engine * * @throws CmsInitException if the initialization fails */ public void init( CmsConfigurationManager configurationManager, I_CmsDbContextFactory dbContextFactory, CmsPublishEngine publishEngine) throws CmsInitException { if (dbContextFactory == null) { throw new CmsInitException( org.opencms.main.Messages.get().container(org.opencms.main.Messages.ERR_CRITICAL_NO_DB_CONTEXT_0)); } m_dbContextFactory = dbContextFactory; CmsSystemConfiguration systemConfiguration = (CmsSystemConfiguration)configurationManager.getConfiguration( CmsSystemConfiguration.class); // create the driver manager m_driverManager = CmsDriverManager.newInstance(configurationManager, this, dbContextFactory, publishEngine); try { // invoke the init method of the driver manager m_driverManager.init(configurationManager, dbContextFactory); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_DRIVER_MANAGER_START_PHASE4_OK_0)); } } catch (Exception exc) { CmsMessageContainer message = Messages.get().container(Messages.LOG_ERR_DRIVER_MANAGER_START_0); if (LOG.isFatalEnabled()) { LOG.fatal(message.key(), exc); } throw new CmsInitException(message, exc); } // create a new lock manager m_lockManager = m_driverManager.getLockManager(); // initialize the permission handler String permHandlerClassName = systemConfiguration.getPermissionHandler(); if (permHandlerClassName == null) { // use default implementation m_permissionHandler = new CmsDefaultPermissionHandler(); } else { // use configured permission handler try { m_permissionHandler = (I_CmsPermissionHandler)Class.forName(permHandlerClassName).newInstance(); } catch (Exception e) { throw new CmsInitException( org.opencms.main.Messages.get().container( org.opencms.main.Messages.ERR_CRITICAL_CLASS_CREATION_1, permHandlerClassName), e); } } m_permissionHandler.init(m_driverManager, systemConfiguration); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SECURITY_MANAGER_INIT_0)); } } /** * Initializes the default groups for an organizational unit.<p> * * @param context the request context * @param ou the organizational unit */ public void initializeOrgUnit(CmsRequestContext context, CmsOrganizationalUnit ou) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); m_driverManager.initOrgUnit(dbc, ou); } /** * Checks if the specified resource is inside the current project.<p> * * The project "view" is determined by a set of path prefixes. * If the resource starts with any one of this prefixes, it is considered to * be "inside" the project.<p> * * @param context the current request context * @param resourcename the specified resource name (full path) * * @return <code>true</code>, if the specified resource is inside the current project */ public boolean isInsideCurrentProject(CmsRequestContext context, String resourcename) { boolean result = false; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.isInsideCurrentProject(dbc, resourcename); } finally { dbc.clear(); } return result; } /** * Checks if the current user has management access to the current project.<p> * * @param context the current request context * * @return <code>true</code>, if the user has management access to the current project */ public boolean isManagerOfProject(CmsRequestContext context) { try { return getAllManageableProjects( context, readOrganizationalUnit(context, context.getCurrentProject().getOuFqn()), false).contains(context.getCurrentProject()); } catch (CmsException e) { // should never happen if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } return false; } } /** * Checks whether the subscription driver is available.<p> * * @return true if the subscription driver is available */ public boolean isSubscriptionDriverAvailable() { return m_driverManager.isSubscriptionDriverAvailable(); } /** * Locks a resource.<p> * * The <code>type</code> parameter controls what kind of lock is used.<br> * Possible values for this parameter are: <br> * <ul> * <li><code>{@link org.opencms.lock.CmsLockType#EXCLUSIVE}</code></li> * <li><code>{@link org.opencms.lock.CmsLockType#TEMPORARY}</code></li> * <li><code>{@link org.opencms.lock.CmsLockType#PUBLISH}</code></li> * </ul><p> * * @param context the current request context * @param resource the resource to lock * @param type type of the lock * * @throws CmsException if something goes wrong * * @see CmsObject#lockResource(String) * @see CmsObject#lockResourceTemporary(String) * @see org.opencms.file.types.I_CmsResourceType#lockResource(CmsObject, CmsSecurityManager, CmsResource, CmsLockType) */ public void lockResource(CmsRequestContext context, CmsResource resource, CmsLockType type) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); m_driverManager.lockResource(dbc, resource, type); } catch (Exception e) { CmsMessageContainer messageContainer; if (e instanceof CmsLockException) { messageContainer = ((CmsLockException)e).getMessageContainer(); } else { messageContainer = Messages.get().container( Messages.ERR_LOCK_RESOURCE_2, context.getSitePath(resource), type.toString()); } dbc.report(null, messageContainer, e); } finally { dbc.clear(); } } /** * Attempts to authenticate a user into OpenCms with the given password.<p> * * @param context the current request context * @param username the name of the user to be logged in * @param password the password of the user * @param remoteAddress the ip address of the request * * @return the logged in user * * @throws CmsException if the login was not successful */ public CmsUser loginUser(CmsRequestContext context, String username, String password, String remoteAddress) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.loginUser( dbc, CmsOrganizationalUnit.removeLeadingSeparator(username), password, remoteAddress); } finally { dbc.clear(); } return result; } /** * Lookup and read the user or group with the given UUID.<p> * * @param context the current request context * @param principalId the UUID of the principal to lookup * * @return the principal (group or user) if found, otherwise <code>null</code> */ public I_CmsPrincipal lookupPrincipal(CmsRequestContext context, CmsUUID principalId) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); I_CmsPrincipal result = null; try { result = m_driverManager.lookupPrincipal(dbc, principalId); } finally { dbc.clear(); } return result; } /** * Lookup and read the user or group with the given name.<p> * * @param context the current request context * @param principalName the name of the principal to lookup * * @return the principal (group or user) if found, otherwise <code>null</code> */ public I_CmsPrincipal lookupPrincipal(CmsRequestContext context, String principalName) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); I_CmsPrincipal result = null; try { result = m_driverManager.lookupPrincipal(dbc, CmsOrganizationalUnit.removeLeadingSeparator(principalName)); } finally { dbc.clear(); } return result; } /** * Mark the given resource as visited by the user.<p> * * @param context the request context * @param poolName the name of the database pool to use * @param resource the resource to mark as visited * @param user the user that visited the resource * * @throws CmsException if something goes wrong */ public void markResourceAsVisitedBy(CmsRequestContext context, String poolName, CmsResource resource, CmsUser user) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.markResourceAsVisitedBy(dbc, poolName, resource, user); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_MARK_RESOURCE_AS_VISITED_2, context.getSitePath(resource), user.getName()), e); } finally { dbc.clear(); } } /** * Returns a new publish list that contains all resources of both given publish lists.<p> * * @param context the current request context * @param pubList1 the first publish list * @param pubList2 the second publish list * * @return a new publish list that contains all resources of both given publish lists * * @throws CmsException if something goes wrong * * @see org.opencms.publish.CmsPublishManager#mergePublishLists(CmsObject, CmsPublishList, CmsPublishList) */ public CmsPublishList mergePublishLists(CmsRequestContext context, CmsPublishList pubList1, CmsPublishList pubList2) throws CmsException { CmsPublishList ret = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // get all resources from the first list Set<CmsResource> publishResources = new HashSet<CmsResource>(pubList1.getAllResources()); // get all resources from the second list publishResources.addAll(pubList2.getAllResources()); // create merged publish list ret = new CmsPublishList( pubList1.getDirectPublishResources(), pubList1.isPublishSiblings(), pubList1.isPublishSubResources()); ret.addAll(publishResources, false); // ignore files that should not be published if (pubList1.isUserPublishList()) { ret.setUserPublishList(true); } ret.initialize(); // ensure sort order checkPublishPermissions(dbc, ret); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_MERGING_PUBLISH_LISTS_0), e); } finally { dbc.clear(); } return ret; } /** * Moves a resource.<p> * * You must ensure that the destination path is an absolute, valid and * existing VFS path. Relative paths from the source are currently not supported.<p> * * The moved resource will always be locked to the current user * after the move operation.<p> * * In case the target resource already exists, it is overwritten with the * source resource.<p> * * @param context the current request context * @param source the resource to copy * @param destination the name of the copy destination with complete path * * @throws CmsException if something goes wrong * @throws CmsSecurityException if resource could not be copied * * @see CmsObject#moveResource(String, String) * @see org.opencms.file.types.I_CmsResourceType#moveResource(CmsObject, CmsSecurityManager, CmsResource, String) */ public void moveResource(CmsRequestContext context, CmsResource source, String destination) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); // checking if the destination folder exists and is not marked as deleted readResource(context, CmsResource.getParentFolder(destination), CmsResourceFilter.IGNORE_EXPIRATION); checkPermissions(dbc, source, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); checkPermissions(dbc, source, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); checkSystemLocks(dbc, source); // check write permissions for subresources in case of moving a folder if (source.isFolder()) { dbc.getRequestContext().setAttribute(I_CmsVfsDriver.REQ_ATTR_CHECK_PERMISSIONS, Boolean.TRUE); try { m_driverManager.getVfsDriver( dbc).moveResource(dbc, dbc.currentProject().getUuid(), source, destination); } catch (CmsDataAccessException e) { // unwrap the permission violation exception if (e.getCause() instanceof CmsPermissionViolationException) { throw (CmsPermissionViolationException)e.getCause(); } else { throw e; } } dbc.getRequestContext().removeAttribute(I_CmsVfsDriver.REQ_ATTR_CHECK_PERMISSIONS); } Set<CmsResource> allMovedResources = new HashSet<>(); moveResource(dbc, source, destination, allMovedResources); if (!dbc.currentProject().isOnlineProject()) { for (CmsResource movedResource : allMovedResources) { m_driverManager.repairCategories( dbc, dbc.getRequestContext().getCurrentProject().getUuid(), movedResource); } } } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_MOVE_RESOURCE_2, dbc.removeSiteRoot(source.getRootPath()), dbc.removeSiteRoot(destination)), e); } finally { dbc.clear(); } } /** * Moves a resource to the "lost and found" folder.<p> * * The method can also be used to check get the name of a resource * in the "lost and found" folder only without actually moving the * the resource. To do this, the <code>returnNameOnly</code> flag * must be set to <code>true</code>.<p> * * In general, it is the same name as the given resource has, the only exception is * if a resource in the "lost and found" folder with the same name already exists. * In such case, a counter is added to the resource name.<p> * * @param context the current request context * @param resource the resource to apply this operation to * @param returnNameOnly if <code>true</code>, only the name of the resource in the "lost and found" * folder is returned, the move operation is not really performed * * @return the name of the resource inside the "lost and found" folder * * @throws CmsException if something goes wrong * * @see CmsObject#moveToLostAndFound(String) * @see CmsObject#getLostAndFoundName(String) */ public String moveToLostAndFound(CmsRequestContext context, CmsResource resource, boolean returnNameOnly) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); String result = null; try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); if (!returnNameOnly) { checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); } result = m_driverManager.moveToLostAndFound(dbc, resource, returnNameOnly); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_MOVE_TO_LOST_AND_FOUND_1, dbc.removeSiteRoot(resource.getRootPath())), e); } finally { dbc.clear(); } return result; } /** * Publishes the resources of a specified publish list.<p> * * @param cms the current request context * @param publishList a publish list * @param report an instance of <code>{@link I_CmsReport}</code> to print messages * * @return the publish history id of the published project * * @throws CmsException if something goes wrong * * @see #fillPublishList(CmsRequestContext, CmsPublishList) */ public CmsUUID publishProject(CmsObject cms, CmsPublishList publishList, I_CmsReport report) throws CmsException { CmsRequestContext context = cms.getRequestContext(); CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check if the current user has the required publish permissions checkPublishPermissions(dbc, publishList); m_driverManager.publishProject(cms, dbc, publishList, report); } finally { dbc.clear(); } return publishList.getPublishHistoryId(); } /** * Reads the alias with a given path in a given site.<p> * * @param context the current request context * @param siteRoot the site root * @param path the site relative alias path * @return the alias for the path, or null if no such alias exists * * @throws CmsException if something goes wrong */ public CmsAlias readAliasByPath(CmsRequestContext context, String siteRoot, String path) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsAlias alias = m_driverManager.readAliasByPath(dbc, context.getCurrentProject(), siteRoot, path); return alias; } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); return null; // will never be executed } finally { dbc.clear(); } } /** * Reads the aliases for a resource with a given structure id.<p> * * @param context the current request context * @param structureId the structure id for which the aliases should be read * * @return the aliases for the structure id * * @throws CmsException if something goes wrong */ public List<CmsAlias> readAliasesById(CmsRequestContext context, CmsUUID structureId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { List<CmsAlias> aliases = m_driverManager.readAliasesByStructureId( dbc, context.getCurrentProject(), structureId); return aliases; } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); return null; // will never be executed } finally { dbc.clear(); } } /** * Reads all historical versions of a resource.<p> * * The reading excludes the file content, if the resource is a file.<p> * * @param context the current request context * @param resource the resource to be read * * @return a list of historical versions, as <code>{@link I_CmsHistoryResource}</code> objects * * @throws CmsException if something goes wrong */ public List<I_CmsHistoryResource> readAllAvailableVersions(CmsRequestContext context, CmsResource resource) throws CmsException { List<I_CmsHistoryResource> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readAllAvailableVersions(dbc, resource); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_ALL_HISTORY_FILE_HEADERS_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Reads all property definitions for the given mapping type.<p> * * @param context the current request context * * @return a list with the <code>{@link CmsPropertyDefinition}</code> objects (may be empty) * * @throws CmsException if something goes wrong */ public List<CmsPropertyDefinition> readAllPropertyDefinitions(CmsRequestContext context) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsPropertyDefinition> result = null; try { result = m_driverManager.readAllPropertyDefinitions(dbc); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_ALL_PROPDEF_0), e); } finally { dbc.clear(); } return result; } /** * Returns all resources subscribed by the given user or group.<p> * * @param context the request context * @param poolName the name of the database pool to use * @param principal the principal to read the subscribed resources * * @return all resources subscribed by the given user or group * * @throws CmsException if something goes wrong */ public List<CmsResource> readAllSubscribedResources( CmsRequestContext context, String poolName, CmsPrincipal principal) throws CmsException { List<CmsResource> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readAllSubscribedResources(dbc, poolName, principal); } catch (Exception e) { if (principal instanceof CmsUser) { dbc.report( null, Messages.get().container(Messages.ERR_READ_SUBSCRIBED_RESOURCES_ALL_USER_1, principal.getName()), e); } else { dbc.report( null, Messages.get().container(Messages.ERR_READ_SUBSCRIBED_RESOURCES_ALL_GROUP_1, principal.getName()), e); } } finally { dbc.clear(); } return result; } /** * Reads all URL name mapping entries for a given structure id.<p> * * @param context the request context * @param id the structure id * * @return the list of URL names for the given structure id * @throws CmsException if something goes wrong */ public List<String> readAllUrlNameMappingEntries(CmsRequestContext context, CmsUUID id) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { List<CmsUrlNameMappingEntry> entries = m_driverManager.readUrlNameMappingEntries( dbc, context.getCurrentProject().isOnlineProject(), CmsUrlNameMappingFilter.ALL.filterStructureId(id)); List<String> result = new ArrayList<String>(); for (CmsUrlNameMappingEntry entry : entries) { result.add(entry.getName()); } return result; } catch (Exception e) { CmsMessageContainer message = Messages.get().container( Messages.ERR_READ_NEWEST_URLNAME_FOR_ID_1, id.toString()); dbc.report(null, message, e); return null; } finally { dbc.clear(); } } /** * Returns the first ancestor folder matching the filter criteria.<p> * * If no folder matching the filter criteria is found, null is returned.<p> * * @param context the context of the current request * @param resource the resource to start * @param filter the resource filter to match while reading the ancestors * * @return the first ancestor folder matching the filter criteria or <code>null</code> if no folder was found * * @throws CmsException if something goes wrong */ public CmsFolder readAncestor(CmsRequestContext context, CmsResource resource, CmsResourceFilter filter) throws CmsException { // get the full folder path of the resource to start from String path = CmsResource.getFolderPath(resource.getRootPath()); do { // check if the current folder matches the given filter if (existsResource(context, path, filter)) { // folder matches, return it return readFolder(context, path, filter); } else { // folder does not match filter criteria, go up one folder path = CmsResource.getParentFolder(path); } if (CmsStringUtil.isEmpty(path) || !path.startsWith(context.getSiteRoot())) { // site root or root folder reached and no matching folder found return null; } } while (true); } /** * Reads the newest URL name which is mapped to the given structure id.<p> * * If the structure id is not mapped to any name, null will be returned.<p> * * @param context the request context * @param id the structure id for which the newest mapped name should be returned * @param locale the locale for the mapping * @param defaultLocales the default locales to use if there is no URL name mapping for the requested locale * * @return an URL name or null * * @throws CmsException if something goes wrong */ public String readBestUrlName(CmsRequestContext context, CmsUUID id, Locale locale, List<Locale> defaultLocales) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { return m_driverManager.readBestUrlName(dbc, id, locale, defaultLocales); } catch (Exception e) { CmsMessageContainer message = Messages.get().container( Messages.ERR_READ_NEWEST_URLNAME_FOR_ID_1, id.toString()); dbc.report(null, message, e); return null; // will never be reached } finally { dbc.clear(); } } /** * Returns the child resources of a resource, that is the resources * contained in a folder.<p> * * With the parameters <code>getFolders</code> and <code>getFiles</code> * you can control what type of resources you want in the result list: * files, folders, or both.<p> * * This method is mainly used by the workplace explorer.<p> * * @param context the current request context * @param resource the resource to return the child resources for * @param filter the resource filter to use * @param getFolders if true the child folders are included in the result * @param getFiles if true the child files are included in the result * * @return a list of all child resources * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (read is required) * */ public List<CmsResource> readChildResources( CmsRequestContext context, CmsResource resource, CmsResourceFilter filter, boolean getFolders, boolean getFiles) throws CmsException, CmsSecurityException { List<CmsResource> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check the access permissions checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); result = m_driverManager.readChildResources(dbc, resource, filter, getFolders, getFiles, true); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_CHILD_RESOURCES_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns the default file for the given folder.<p> * * If the given resource is a file, then this file is returned.<p> * * Otherwise, in case of a folder:<br> * <ol> * <li>the {@link CmsPropertyDefinition#PROPERTY_DEFAULT_FILE} is checked, and * <li>if still no file could be found, the configured default files in the * <code>opencms-vfs.xml</code> configuration are iterated until a match is * found, and * <li>if still no file could be found, <code>null</code> is returned * </ol><p> * * @param context the request context * @param resource the folder to get the default file for * @param resourceFilter the resource filter * * @return the default file for the given folder * * @throws CmsSecurityException if the user has no permissions to read the resulting file * * @see CmsObject#readDefaultFile(String) */ public CmsResource readDefaultFile( CmsRequestContext context, CmsResource resource, CmsResourceFilter resourceFilter) throws CmsSecurityException { CmsResource result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsResource tempResult = m_driverManager.readDefaultFile(dbc, resource, resourceFilter); if (tempResult != null) { // check if the user has read access to the resource checkPermissions(dbc, tempResult, CmsPermissionSet.ACCESS_READ, true, resourceFilter); result = tempResult; } } catch (CmsSecurityException se) { // permissions deny access to the resource throw se; } catch (CmsException e) { // ignore all other exceptions LOG.debug(e.getLocalizedMessage(), e); } finally { dbc.clear(); } return result; } /** * Reads all deleted (historical) resources below the given path, * including the full tree below the path, if required.<p> * * @param context the current request context * @param resource the parent resource to read the resources from * @param readTree <code>true</code> to read all subresources * * @return a list of <code>{@link I_CmsHistoryResource}</code> objects * * @throws CmsException if something goes wrong * * @see CmsObject#readResource(CmsUUID, int) * @see CmsObject#readResources(String, CmsResourceFilter, boolean) * @see CmsObject#readDeletedResources(String, boolean) */ public List<I_CmsHistoryResource> readDeletedResources( CmsRequestContext context, CmsResource resource, boolean readTree) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<I_CmsHistoryResource> result = null; try { boolean isVfsManager = hasRoleForResource(dbc, dbc.currentUser(), CmsRole.VFS_MANAGER, resource); result = m_driverManager.readDeletedResources(dbc, resource, readTree, isVfsManager); } catch (CmsException e) { dbc.report( null, Messages.get().container( Messages.ERR_READING_DELETED_RESOURCES_1, dbc.removeSiteRoot(resource.getRootPath())), e); } finally { dbc.clear(); } return result; } /** * Reads a file resource (including it's binary content) from the VFS.<p> * * In case you do not need the file content, * use <code>{@link #readResource(CmsRequestContext, String, CmsResourceFilter)}</code> instead.<p> * * @param context the current request context * @param resource the resource to be read * * @return the file read from the VFS * * @throws CmsException if something goes wrong */ public CmsFile readFile(CmsRequestContext context, CmsResource resource) throws CmsException { CmsFile result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readFile(dbc, resource); } catch (Exception e) { if (resource instanceof I_CmsHistoryResource) { dbc.report( null, Messages.get().container( Messages.ERR_READ_FILE_HISTORY_2, context.getSitePath(resource), new Integer(resource.getVersion())), e); } else { dbc.report(null, Messages.get().container(Messages.ERR_READ_FILE_1, context.getSitePath(resource)), e); } } finally { dbc.clear(); } return result; } /** * Reads a folder resource from the VFS, * using the specified resource filter.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * @param context the current request context * @param resourcename the name of the folder to read (full path) * @param filter the resource filter to use while reading * * @return the folder that was read * * @throws CmsException if something goes wrong */ public CmsFolder readFolder(CmsRequestContext context, String resourcename, CmsResourceFilter filter) throws CmsException { CmsFolder result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = readFolder(dbc, resourcename, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_FOLDER_2, resourcename, filter), e); } finally { dbc.clear(); } return result; } /** * Reads the group of a project.<p> * * @param context the current request context * @param project the project to read from * * @return the group of a resource */ public CmsGroup readGroup(CmsRequestContext context, CmsProject project) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readGroup(dbc, project); } finally { dbc.clear(); } return result; } /** * Reads a group based on its id.<p> * * @param context the current request context * @param groupId the id of the group that is to be read * * @return the requested group * * @throws CmsException if operation was not successful */ public CmsGroup readGroup(CmsRequestContext context, CmsUUID groupId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readGroup(dbc, groupId); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_GROUP_FOR_ID_1, groupId.toString()), e); } finally { dbc.clear(); } return result; } /** * Reads a group based on its name.<p> * * @param context the current request context * @param groupname the name of the group that is to be read * * @return the requested group * * @throws CmsException if operation was not successful */ public CmsGroup readGroup(CmsRequestContext context, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readGroup(dbc, CmsOrganizationalUnit.removeLeadingSeparator(groupname)); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_GROUP_FOR_NAME_1, groupname), e); } finally { dbc.clear(); } return result; } /** * Reads a principal (an user or group) from the historical archive based on its ID.<p> * * @param context the current request context * @param principalId the id of the principal to read * * @return the historical principal entry with the given id * * @throws CmsException if something goes wrong, ie. {@link CmsDbEntryNotFoundException} * * @see CmsObject#readUser(CmsUUID) * @see CmsObject#readGroup(CmsUUID) * @see CmsObject#readHistoryPrincipal(CmsUUID) */ public CmsHistoryPrincipal readHistoricalPrincipal(CmsRequestContext context, CmsUUID principalId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsHistoryPrincipal result = null; try { result = m_driverManager.readHistoricalPrincipal(dbc, principalId); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_HISTORY_PRINCIPAL_1, principalId), e); } finally { dbc.clear(); } return result; } /** * Returns the latest historical project entry with the given id.<p> * * @param context the current request context * @param projectId the project id * * @return the requested historical project entry * * @throws CmsException if something goes wrong */ public CmsHistoryProject readHistoryProject(CmsRequestContext context, CmsUUID projectId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsHistoryProject result = null; try { result = m_driverManager.readHistoryProject(dbc, projectId); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_READ_HISTORY_PROJECT_2, projectId, dbc.currentProject().getName()), e); } finally { dbc.clear(); } return result; } /** * Returns a historical project entry.<p> * * @param context the current request context * @param publishTag the publish tag of the project * * @return the requested historical project entry * * @throws CmsException if something goes wrong */ public CmsHistoryProject readHistoryProject(CmsRequestContext context, int publishTag) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsHistoryProject result = null; try { result = m_driverManager.readHistoryProject(dbc, publishTag); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_READ_HISTORY_PROJECT_2, new Integer(publishTag), dbc.currentProject().getName()), e); } finally { dbc.clear(); } return result; } /** * Reads the list of all <code>{@link CmsProperty}</code> objects that belong to the given historical resource.<p> * * @param context the current request context * @param resource the historical resource entry to read the properties for * * @return the list of <code>{@link CmsProperty}</code> objects * * @throws CmsException if something goes wrong */ public List<CmsProperty> readHistoryPropertyObjects(CmsRequestContext context, I_CmsHistoryResource resource) throws CmsException { List<CmsProperty> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readHistoryPropertyObjects(dbc, resource); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_READ_PROPS_FOR_RESOURCE_1, context.getSitePath((CmsResource)resource)), e); } finally { dbc.clear(); } return result; } /** * Reads the structure id which is mapped to the given URL name, or null if the name is not * mapped to any structure IDs.<p> * * @param context the request context * @param name an URL name * * @return the structure ID which is mapped to the given name * * @throws CmsException if something goes wrong */ public CmsUUID readIdForUrlName(CmsRequestContext context, String name) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { return m_driverManager.readIdForUrlName(dbc, name); } catch (Exception e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_READ_ID_FOR_URLNAME_1, name); dbc.report(null, message, e); return null; // will never be reached } finally { dbc.clear(); } } /** * Reads the locks that were saved to the database in the previous run of OpenCms.<p> * * @throws CmsException if something goes wrong */ public void readLocks() throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(); try { m_driverManager.readLocks(dbc); } finally { dbc.clear(); } } /** * Reads the manager group of a project.<p> * * @param context the current request context * @param project the project to read from * * @return the group of a resource */ public CmsGroup readManagerGroup(CmsRequestContext context, CmsProject project) { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsGroup result = null; try { result = m_driverManager.readManagerGroup(dbc, project); } finally { dbc.clear(); } return result; } /** * Reads an organizational Unit based on its fully qualified name.<p> * * @param context the current request context * @param ouFqn the fully qualified name of the organizational Unit to be read * * @return the organizational Unit that with the provided fully qualified name * * @throws CmsException if something goes wrong */ public CmsOrganizationalUnit readOrganizationalUnit(CmsRequestContext context, String ouFqn) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsOrganizationalUnit result = null; try { result = m_driverManager.readOrganizationalUnit(dbc, CmsOrganizationalUnit.removeLeadingSeparator(ouFqn)); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_ORGUNIT_1, ouFqn), e); } finally { dbc.clear(); } return result; } /** * Reads the owner of a project from the OpenCms.<p> * * @param context the current request context * @param project the project to get the owner from * * @return the owner of a resource * * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsRequestContext context, CmsProject project) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readOwner(dbc, project); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_OWNER_FOR_PROJECT_2, project.getName(), project.getUuid()), e); } finally { dbc.clear(); } return result; } /** * Returns the parent folder to the given structure id.<p> * * @param context the current request context * @param structureId the child structure id * * @return the parent folder <code>{@link CmsResource}</code> * * @throws CmsException if something goes wrong */ public CmsResource readParentFolder(CmsRequestContext context, CmsUUID structureId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsResource result = null; try { result = m_driverManager.readParentFolder(dbc, structureId); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_READ_PARENT_FOLDER_2, dbc.currentProject().getName(), structureId), e); } finally { dbc.clear(); } return result; } /** * Builds a list of resources for a given path.<p> * * @param context the current request context * @param path the requested path * @param filter a filter object (only "includeDeleted" information is used!) * * @return list of <code>{@link CmsResource}</code>s * * @throws CmsException if something goes wrong */ public List<CmsResource> readPath(CmsRequestContext context, String path, CmsResourceFilter filter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsResource> result = null; try { result = m_driverManager.readPath(dbc, path, filter); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_PATH_2, dbc.currentProject().getName(), path), e); } finally { dbc.clear(); } return result; } /** * Reads a project given the projects id.<p> * * @param id the id of the project * * @return the project read * * @throws CmsException if something goes wrong */ public CmsProject readProject(CmsUUID id) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(); CmsProject result = null; try { result = m_driverManager.readProject(dbc, id); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_PROJECT_FOR_ID_1, id), e); } finally { dbc.clear(); } return result; } /** * Reads a project.<p> * * Important: Since a project name can be used multiple times, this is NOT the most efficient * way to read the project. This is only a convenience for front end developing. * Reading a project by name will return the first project with that name. * All core classes must use the id version {@link #readProject(CmsUUID)} to ensure the right project is read.<p> * * @param name the name of the project * * @return the project read * * @throws CmsException if something goes wrong */ public CmsProject readProject(String name) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(); CmsProject result = null; try { result = m_driverManager.readProject(dbc, CmsOrganizationalUnit.removeLeadingSeparator(name)); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_PROJECT_FOR_NAME_1, name), e); } finally { dbc.clear(); } return result; } /** * Returns the list of all resource names that define the "view" of the given project.<p> * * @param context the current request context * @param project the project to get the project resources for * * @return the list of all resources, as <code>{@link String}</code> objects * that define the "view" of the given project * * @throws CmsException if something goes wrong */ public List<String> readProjectResources(CmsRequestContext context, CmsProject project) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<String> result = null; try { result = m_driverManager.readProjectResources(dbc, project); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_PROJECT_RESOURCES_2, project.getName(), project.getUuid()), e); } finally { dbc.clear(); } return result; } /** * Reads all resources of a project that match a given state from the VFS.<p> * * Possible values for the <code>state</code> parameter are:<br> * <ul> * <li><code>{@link CmsResource#STATE_CHANGED}</code>: Read all "changed" resources in the project</li> * <li><code>{@link CmsResource#STATE_NEW}</code>: Read all "new" resources in the project</li> * <li><code>{@link CmsResource#STATE_DELETED}</code>: Read all "deleted" resources in the project</li> * <li><code>{@link CmsResource#STATE_KEEP}</code>: Read all resources either "changed", "new" or "deleted" in the project</li> * </ul><p> * * @param context the current request context * @param projectId the id of the project to read the file resources for * @param state the resource state to match * * @return a list of <code>{@link CmsResource}</code> objects matching the filter criteria * * @throws CmsException if something goes wrong * * @see CmsObject#readProjectView(CmsUUID, CmsResourceState) */ public List<CmsResource> readProjectView(CmsRequestContext context, CmsUUID projectId, CmsResourceState state) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsResource> result = null; try { result = m_driverManager.readProjectView(dbc, projectId, state); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_PROJECT_VIEW_1, projectId), e); } finally { dbc.clear(); } return result; } /** * Reads a property definition.<p> * * If no property definition with the given name is found, * <code>null</code> is returned.<p> * * @param context the current request context * @param name the name of the property definition to read * * @return the property definition that was read * * @throws CmsException a CmsDbEntryNotFoundException is thrown if the property definition does not exist */ public CmsPropertyDefinition readPropertyDefinition(CmsRequestContext context, String name) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsPropertyDefinition result = null; try { result = m_driverManager.readPropertyDefinition(dbc, name); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_PROPDEF_1, name), e); } finally { dbc.clear(); } return result; } /** * Reads a property object from a resource specified by a property name.<p> * * Returns <code>{@link CmsProperty#getNullProperty()}</code> if the property is not found.<p> * * @param context the context of the current request * @param resource the resource where the property is mapped to * @param key the property key name * @param search if <code>true</code>, the property is searched on all parent folders of the resource. * if it's not found attached directly to the resource. * * @return the required property, or <code>{@link CmsProperty#getNullProperty()}</code> if the property was not found * * @throws CmsException if something goes wrong */ public CmsProperty readPropertyObject(CmsRequestContext context, CmsResource resource, String key, boolean search) throws CmsException { return readPropertyObject(context, resource, key, search, null); } /** * Reads a property object from a resource specified by a property name.<p> * * Returns <code>{@link CmsProperty#getNullProperty()}</code> if the property is not found.<p> * * @param context the context of the current request * @param resource the resource where the property is mapped to * @param key the property key name * @param search if <code>true</code>, the property is searched on all parent folders of the resource. * if it's not found attached directly to the resource. * @param locale the locale for which the property should be read. * * @return the required property, or <code>{@link CmsProperty#getNullProperty()}</code> if the property was not found * * @throws CmsException if something goes wrong */ public CmsProperty readPropertyObject( CmsRequestContext context, CmsResource resource, String key, boolean search, Locale locale) throws CmsException { CmsProperty result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { if (null == locale) { result = m_driverManager.readPropertyObject(dbc, resource, key, search); } else { result = m_driverManager.readPropertyObject(dbc, resource, key, search, locale); } } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_PROP_FOR_RESOURCE_2, key, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Reads all property objects from a resource.<p> * * Returns an empty list if no properties are found.<p> * * If the <code>search</code> parameter is <code>true</code>, the properties of all * parent folders of the resource are also read. The results are merged with the * properties directly attached to the resource. While merging, a property * on a parent folder that has already been found will be ignored. * So e.g. if a resource has a property "Title" attached, and it's parent folder * has the same property attached but with a different value, the result list will * contain only the property with the value from the resource, not form the parent folder(s).<p> * * @param context the context of the current request * @param resource the resource where the property is mapped to * @param search <code>true</code>, if the properties should be searched on all parent folders if not found on the resource * * @return a list of <code>{@link CmsProperty}</code> objects * * @throws CmsException if something goes wrong */ public List<CmsProperty> readPropertyObjects(CmsRequestContext context, CmsResource resource, boolean search) throws CmsException { List<CmsProperty> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readPropertyObjects(dbc, resource, search); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_PROPS_FOR_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Reads the resources that were published in a publish task for a given publish history ID.<p> * * @param context the current request context * @param publishHistoryId unique ID to identify each publish task in the publish history * * @return a list of <code>{@link org.opencms.db.CmsPublishedResource}</code> objects * * @throws CmsException if something goes wrong */ public List<CmsPublishedResource> readPublishedResources(CmsRequestContext context, CmsUUID publishHistoryId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsPublishedResource> result = null; try { result = m_driverManager.readPublishedResources(dbc, publishHistoryId); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_PUBLISHED_RESOURCES_FOR_ID_1, publishHistoryId.toString()), e); } finally { dbc.clear(); } return result; } /** * Reads the historical resource entry for the given resource with the given version number.<p> * * @param context the current request context * @param resource the resource to be read the version for * @param version the version number to retrieve * * @return the resource that was read * * @throws CmsException if the resource could not be read for any reason * * @see CmsObject#readFile(CmsResource) * @see CmsObject#restoreResourceVersion(CmsUUID, int) * @see CmsObject#readResource(CmsUUID, int) */ public I_CmsHistoryResource readResource(CmsRequestContext context, CmsResource resource, int version) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); I_CmsHistoryResource result = null; try { result = m_driverManager.readResource(dbc, resource, version); } catch (CmsException e) { dbc.report( null, Messages.get().container( Messages.ERR_READING_RESOURCE_VERSION_2, dbc.removeSiteRoot(resource.getRootPath()), new Integer(version)), e); } finally { dbc.clear(); } return result; } /** * Reads a resource from the VFS, * using the specified resource filter.<p> * * A resource may be of type <code>{@link CmsFile}</code> or * <code>{@link CmsFolder}</code>. In case of * a file, the resource will not contain the binary file content. Since reading * the binary content is a cost-expensive database operation, it's recommended * to work with resources if possible, and only read the file content when absolutely * required. To "upgrade" a resource to a file, * use <code>{@link CmsObject#readFile(CmsResource)}</code>.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * @param context the current request context * @param structureID the ID of the structure which will be used) * @param filter the resource filter to use while reading * * @return the resource that was read * * @throws CmsException if the resource could not be read for any reason * * @see CmsObject#readResource(CmsUUID, CmsResourceFilter) * @see CmsObject#readResource(CmsUUID) * @see CmsObject#readFile(CmsResource) */ public CmsResource readResource(CmsRequestContext context, CmsUUID structureID, CmsResourceFilter filter) throws CmsException { CmsResource result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = readResource(dbc, structureID, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_RESOURCE_FOR_ID_1, structureID), e); } finally { dbc.clear(); } return result; } /** * Reads a resource from the VFS, * using the specified resource filter.<p> * * A resource may be of type <code>{@link CmsFile}</code> or * <code>{@link CmsFolder}</code>. In case of * a file, the resource will not contain the binary file content. Since reading * the binary content is a cost-expensive database operation, it's recommended * to work with resources if possible, and only read the file content when absolutely * required. To "upgrade" a resource to a file, * use <code>{@link CmsObject#readFile(CmsResource)}</code>.<p> * * The specified filter controls what kind of resources should be "found" * during the read operation. This will depend on the application. For example, * using <code>{@link CmsResourceFilter#DEFAULT}</code> will only return currently * "valid" resources, while using <code>{@link CmsResourceFilter#IGNORE_EXPIRATION}</code> * will ignore the date release / date expired information of the resource.<p> * * @param context the current request context * @param resourcePath the name of the resource to read (full path) * @param filter the resource filter to use while reading * * @return the resource that was read * * @throws CmsException if the resource could not be read for any reason * * @see CmsObject#readResource(String, CmsResourceFilter) * @see CmsObject#readResource(String) * @see CmsObject#readFile(CmsResource) */ public CmsResource readResource(CmsRequestContext context, String resourcePath, CmsResourceFilter filter) throws CmsException { CmsResource result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = readResource(dbc, resourcePath, filter); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_RESOURCE_1, dbc.removeSiteRoot(resourcePath)), e); } finally { dbc.clear(); } return result; } /** * Reads all resources below the given path matching the filter criteria, * including the full tree below the path only in case the <code>readTree</code> * parameter is <code>true</code>.<p> * * @param context the current request context * @param parent the parent path to read the resources from * @param filter the filter * @param readTree <code>true</code> to read all subresources * * @return a list of <code>{@link CmsResource}</code> objects matching the filter criteria * * @throws CmsSecurityException if the user has insufficient permission for the given resource (read is required) * @throws CmsException if something goes wrong * */ public List<CmsResource> readResources( CmsRequestContext context, CmsResource parent, CmsResourceFilter filter, boolean readTree) throws CmsException, CmsSecurityException { List<CmsResource> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { // check the access permissions checkPermissions(dbc, parent, CmsPermissionSet.ACCESS_READ, true, CmsResourceFilter.ALL); result = m_driverManager.readResources(dbc, parent, filter, readTree); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_RESOURCES_1, context.removeSiteRoot(parent.getRootPath())), e); } finally { dbc.clear(); } return result; } /** * Returns the resources that were visited by a user set in the filter.<p> * * @param context the request context * @param poolName the name of the database pool to use * @param filter the filter that is used to get the visited resources * * @return the resources that were visited by a user set in the filter * * @throws CmsException if something goes wrong */ public List<CmsResource> readResourcesVisitedBy( CmsRequestContext context, String poolName, CmsVisitedByFilter filter) throws CmsException { List<CmsResource> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readResourcesVisitedBy(dbc, poolName, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_VISITED_RESOURCES_1, filter.toString()), e); } finally { dbc.clear(); } return result; } /** * Reads all resources that have a value (containing the specified value) set * for the specified property (definition) in the given path.<p> * * If the <code>value</code> parameter is <code>null</code>, all resources having the * given property set are returned.<p> * * Both individual and shared properties of a resource are checked.<p> * * @param context the current request context * @param folder the folder to get the resources with the property from * @param propertyDefinition the name of the property (definition) to check for * @param value the string to search in the value of the property * @param filter the resource filter to apply to the result set * * @return a list of all <code>{@link CmsResource}</code> objects * that have a value set for the specified property. * * @throws CmsException if something goes wrong */ public List<CmsResource> readResourcesWithProperty( CmsRequestContext context, CmsResource folder, String propertyDefinition, String value, CmsResourceFilter filter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<CmsResource> result = null; try { result = m_driverManager.readResourcesWithProperty(dbc, folder, propertyDefinition, value, filter); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_READ_RESOURCES_FOR_PROP_VALUE_3, context.removeSiteRoot(folder.getRootPath()), propertyDefinition, value), e); } finally { dbc.clear(); } return result; } /** * Returns a set of users that are responsible for a specific resource.<p> * * @param context the current request context * @param resource the resource to get the responsible users from * * @return the set of users that are responsible for a specific resource * * @throws CmsException if something goes wrong */ public Set<I_CmsPrincipal> readResponsiblePrincipals(CmsRequestContext context, CmsResource resource) throws CmsException { Set<I_CmsPrincipal> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readResponsiblePrincipals(dbc, resource); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_RESPONSIBLE_USERS_1, resource.getRootPath()), e); } finally { dbc.clear(); } return result; } /** * Returns a set of users that are responsible for a specific resource.<p> * * @param context the current request context * @param resource the resource to get the responsible users from * * @return the set of users that are responsible for a specific resource * * @throws CmsException if something goes wrong */ public Set<CmsUser> readResponsibleUsers(CmsRequestContext context, CmsResource resource) throws CmsException { Set<CmsUser> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readResponsibleUsers(dbc, resource); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_RESPONSIBLE_USERS_1, resource.getRootPath()), e); } finally { dbc.clear(); } return result; } /** * Returns a List of all siblings of the specified resource, * the specified resource being always part of the result set.<p> * * @param context the request context * @param resource the specified resource * @param filter a filter object * * @return a list of <code>{@link CmsResource}</code>s that * are siblings to the specified resource, * including the specified resource itself * * @throws CmsException if something goes wrong */ public List<CmsResource> readSiblings(CmsRequestContext context, CmsResource resource, CmsResourceFilter filter) throws CmsException { List<CmsResource> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readSiblings(dbc, resource, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_SIBLINGS_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Returns the parameters of a resource in the table of all published template resources.<p> * * @param context the current request context * @param rfsName the rfs name of the resource * * @return the parameter string of the requested resource * * @throws CmsException if something goes wrong */ public String readStaticExportPublishedResourceParameters(CmsRequestContext context, String rfsName) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); String result = null; try { result = m_driverManager.readStaticExportPublishedResourceParameters(dbc, rfsName); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_STATEXP_PUBLISHED_RESOURCE_PARAMS_1, rfsName), e); } finally { dbc.clear(); } return result; } /** * Returns a list of all template resources which must be processed during a static export.<p> * * @param context the current request context * @param parameterResources flag for reading resources with parameters (1) or without (0) * @param timestamp for reading the data from the db * * @return a list of template resources as <code>{@link String}</code> objects * * @throws CmsException if something goes wrong */ public List<String> readStaticExportResources(CmsRequestContext context, int parameterResources, long timestamp) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); List<String> result = null; try { result = m_driverManager.readStaticExportResources(dbc, parameterResources, timestamp); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_STATEXP_RESOURCES_1, new Date(timestamp)), e); } finally { dbc.clear(); } return result; } /** * Returns the subscribed history resources that were deleted.<p> * * @param context the request context * @param poolName the name of the database pool to use * @param user the user that subscribed to the resource * @param groups the groups to check subscribed resources for * @param parent the parent resource (folder) of the deleted resources, if <code>null</code> all deleted resources will be returned * @param includeSubFolders indicates if the sub folders of the specified folder path should be considered, too * @param deletedFrom the time stamp from which the resources should have been deleted * * @return the subscribed history resources that were deleted * * @throws CmsException if something goes wrong */ public List<I_CmsHistoryResource> readSubscribedDeletedResources( CmsRequestContext context, String poolName, CmsUser user, List<CmsGroup> groups, CmsResource parent, boolean includeSubFolders, long deletedFrom) throws CmsException { List<I_CmsHistoryResource> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readSubscribedDeletedResources( dbc, poolName, user, groups, parent, includeSubFolders, deletedFrom); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_READ_SUBSCRIBED_DELETED_RESOURCES_1, user.getName()), e); } finally { dbc.clear(); } return result; } /** * Returns the resources that were subscribed by a user or group set in the filter.<p> * * @param context the request context * @param poolName the name of the database pool to use * @param filter the filter that is used to get the subscribed resources * * @return the resources that were subscribed by a user or group set in the filter * * @throws CmsException if something goes wrong */ public List<CmsResource> readSubscribedResources( CmsRequestContext context, String poolName, CmsSubscriptionFilter filter) throws CmsException { List<CmsResource> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.readSubscribedResources(dbc, poolName, filter); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_SUBSCRIBED_RESOURCES_1, filter.toString()), e); } finally { dbc.clear(); } return result; } /** * Reads the URL name mappings matching a given filter.<p> * * @param context the current request context * @param filter the filter to match * * @return the matching URL name mappings * * @throws CmsException if something goes wrong */ public List<CmsUrlNameMappingEntry> readUrlNameMappings(CmsRequestContext context, CmsUrlNameMappingFilter filter) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { return m_driverManager.readUrlNameMappings(dbc, filter); } catch (Exception e) { CmsMessageContainer message = Messages.get().container( Messages.ERR_DB_OPERATION_1, e.getLocalizedMessage()); dbc.report(null, message, e); return null; // will never be reached } finally { dbc.clear(); } } /** * Reads the newest URL names of a structure id for all locales.<p> * * @param context the current context * @param id a structure id * * @return the list of URL names for all * @throws CmsException if something goes wrong */ public List<String> readUrlNamesForAllLocales(CmsRequestContext context, CmsUUID id) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { return m_driverManager.readUrlNamesForAllLocales(dbc, id); } catch (Exception e) { CmsMessageContainer message = Messages.get().container( Messages.ERR_READ_NEWEST_URLNAME_FOR_ID_1, id.toString()); dbc.report(null, message, e); return null; // will never be reached } finally { dbc.clear(); } } /** * Returns a user object based on the id of a user.<p> * * @param context the current request context * @param id the id of the user to read * * @return the user read * * @throws CmsException if something goes wrong */ public CmsUser readUser(CmsRequestContext context, CmsUUID id) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readUser(dbc, id); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_FOR_ID_1, id.toString()), e); } finally { dbc.clear(); } return result; } /** * Returns a user object.<p> * * @param context the current request context * @param username the name of the user that is to be read * * @return user read form the cms * * @throws CmsException if operation was not successful */ public CmsUser readUser(CmsRequestContext context, String username) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readUser(dbc, CmsOrganizationalUnit.removeLeadingSeparator(username)); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_FOR_NAME_1, username), e); } finally { dbc.clear(); } return result; } /** * Returns a user object if the password for the user is correct.<p> * * If the user/password pair is not valid a <code>{@link CmsException}</code> is thrown.<p> * * @param context the current request context * @param username the user name of the user that is to be read * @param password the password of the user that is to be read * * @return user read * * @throws CmsException if operation was not successful */ public CmsUser readUser(CmsRequestContext context, String username, String password) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUser result = null; try { result = m_driverManager.readUser(dbc, CmsOrganizationalUnit.removeLeadingSeparator(username), password); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_READ_USER_FOR_NAME_1, username), e); } finally { dbc.clear(); } return result; } /** * Removes an access control entry for a given resource and principal.<p> * * @param context the current request context * @param resource the resource * @param principal the id of the principal to remove the the access control entry for * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (control of access control is required). * */ public void removeAccessControlEntry(CmsRequestContext context, CmsResource resource, CmsUUID principal) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_CONTROL, true, CmsResourceFilter.ALL); m_driverManager.removeAccessControlEntry(dbc, resource, principal); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_REMOVE_ACL_ENTRY_2, context.getSitePath(resource), principal.toString()), e); } finally { dbc.clear(); } } /** * Removes a resource from the given organizational unit.<p> * * @param context the current request context * @param orgUnit the organizational unit to remove the resource from * @param resource the resource that is to be removed from the organizational unit * * @throws CmsException if something goes wrong * * @see org.opencms.security.CmsOrgUnitManager#addResourceToOrgUnit(CmsObject, String, String) * @see org.opencms.security.CmsOrgUnitManager#addResourceToOrgUnit(CmsObject, String, String) */ public void removeResourceFromOrgUnit( CmsRequestContext context, CmsOrganizationalUnit orgUnit, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.ADMINISTRATOR.forOrgUnit(orgUnit.getName())); checkOfflineProject(dbc); m_driverManager.removeResourceFromOrgUnit(dbc, orgUnit, resource); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_REMOVE_RESOURCE_FROM_ORGUNIT_2, orgUnit.getName(), dbc.removeSiteRoot(resource.getRootPath())), e); } finally { dbc.clear(); } } /** * Removes a resource from the current project of the user.<p> * * @param context the current request context * @param resource the resource to apply this operation to * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not have management access to the project * * @see org.opencms.file.types.I_CmsResourceType#copyResourceToProject(CmsObject, CmsSecurityManager, CmsResource) */ public void removeResourceFromProject(CmsRequestContext context, CmsResource resource) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkManagerOfProjectRole(dbc, context.getCurrentProject()); m_driverManager.removeResourceFromProject(dbc, resource); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_COPY_RESOURCE_TO_PROJECT_2, context.getSitePath(resource), context.getCurrentProject().getName()), e); } finally { dbc.clear(); } } /** * Removes the given resource to the given user's publish list.<p> * * @param context the request context * @param structureIds the collection of structure IDs to remove * * @throws CmsException if something goes wrong */ public void removeResourceFromUsersPubList(CmsRequestContext context, Collection<CmsUUID> structureIds) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.removeResourceFromUsersPubList(dbc, context.getCurrentUser().getId(), structureIds); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_REMOVE_RESOURCE_FROM_PUBLIST_2, context.getCurrentUser().getName(), structureIds), e); } finally { dbc.clear(); } } /** * Removes a user from a group.<p> * * @param context the current request context * @param username the name of the user that is to be removed from the group * @param groupname the name of the group * @param readRoles if to read roles or groups * * @throws CmsException if operation was not successful * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#ACCOUNT_MANAGER} * */ public void removeUserFromGroup(CmsRequestContext context, String username, String groupname, boolean readRoles) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsRole role = CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(groupname)); checkRoleForUserModification(dbc, username, role); m_driverManager.removeUserFromGroup( dbc, CmsOrganizationalUnit.removeLeadingSeparator(username), CmsOrganizationalUnit.removeLeadingSeparator(groupname), readRoles); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_REMOVE_USER_FROM_GROUP_2, username, groupname), e); } finally { dbc.clear(); } } /** * Replaces the content, type and properties of a resource.<p> * * @param context the current request context * @param resource the name of the resource to apply this operation to * @param type the new type of the resource * @param content the new content of the resource * @param properties the new properties of the resource * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required) * * @see CmsObject#replaceResource(String, int, byte[], List) * @see org.opencms.file.types.I_CmsResourceType#replaceResource(CmsObject, CmsSecurityManager, CmsResource, int, byte[], List) */ @SuppressWarnings("javadoc") public void replaceResource( CmsRequestContext context, CmsResource resource, int type, byte[] content, List<CmsProperty> properties) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); if (CmsResourceTypeJsp.isJspTypeId(type)) { // security check preventing the creation of a jsp file without permissions checkRoleForResource(dbc, CmsRole.VFS_MANAGER, resource); } m_driverManager.replaceResource(dbc, resource, type, content, properties); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_REPLACE_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Resets the password for a specified user.<p> * * @param context the current request context * @param username the name of the user * @param oldPassword the old password * @param newPassword the new password * * @throws CmsException if the user data could not be read from the database * @throws CmsSecurityException if the specified user name and old password could not be verified */ public void resetPassword(CmsRequestContext context, String username, String oldPassword, String newPassword) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.resetPassword( dbc, CmsOrganizationalUnit.removeLeadingSeparator(username), oldPassword, newPassword); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_RESET_PASSWORD_1, username), e); } finally { dbc.clear(); } } /** * Returns the original path of given resource, that is the online path for the resource.<p> * * If it differs from the offline path, the resource has been moved.<p> * * @param context the current request context * @param resource the resource to get the path for * * @return the online path * * @throws CmsException if something goes wrong * * @see org.opencms.workplace.commons.CmsUndoChanges#resourceOriginalPath(CmsObject, String) */ public String resourceOriginalPath(CmsRequestContext context, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); String result = null; try { checkOfflineProject(dbc); result = m_driverManager.getVfsDriver( dbc).readResource(dbc, CmsProject.ONLINE_PROJECT_ID, resource.getStructureId(), true).getRootPath(); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_TEST_MOVED_RESOURCE_1, dbc.removeSiteRoot(resource.getRootPath())), e); } finally { dbc.clear(); } return result; } /** * Restores a deleted resource identified by its structure id from the historical archive.<p> * * @param context the current request context * @param structureId the structure id of the resource to restore * * @throws CmsException if something goes wrong * * @see CmsObject#restoreDeletedResource(CmsUUID) */ public void restoreDeletedResource(CmsRequestContext context, CmsUUID structureId) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); // write permissions on parent folder are checked later m_driverManager.restoreDeletedResource(dbc, structureId); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_RESTORE_DELETED_RESOURCE_1, structureId), e); } finally { dbc.clear(); } } /** * Restores a resource in the current project with the given version from the historical archive.<p> * * @param context the current request context * @param resource the resource to restore from the archive * @param version the version number to restore * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required) * * @see CmsObject#restoreResourceVersion(CmsUUID, int) * @see org.opencms.file.types.I_CmsResourceType#restoreResource(CmsObject, CmsSecurityManager, CmsResource, int) */ public void restoreResource(CmsRequestContext context, CmsResource resource, int version) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.restoreResource(dbc, resource, version); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_RESTORE_RESOURCE_2, context.getSitePath(resource), new Integer(version)), e); } finally { dbc.clear(); } } /** * Saves the aliases for a given resource.<p> * * This method completely replaces any existing aliases for the same structure id. * * @param context the request context * @param resource the resource for which the aliases should be written * @param aliases the list of aliases to write, where all aliases must have the same structure id as the resource * * @throws CmsException if something goes wrong */ public void saveAliases(CmsRequestContext context, CmsResource resource, List<CmsAlias> aliases) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { if ((aliases.size() > 0) && !(resource.getStructureId().equals(aliases.get(0).getStructureId()))) { throw new IllegalArgumentException("Resource does not match aliases!"); } checkPermissions(context, resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ALL); m_driverManager.saveAliases(dbc, context.getCurrentProject(), resource.getStructureId(), aliases); Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put(I_CmsEventListener.KEY_RESOURCE, resource); eventData.put(I_CmsEventListener.KEY_CHANGE, new Integer(CmsDriverManager.CHANGED_RESOURCE)); OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_RESOURCE_MODIFIED, eventData)); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); } finally { dbc.clear(); } } /** * Replaces the rewrite aliases for a given site root.<p> * * @param requestContext the current request context * @param siteRoot the site root for which the rewrite aliases should be replaced * @param newAliases the new list of aliases for the given site root * * @throws CmsException if something goes wrong */ public void saveRewriteAliases(CmsRequestContext requestContext, String siteRoot, List<CmsRewriteAlias> newAliases) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(requestContext); try { // checkOfflineProject(dbc); // checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.saveRewriteAliases(dbc, siteRoot, newAliases); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e); } finally { dbc.clear(); } } /** * Searches users by search criteria.<p> * * @param requestContext the request context * @param searchParams the search criteria object * * @return a list of users * @throws CmsException if something goes wrong */ public List<CmsUser> searchUsers(CmsRequestContext requestContext, CmsUserSearchParameters searchParams) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(requestContext); try { return m_driverManager.searchUsers(dbc, searchParams); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_SEARCH_USERS_0), e); return null; } finally { dbc.clear(); } } /** * Changes the "expire" date of a resource.<p> * * @param context the current request context * @param resource the resource to touch * @param dateExpired the new expire date of the changed resource * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required) * * @see CmsObject#setDateExpired(String, long, boolean) * @see org.opencms.file.types.I_CmsResourceType#setDateExpired(CmsObject, CmsSecurityManager, CmsResource, long, boolean) */ public void setDateExpired(CmsRequestContext context, CmsResource resource, long dateExpired) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); m_driverManager.setDateExpired(dbc, resource, dateExpired); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_SET_DATE_EXPIRED_2, new Object[] {new Date(dateExpired), context.getSitePath(resource)}), e); } finally { dbc.clear(); } } /** * Changes the "last modified" time stamp of a resource.<p> * * @param context the current request context * @param resource the resource to touch * @param dateLastModified the new time stamp of the changed resource * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required) * * @see CmsObject#setDateLastModified(String, long, boolean) * @see org.opencms.file.types.I_CmsResourceType#setDateLastModified(CmsObject, CmsSecurityManager, CmsResource, long, boolean) */ public void setDateLastModified(CmsRequestContext context, CmsResource resource, long dateLastModified) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); m_driverManager.setDateLastModified(dbc, resource, dateLastModified); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_SET_DATE_LAST_MODIFIED_2, new Object[] {new Date(dateLastModified), context.getSitePath(resource)}), e); } finally { dbc.clear(); } } /** * Changes the "release" date of a resource.<p> * * @param context the current request context * @param resource the resource to touch * @param dateReleased the new release date of the changed resource * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required) * * @see CmsObject#setDateReleased(String, long, boolean) * @see org.opencms.file.types.I_CmsResourceType#setDateReleased(CmsObject, CmsSecurityManager, CmsResource, long, boolean) */ public void setDateReleased(CmsRequestContext context, CmsResource resource, long dateReleased) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.IGNORE_EXPIRATION); m_driverManager.setDateReleased(dbc, resource, dateReleased); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_SET_DATE_RELEASED_2, new Object[] {new Date(dateReleased), context.getSitePath(resource)}), e); } finally { dbc.clear(); } } /** * Sets a new parent-group for an already existing group.<p> * * @param context the current request context * @param groupName the name of the group that should be written * @param parentGroupName the name of the parent group to set, * or <code>null</code> if the parent * group should be deleted. * * @throws CmsException if operation was not successful * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#ACCOUNT_MANAGER} * */ public void setParentGroup(CmsRequestContext context, String groupName, String parentGroupName) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(groupName))); m_driverManager.setParentGroup( dbc, CmsOrganizationalUnit.removeLeadingSeparator(groupName), CmsOrganizationalUnit.removeLeadingSeparator(parentGroupName)); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_SET_PARENT_GROUP_2, parentGroupName, groupName), e); } finally { dbc.clear(); } } /** * Sets the password for a user.<p> * * @param context the current request context * @param username the name of the user * @param newPassword the new password * * @throws CmsException if operation was not successful * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#ACCOUNT_MANAGER} */ public void setPassword(CmsRequestContext context, String username, String newPassword) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsRole role = CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(username)); checkRoleForUserModification(dbc, username, role); m_driverManager.setPassword(dbc, CmsOrganizationalUnit.removeLeadingSeparator(username), newPassword); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_SET_PASSWORD_1, username), e); } finally { dbc.clear(); } } /** * Marks a subscribed resource as deleted.<p> * * @param context the request context * @param poolName the name of the database pool to use * @param resource the subscribed resource to mark as deleted * * @throws CmsException if something goes wrong */ public void setSubscribedResourceAsDeleted(CmsRequestContext context, String poolName, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.setSubscribedResourceAsDeleted(dbc, poolName, resource); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_SET_SUBSCRIBED_RESOURCE_AS_DELETED_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Moves an user to the given organizational unit.<p> * * @param context the current request context * @param orgUnit the organizational unit to add the principal to * @param user the user that is to be move to the organizational unit * * @throws CmsException if something goes wrong * * @see org.opencms.security.CmsOrgUnitManager#setUsersOrganizationalUnit(CmsObject, String, String) */ public void setUsersOrganizationalUnit(CmsRequestContext context, CmsOrganizationalUnit orgUnit, CmsUser user) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.ADMINISTRATOR.forOrgUnit(orgUnit.getName())); checkOfflineProject(dbc); m_driverManager.setUsersOrganizationalUnit(dbc, orgUnit, user); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_SET_USERS_ORGUNIT_2, orgUnit.getName(), user.getName()), e); } finally { dbc.clear(); } } /** * Subscribes the user or group to the resource.<p> * * @param context the request context * @param poolName the name of the database pool to use * @param principal the principal that subscribes to the resource * @param resource the resource to subscribe to * * @throws CmsException if something goes wrong */ public void subscribeResourceFor( CmsRequestContext context, String poolName, CmsPrincipal principal, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.subscribeResourceFor(dbc, poolName, principal, resource); } catch (Exception e) { if (principal instanceof CmsUser) { dbc.report( null, Messages.get().container( Messages.ERR_SUBSCRIBE_RESOURCE_FOR_USER_2, context.getSitePath(resource), principal.getName()), e); } else { dbc.report( null, Messages.get().container( Messages.ERR_SUBSCRIBE_RESOURCE_FOR_GROUP_2, context.getSitePath(resource), principal.getName()), e); } } finally { dbc.clear(); } } /** * Undelete the resource by resetting it's state.<p> * * @param context the current request context * @param resource the name of the resource to apply this operation to * * @throws CmsException if something goes wrong * * @see CmsObject#undeleteResource(String, boolean) * @see org.opencms.file.types.I_CmsResourceType#undelete(CmsObject, CmsSecurityManager, CmsResource, boolean) */ public void undelete(CmsRequestContext context, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); checkSystemLocks(dbc, resource); m_driverManager.undelete(dbc, resource); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_UNDELETE_FOR_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Undos all changes in the resource by restoring the version from the * online project to the current offline project.<p> * * @param context the current request context * @param resource the name of the resource to apply this operation to * @param mode the undo mode, one of the <code>{@link CmsResource}#UNDO_XXX</code> constants * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required) * * @see CmsObject#undoChanges(String, CmsResource.CmsResourceUndoMode) * @see org.opencms.file.types.I_CmsResourceType#undoChanges(CmsObject, CmsSecurityManager, CmsResource, CmsResource.CmsResourceUndoMode) */ public void undoChanges(CmsRequestContext context, CmsResource resource, CmsResource.CmsResourceUndoMode mode) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); checkSystemLocks(dbc, resource); m_driverManager.undoChanges(dbc, resource, mode); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_UNDO_CHANGES_FOR_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Unlocks all resources in this project.<p> * * @param context the current request context * @param projectId the id of the project to be published * * @throws CmsException if something goes wrong * @throws CmsRoleViolationException if the current user does not own the required permissions */ public void unlockProject(CmsRequestContext context, CmsUUID projectId) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsProject project = m_driverManager.readProject(dbc, projectId); try { checkManagerOfProjectRole(dbc, project); m_driverManager.unlockProject(project); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_UNLOCK_PROJECT_2, projectId, dbc.currentUser().getName()), e); } finally { dbc.clear(); } } /** * Unlocks a resource.<p> * * @param context the current request context * @param resource the resource to unlock * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required) * * @see CmsObject#unlockResource(String) * @see org.opencms.file.types.I_CmsResourceType#unlockResource(CmsObject, CmsSecurityManager, CmsResource) */ public void unlockResource(CmsRequestContext context, CmsResource resource) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions( dbc, resource, CmsPermissionSet.ACCESS_WRITE, LockCheck.shallowOnly, CmsResourceFilter.ALL); m_driverManager.unlockResource(dbc, resource, false, false); } catch (CmsException e) { dbc.report( null, Messages.get().container( Messages.ERR_UNLOCK_RESOURCE_3, context.getSitePath(resource), dbc.currentUser().getName(), e.getLocalizedMessage(dbc.getRequestContext().getLocale())), e); } finally { dbc.clear(); } } /** * Unsubscribes all deleted resources that were deleted before the specified time stamp.<p> * * @param context the request context * @param poolName the name of the database pool to use * @param deletedTo the time stamp to which the resources have been deleted * * @throws CmsException if something goes wrong */ public void unsubscribeAllDeletedResources(CmsRequestContext context, String poolName, long deletedTo) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.unsubscribeAllDeletedResources(dbc, poolName, deletedTo); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_UNSUBSCRIBE_ALL_DELETED_RESOURCES_USER_0), e); } finally { dbc.clear(); } } /** * Unsubscribes the user or group from all resources.<p> * * @param context the request context * @param poolName the name of the database pool to use * @param principal the principal that unsubscribes from all resources * * @throws CmsException if something goes wrong */ public void unsubscribeAllResourcesFor(CmsRequestContext context, String poolName, CmsPrincipal principal) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.unsubscribeAllResourcesFor(dbc, poolName, principal); } catch (Exception e) { if (principal instanceof CmsUser) { dbc.report( null, Messages.get().container(Messages.ERR_UNSUBSCRIBE_ALL_RESOURCES_USER_1, principal.getName()), e); } else { dbc.report( null, Messages.get().container(Messages.ERR_UNSUBSCRIBE_ALL_RESOURCES_GROUP_1, principal.getName()), e); } } finally { dbc.clear(); } } /** * Unsubscribes the principal from the resource.<p> * * @param context the request context * @param poolName the name of the database pool to use * @param principal the principal that unsubscribes from the resource * @param resource the resource to unsubscribe from * * @throws CmsException if something goes wrong */ public void unsubscribeResourceFor( CmsRequestContext context, String poolName, CmsPrincipal principal, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.unsubscribeResourceFor(dbc, poolName, principal, resource); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_UNSUBSCRIBE_RESOURCE_FOR_GROUP_2, context.getSitePath(resource), principal.getName()), e); } finally { dbc.clear(); } } /** * Unsubscribes all groups and users from the resource.<p> * * @param context the request context * @param poolName the name of the database pool to use * @param resource the resource to unsubscribe all groups and users from * * @throws CmsException if something goes wrong */ public void unsubscribeResourceForAll(CmsRequestContext context, String poolName, CmsResource resource) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.unsubscribeResourceForAll(dbc, poolName, resource); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_UNSUBSCRIBE_RESOURCE_ALL_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Updates the last login date on the given user to the current time.<p> * * @param context the current request context * @param user the user to be updated * * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#ACCOUNT_MANAGER} for the current project * @throws CmsException if operation was not successful */ public void updateLastLoginDate(CmsRequestContext context, CmsUser user) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsRole role = CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(user.getName())); checkRoleForUserModification(dbc, user.getName(), role); m_driverManager.updateLastLoginDate(dbc, user); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_USER_1, user.getName()), e); } finally { dbc.clear(); } } /** * Logs everything that has not been written to DB jet.<p> * * @throws CmsException if something goes wrong */ public void updateLog() throws CmsException { if (m_dbContextFactory == null) { // already shutdown return; } CmsDbContext dbc = m_dbContextFactory.getDbContext(); try { m_driverManager.updateLog(dbc); } finally { dbc.clear(); } } /** * Updates/Creates the relations for the given resource.<p> * * @param context the current user context * @param resource the resource to update the relations for * @param relations the relations to update * * @throws CmsException if something goes wrong * * @see CmsDriverManager#updateRelationsForResource(CmsDbContext, CmsResource, List) */ public void updateRelationsForResource(CmsRequestContext context, CmsResource resource, List<CmsLink> relations) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.updateRelationsForResource(dbc, resource, relations); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_UPDATE_RELATIONS_1, dbc.removeSiteRoot(resource.getRootPath())), e); } finally { dbc.clear(); } } /** * Tests if a user is member of the given group.<p> * * @param context the current request context * @param username the name of the user to check * @param groupname the name of the group to check * * @return <code>true</code>, if the user is in the group; or <code>false</code> otherwise * * @throws CmsException if operation was not successful */ public boolean userInGroup(CmsRequestContext context, String username, String groupname) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); boolean result = false; try { result = m_driverManager.userInGroup( dbc, CmsOrganizationalUnit.removeLeadingSeparator(username), CmsOrganizationalUnit.removeLeadingSeparator(groupname), false); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_USER_IN_GROUP_2, username, groupname), e); } finally { dbc.clear(); } return result; } /** * Checks if a new password follows the rules for * new passwords, which are defined by a Class implementing the * <code>{@link org.opencms.security.I_CmsPasswordHandler}</code> * interface and configured in the opencms.properties file.<p> * * If this method throws no exception the password is valid.<p> * * @param password the new password that has to be checked * * @throws CmsSecurityException if the password is not valid */ public void validatePassword(String password) throws CmsSecurityException { m_driverManager.validatePassword(password); } /** * Validates the relations for the given resources.<p> * * @param context the current request context * @param publishList the resources to validate during publishing * @param report a report to write the messages to * * @return a map with lists of invalid links * (<code>{@link org.opencms.relations.CmsRelation}}</code> objects) * keyed by root paths * * @throws Exception if something goes wrong */ public Map<String, List<CmsRelation>> validateRelations( CmsRequestContext context, CmsPublishList publishList, I_CmsReport report) throws Exception { Map<String, List<CmsRelation>> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.validateRelations(dbc, publishList, report); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_VALIDATE_RELATIONS_0), e); } finally { dbc.clear(); } return result; } /** * Writes an access control entries to a given resource.<p> * * @param context the current request context * @param resource the resource * @param ace the entry to write * * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_CONTROL} required) * @throws CmsException if something goes wrong */ public void writeAccessControlEntry(CmsRequestContext context, CmsResource resource, CmsAccessControlEntry ace) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_CONTROL, true, CmsResourceFilter.ALL); if (ace.getPrincipal().equals(CmsAccessControlEntry.PRINCIPAL_OVERWRITE_ALL_ID)) { // only vfs managers can set the overwrite all ACE checkRoleForResource(dbc, CmsRole.VFS_MANAGER, resource); } m_driverManager.writeAccessControlEntry(dbc, resource, ace); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_WRITE_ACL_ENTRY_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Writes a resource to the OpenCms VFS, including it's content.<p> * * Applies only to resources of type <code>{@link CmsFile}</code> * i.e. resources that have a binary content attached.<p> * * Certain resource types might apply content validation or transformation rules * before the resource is actually written to the VFS. The returned result * might therefore be a modified version from the provided original.<p> * * @param context the current request context * @param resource the resource to apply this operation to * * @return the written resource (may have been modified) * * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required) * @throws CmsException if something goes wrong * * @see CmsObject#writeFile(CmsFile) * @see org.opencms.file.types.I_CmsResourceType#writeFile(CmsObject, CmsSecurityManager, CmsFile) */ public CmsFile writeFile(CmsRequestContext context, CmsFile resource) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsFile result = null; try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); result = m_driverManager.writeFile(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_FILE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } return result; } /** * Writes an already existing group.<p> * * The group id has to be a valid OpenCms group id.<br> * * The group with the given id will be completely overridden * by the given data.<p> * * @param context the current request context * @param group the group that should be written * * @throws CmsRoleViolationException if the current user does not own the role {@link CmsRole#ACCOUNT_MANAGER} for the current project * @throws CmsException if operation was not successful */ public void writeGroup(CmsRequestContext context, CmsGroup group) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(group.getName()))); m_driverManager.writeGroup(dbc, group); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_GROUP_1, group.getName()), e); } finally { dbc.clear(); } } /** * Creates a historical entry of the current project.<p> * * @param context the current request context * @param publishTag the correlative publish tag * @param publishDate the date of publishing * * @throws CmsException if operation was not successful */ public void writeHistoryProject(CmsRequestContext context, int publishTag, long publishDate) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.writeHistoryProject(dbc, publishTag, publishDate); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_HISTORY_PROJECT_4, new Object[] { new Integer(publishTag), dbc.currentProject().getName(), dbc.currentProject().getUuid(), new Long(publishDate)}), e); } finally { dbc.clear(); } } /** * Writes the locks that are currently stored in-memory to the database to allow restoring them in * later startups.<p> * * This overwrites the locks previously stored in the underlying database table.<p> * * @throws CmsException if something goes wrong */ public void writeLocks() throws CmsException { if (m_dbContextFactory == null) { // already shutdown return; } CmsDbContext dbc = m_dbContextFactory.getDbContext(); try { m_driverManager.writeLocks(dbc); } finally { dbc.clear(); } } /** * Writes an already existing organizational unit.<p> * * The organizational unit id has to be a valid OpenCms organizational unit id.<p> * * The organizational unit with the given id will be completely overridden * by the given data.<p> * * @param context the current request context * @param organizationalUnit the organizational unit that should be written * * @throws CmsException if operation was not successful * * @see org.opencms.security.CmsOrgUnitManager#writeOrganizationalUnit(CmsObject, CmsOrganizationalUnit) */ public void writeOrganizationalUnit(CmsRequestContext context, CmsOrganizationalUnit organizationalUnit) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkRole(dbc, CmsRole.ADMINISTRATOR.forOrgUnit(organizationalUnit.getName())); checkOfflineProject(dbc); m_driverManager.writeOrganizationalUnit(dbc, organizationalUnit); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_ORGUNIT_1, organizationalUnit.getName()), e); } finally { dbc.clear(); } } /** * Writes an already existing project.<p> * * The project id has to be a valid OpenCms project id.<br> * * The project with the given id will be completely overridden * by the given data.<p> * * @param project the project that should be written * @param context the current request context * * @throws CmsRoleViolationException if the current user does not own the required permissions * @throws CmsException if operation was not successful */ public void writeProject(CmsRequestContext context, CmsProject project) throws CmsRoleViolationException, CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkManagerOfProjectRole(dbc, project); m_driverManager.writeProject(dbc, project); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_PROJECT_1, project.getName()), e); } finally { dbc.clear(); } } /** * Writes a property for a specified resource.<p> * * @param context the current request context * @param resource the resource to write the property for * @param property the property to write * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required) * * @see CmsObject#writePropertyObject(String, CmsProperty) * @see org.opencms.file.types.I_CmsResourceType#writePropertyObject(CmsObject, CmsSecurityManager, CmsResource, CmsProperty) */ public void writePropertyObject(CmsRequestContext context, CmsResource resource, CmsProperty property) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions( dbc, resource, CmsPermissionSet.ACCESS_WRITE, LockCheck.shallowOnly, CmsResourceFilter.IGNORE_EXPIRATION); m_driverManager.writePropertyObject(dbc, resource, property); } catch (Exception e) { dbc.report( null, Messages.get().container(Messages.ERR_WRITE_PROP_2, property.getName(), context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Writes a list of properties for a specified resource.<p> * * Code calling this method has to ensure that the no properties * <code>a, b</code> are contained in the specified list so that <code>a.equals(b)</code>, * otherwise an exception is thrown.<p> * * @param context the current request context * @param resource the resource to write the properties for * @param properties the list of properties to write * * @throws CmsException if something goes wrong * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required) * * @see CmsObject#writePropertyObjects(String, List) * @see org.opencms.file.types.I_CmsResourceType#writePropertyObjects(CmsObject, CmsSecurityManager, CmsResource, List) */ public void writePropertyObjects(CmsRequestContext context, CmsResource resource, List<CmsProperty> properties) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions( dbc, resource, CmsPermissionSet.ACCESS_WRITE, LockCheck.shallowOnly, CmsResourceFilter.IGNORE_EXPIRATION); // write the properties m_driverManager.writePropertyObjects(dbc, resource, properties, true); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_PROPS_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Writes a resource to the OpenCms VFS.<p> * * @param context the current request context * @param resource the resource to write * * @throws CmsSecurityException if the user has insufficient permission for the given resource ({@link CmsPermissionSet#ACCESS_WRITE} required) * @throws CmsException if something goes wrong */ public void writeResource(CmsRequestContext context, CmsResource resource) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.writeResource(dbc, resource); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Writes the 'projectlastmodified' field of a resource record.<p> * * @param context the current database context * @param resource the resource which should be modified * @param project the project whose project id should be written into the resource record * * @throws CmsException if something goes wrong */ public void writeResourceProjectLastModified(CmsRequestContext context, CmsResource resource, CmsProject project) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.writeProjectLastModified(dbc, resource, project.getUuid()); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_RESOURCE_1, context.getSitePath(resource)), e); } finally { dbc.clear(); } } /** * Inserts an entry in the published resource table.<p> * * This is done during static export.<p> * * @param context the current request context * @param resourceName The name of the resource to be added to the static export * @param linkType the type of resource exported (0= non-parameter, 1=parameter) * @param linkParameter the parameters added to the resource * @param timestamp a time stamp for writing the data into the db * * @throws CmsException if something goes wrong */ public void writeStaticExportPublishedResource( CmsRequestContext context, String resourceName, int linkType, String linkParameter, long timestamp) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { m_driverManager.writeStaticExportPublishedResource(dbc, resourceName, linkType, linkParameter, timestamp); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_WRITE_STATEXP_PUBLISHED_RESOURCES_3, resourceName, linkParameter, new Date(timestamp)), e); } finally { dbc.clear(); } } /** * Writes a new URL name mapping for a given resource.<p> * * The first name from the given sequence which is not already mapped to another resource will be used for * the URL name mapping.<p> * * @param context the request context * @param nameSeq the sequence of URL name candidates * @param structureId the structure id which should be mapped to the name * @param locale the locale for the mapping * @param replaceOnPublish mappings for which this is set will replace all other mappings for the same resource on publishing * * @return the name which was actually mapped to the structure id * * @throws CmsException if something goes wrong */ public String writeUrlNameMapping( CmsRequestContext context, Iterator<String> nameSeq, CmsUUID structureId, String locale, boolean replaceOnPublish) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { return m_driverManager.writeUrlNameMapping(dbc, nameSeq, structureId, locale, replaceOnPublish); } catch (Exception e) { CmsMessageContainer message = Messages.get().container( Messages.ERR_ADD_URLNAME_MAPPING_2, nameSeq.toString(), structureId.toString()); dbc.report(null, message, e); return null; } finally { dbc.clear(); } } /** * Updates the user information. <p> * * The user id has to be a valid OpenCms user id.<br> * * The user with the given id will be completely overridden * by the given data.<p> * * @param context the current request context * @param user the user to be updated * * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#ACCOUNT_MANAGER} for the current project * @throws CmsException if operation was not successful */ public void writeUser(CmsRequestContext context, CmsUser user) throws CmsException, CmsRoleViolationException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsRole role = CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(user.getName())); checkRoleForUserModification(dbc, user.getName(), role); m_driverManager.writeUser(dbc, user); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_WRITE_USER_1, user.getName()), e); } finally { dbc.clear(); } } /** * Performs a blocking permission check on a resource.<p> * * If the required permissions are not satisfied by the permissions the user has on the resource, * an exception is thrown.<p> * * @param dbc the current database context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required to access the resource * @param checkLock if true, the lock status of the resource is also checked * @param filter the filter for the resource * * @throws CmsException in case of any i/o error * @throws CmsSecurityException if the required permissions are not satisfied * * @see #hasPermissions(CmsRequestContext, CmsResource, CmsPermissionSet, boolean, CmsResourceFilter) */ protected void checkPermissions( CmsDbContext dbc, CmsResource resource, CmsPermissionSet requiredPermissions, boolean checkLock, CmsResourceFilter filter) throws CmsException, CmsSecurityException { // get the permissions I_CmsPermissionHandler.CmsPermissionCheckResult permissions = hasPermissions( dbc, resource, requiredPermissions, checkLock ? LockCheck.yes : LockCheck.no, filter); if (!permissions.isAllowed()) { checkPermissions(dbc.getRequestContext(), resource, requiredPermissions, permissions); } } /** * Performs a blocking permission check on a resource.<p> * * If the required permissions are not satisfied by the permissions the user has on the resource, * an exception is thrown.<p> * * @param dbc the current database context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required to access the resource * @param checkLock if true, the lock status of the resource is also checked * @param filter the filter for the resource * * @throws CmsException in case of any i/o error * @throws CmsSecurityException if the required permissions are not satisfied * * @see #hasPermissions(CmsRequestContext, CmsResource, CmsPermissionSet, boolean, CmsResourceFilter) */ protected void checkPermissions( CmsDbContext dbc, CmsResource resource, CmsPermissionSet requiredPermissions, LockCheck checkLock, CmsResourceFilter filter) throws CmsException, CmsSecurityException { // get the permissions I_CmsPermissionHandler.CmsPermissionCheckResult permissions = hasPermissions( dbc, resource, requiredPermissions, checkLock, filter); if (!permissions.isAllowed()) { checkPermissions(dbc.getRequestContext(), resource, requiredPermissions, permissions); } } /** * Applies the permission check result of a previous call * to {@link #hasPermissions(CmsRequestContext, CmsResource, CmsPermissionSet, boolean, CmsResourceFilter)}.<p> * * @param context the current request context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required to access the resource * @param permissions the permissions to check * * @throws CmsSecurityException if the required permissions are not satisfied * @throws CmsLockException if the lock status is not as required * @throws CmsVfsResourceNotFoundException if the required resource has been filtered */ protected void checkPermissions( CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions, I_CmsPermissionHandler.CmsPermissionCheckResult permissions) throws CmsSecurityException, CmsLockException, CmsVfsResourceNotFoundException { if (permissions == I_CmsPermissionHandler.PERM_FILTERED) { throw new CmsVfsResourceNotFoundException( Messages.get().container(Messages.ERR_PERM_FILTERED_1, context.getSitePath(resource))); } if (permissions == I_CmsPermissionHandler.PERM_DENIED) { throw new CmsPermissionViolationException( Messages.get().container( Messages.ERR_PERM_DENIED_2, context.getSitePath(resource), requiredPermissions.getPermissionString())); } if (permissions == I_CmsPermissionHandler.PERM_NOTLOCKED) { throw new CmsLockException( Messages.get().container( Messages.ERR_PERM_NOTLOCKED_2, context.getSitePath(resource), context.getCurrentUser().getName())); } } /** * Checks that the current user has enough permissions to modify the given user.<p> * * @param dbc the database context * @param username the name of the user to modify * @param role the needed role * * @throws CmsDataAccessException if something goes wrong accessing the database * @throws CmsRoleViolationException if the user has not the needed permissions */ protected void checkRoleForUserModification(CmsDbContext dbc, String username, CmsRole role) throws CmsDataAccessException, CmsRoleViolationException { CmsUser userToModify = m_driverManager.readUser(dbc, CmsOrganizationalUnit.removeLeadingSeparator(username)); if (dbc.currentUser().equals(userToModify)) { // a user is allowed to write his own data return; } if (hasRole(dbc, dbc.currentUser(), CmsRole.ROOT_ADMIN)) { // a user with the ROOT_ADMIN role may change any other user return; } if (hasRole(dbc, userToModify, CmsRole.ADMINISTRATOR)) { // check the user that is going to do the modification is administrator checkRole(dbc, CmsRole.ADMINISTRATOR); } else { // check the user that is going to do the modification has the given role checkRole(dbc, role); } } /** * Checks if the given resource contains a resource that has a system lock.<p> * * @param dbc the current database context * @param resource the resource to check * * @throws CmsException in case there is a system lock contained in the given resource */ protected void checkSystemLocks(CmsDbContext dbc, CmsResource resource) throws CmsException { if (m_lockManager.hasSystemLocks(dbc, resource)) { throw new CmsLockException( Messages.get().container( Messages.ERR_RESOURCE_SYSTEM_LOCKED_1, dbc.removeSiteRoot(resource.getRootPath()))); } } /** * Internal recursive method for deleting a resource.<p> * * @param dbc the db context * @param resource the name of the resource to delete (full path) * @param siblingMode indicates how to handle siblings of the deleted resource * * @throws CmsException if something goes wrong */ protected void deleteResource(CmsDbContext dbc, CmsResource resource, CmsResource.CmsResourceDeleteMode siblingMode) throws CmsException { if (resource.isFolder()) { // collect all resources in the folder (but exclude deleted ones) List<CmsResource> resources = m_driverManager.readChildResources( dbc, resource, CmsResourceFilter.IGNORE_EXPIRATION, true, true, false); Set<CmsUUID> deletedResources = new HashSet<CmsUUID>(); // now walk through all sub-resources in the folder for (int i = 0; i < resources.size(); i++) { CmsResource childResource = resources.get(i); if ((siblingMode == CmsResource.DELETE_REMOVE_SIBLINGS) && deletedResources.contains(childResource.getResourceId())) { // sibling mode is "delete all siblings" and another sibling of the current child resource has already // been deleted- do nothing and continue with the next child resource. continue; } if (childResource.isFolder()) { // recurse into this method for subfolders deleteResource(dbc, childResource, siblingMode); } else { // handle child resources m_driverManager.deleteResource(dbc, childResource, siblingMode); } deletedResources.add(childResource.getResourceId()); } deletedResources.clear(); } // handle the resource itself m_driverManager.deleteResource(dbc, resource, siblingMode); } /** * Deletes a user, where all permissions and resources attributes of the user * were transfered to a replacement user, if given.<p> * * @param context the current request context * @param user the user to be deleted * @param replacement the user to be transfered, can be <code>null</code> * * @throws CmsRoleViolationException if the current user does not own the rule {@link CmsRole#ACCOUNT_MANAGER} * @throws CmsSecurityException in case the user is a default user * @throws CmsException if something goes wrong */ protected void deleteUser(CmsRequestContext context, CmsUser user, CmsUser replacement) throws CmsException, CmsSecurityException, CmsRoleViolationException { if (OpenCms.getDefaultUsers().isDefaultUser(user.getName())) { throw new CmsSecurityException( org.opencms.security.Messages.get().container( org.opencms.security.Messages.ERR_CANT_DELETE_DEFAULT_USER_1, user.getName())); } if (context.getCurrentUser().equals(user)) { throw new CmsSecurityException(Messages.get().container(Messages.ERR_USER_CANT_DELETE_ITSELF_USER_0)); } CmsDbContext dbc = null; try { dbc = getDbContextForDeletePrincipal(context); CmsRole role = CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(user.getName())); checkRoleForUserModification(dbc, user.getName(), role); m_driverManager.deleteUser( dbc, dbc.getRequestContext().getCurrentProject(), user.getName(), null == replacement ? null : replacement.getName()); } catch (Exception e) { CmsDbContext dbcForException = m_dbContextFactory.getDbContext(context); dbcForException.report(null, Messages.get().container(Messages.ERR_DELETE_USER_1, user.getName()), e); dbcForException.clear(); } finally { if (null != dbc) { dbc.clear(); } } } /** * Returns all resources of organizational units for which the current user has * the given role role.<p> * * @param dbc the current database context * @param role the role to check * * @return a list of {@link org.opencms.file.CmsResource} objects * * @throws CmsException if something goes wrong */ protected List<CmsResource> getManageableResources(CmsDbContext dbc, CmsRole role) throws CmsException { CmsOrganizationalUnit ou = m_driverManager.readOrganizationalUnit(dbc, role.getOuFqn()); if (hasRole(dbc, dbc.currentUser(), role)) { return m_driverManager.getResourcesForOrganizationalUnit(dbc, ou); } List<CmsResource> resources = new ArrayList<CmsResource>(); Iterator<CmsOrganizationalUnit> it = m_driverManager.getOrganizationalUnits(dbc, ou, false).iterator(); while (it.hasNext()) { CmsOrganizationalUnit orgUnit = it.next(); resources.addAll(getManageableResources(dbc, role.forOrgUnit(orgUnit.getName()))); } return resources; } /** * Returns the organizational unit for the parent of the given fully qualified name.<p> * * @param fqn the fully qualified name to get the parent organizational unit for * * @return the parent organizational unit for the fully qualified name */ protected String getParentOrganizationalUnit(String fqn) { String ouFqn = CmsOrganizationalUnit.getParentFqn(CmsOrganizationalUnit.removeLeadingSeparator(fqn)); if (ouFqn == null) { ouFqn = ""; } return ouFqn; } /** * Performs a non-blocking permission check on a resource.<p> * * This test will not throw an exception in case the required permissions are not * available for the requested operation. Instead, it will return one of the * following values:<ul> * <li><code>{@link I_CmsPermissionHandler#PERM_ALLOWED}</code></li> * <li><code>{@link I_CmsPermissionHandler#PERM_FILTERED}</code></li> * <li><code>{@link I_CmsPermissionHandler#PERM_DENIED}</code></li></ul><p> * * @param dbc the current database context * @param resource the resource on which permissions are required * @param requiredPermissions the set of permissions required for the operation * @param checkLock if true, a lock for the current user is required for * all write operations, if false it's ok to write as long as the resource * is not locked by another user * @param filter the resource filter to use * * @return <code>{@link I_CmsPermissionHandler#PERM_ALLOWED}</code> if the user has sufficient permissions on the resource * for the requested operation * * @throws CmsException in case of i/o errors (NOT because of insufficient permissions) */ protected I_CmsPermissionHandler.CmsPermissionCheckResult hasPermissions( CmsDbContext dbc, CmsResource resource, CmsPermissionSet requiredPermissions, LockCheck checkLock, CmsResourceFilter filter) throws CmsException { return m_permissionHandler.hasPermissions(dbc, resource, requiredPermissions, checkLock, filter); } /** * Returns <code>true</code> if at least one of the given group names is equal to a group name * of the given role in the given organizational unit.<p> * * This checks the given list against the group of the given role as well as against the role group * of all parent roles.<p> * * If the organizational unit is <code>null</code>, this method will check if the * given user has the given role for at least one organizational unit.<p> * * @param role the role to check * @param roles the groups to match the role groups against * * @return <code>true</code> if at last one of the given group names is equal to a group name * of this role */ protected boolean hasRole(CmsRole role, List<CmsGroup> roles) { // iterates the role groups the user is in for (CmsGroup group : roles) { String groupName = group.getName(); // iterate the role hierarchy for (String distictGroupName : role.getDistinctGroupNames()) { if (distictGroupName.startsWith(CmsOrganizationalUnit.SEPARATOR)) { // this is a ou independent role // we need an exact match, and we ignore the ou parameter if (groupName.equals(distictGroupName.substring(1))) { return true; } } else { // first check if the user has the role at all if (groupName.endsWith(CmsOrganizationalUnit.SEPARATOR + distictGroupName) || groupName.equals(distictGroupName)) { // this is a ou dependent role if (role.getOuFqn() == null) { // ou parameter is null, so the user needs to have the role in at least one ou does not matter which return true; } else { // the user needs to have the role in the given ou or in a parent ou // now check that the ou matches String groupFqn = CmsOrganizationalUnit.getParentFqn(groupName); if (role.getOuFqn().startsWith(groupFqn)) { return true; } } } } } } return false; } /** * Internal recursive method to move a resource.<p> * * @param dbc the db context * @param source the source resource * @param destination the destination path * @param allMovedResources a set used to collect all moved resources * * @throws CmsException if something goes wrong */ protected void moveResource( CmsDbContext dbc, CmsResource source, String destination, Set<CmsResource> allMovedResources) throws CmsException { List<CmsResource> resources = null; if (source.isFolder()) { if (!CmsResource.isFolder(destination)) { // ensure folder name end's with a / destination = destination.concat("/"); } // collect all resources in the folder without checking permissions resources = m_driverManager.readChildResources(dbc, source, CmsResourceFilter.ALL, true, true, false); } // target permissions will be checked later m_driverManager.moveResource(dbc, source, destination, false); // make sure lock is set CmsResource destinationResource = m_driverManager.readResource(dbc, destination, CmsResourceFilter.ALL); try { // the destination must always get a new lock m_driverManager.lockResource(dbc, destinationResource, CmsLockType.EXCLUSIVE); } catch (Exception e) { // could happen with with shared locks on single files if (LOG.isWarnEnabled()) { LOG.warn(e.getLocalizedMessage(), e); } } if (resources != null) { // Ensure consistent order that is not database-dependent, since readChildResources doesn't specify an ordering. // this is necessary to make test cases more useful. Collections.sort(resources, (r1, r2) -> r1.getRootPath().compareTo(r2.getRootPath())); // now walk through all sub-resources in the folder for (int i = 0; i < resources.size(); i++) { CmsResource childResource = resources.get(i); String childDestination = destination.concat(childResource.getName()); // recurse with child resource moveResource(dbc, childResource, childDestination, allMovedResources); } } List<CmsResource> movedResources = m_driverManager.readChildResources( dbc, destinationResource, CmsResourceFilter.ALL, true, true, false); allMovedResources.add(destinationResource); allMovedResources.addAll(movedResources); } /** * Reads a folder from the VFS, using the specified resource filter.<p> * * @param dbc the current database context * @param resourcename the name of the folder to read (full path) * @param filter the resource filter to use while reading * * @return the folder that was read * * @throws CmsException if something goes wrong */ protected CmsFolder readFolder(CmsDbContext dbc, String resourcename, CmsResourceFilter filter) throws CmsException { CmsResource resource = readResource(dbc, resourcename, filter); return m_driverManager.convertResourceToFolder(resource); } /** * Reads a resource from the OpenCms VFS, using the specified resource filter.<p> * * @param dbc the current database context * @param structureID the ID of the structure to read * @param filter the resource filter to use while reading * * @return the resource that was read * * @throws CmsException if something goes wrong * * @see CmsObject#readResource(CmsUUID, CmsResourceFilter) * @see CmsObject#readResource(CmsUUID) * @see CmsObject#readFile(CmsResource) */ protected CmsResource readResource(CmsDbContext dbc, CmsUUID structureID, CmsResourceFilter filter) throws CmsException { // read the resource from the VFS CmsResource resource = m_driverManager.readResource(dbc, structureID, filter); // check if the user has read access to the resource checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_READ, true, filter); // access was granted - return the resource return resource; } /** * Reads a resource from the OpenCms VFS, using the specified resource filter.<p> * * @param dbc the current database context * @param resourcePath the name of the resource to read (full path) * @param filter the resource filter to use while reading * * @return the resource that was read * * @throws CmsException if something goes wrong * * @see CmsObject#readResource(String, CmsResourceFilter) * @see CmsObject#readResource(String) * @see CmsObject#readFile(CmsResource) */ protected CmsResource readResource(CmsDbContext dbc, String resourcePath, CmsResourceFilter filter) throws CmsException { // read the resource from the VFS CmsResource resource = m_driverManager.readResource(dbc, resourcePath, filter); // check if the user has read access to the resource checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_READ, true, filter); // access was granted - return the resource return resource; } /** * Determines a project where the deletion of a principal can be executed and sets it in the returned db context.<p> * * @param context the current request context * * @return the db context to use when deleting the principal. * * @throws CmsDataAccessException if determining a project that is suitable to delete the prinicipal fails. */ private CmsDbContext getDbContextForDeletePrincipal(CmsRequestContext context) throws CmsDataAccessException { CmsProject currentProject = context.getCurrentProject(); CmsDbContext dbc = m_dbContextFactory.getDbContext(context); CmsUUID projectId = dbc.getProjectId(); // principal modifications are allowed if the current project is not the online project if (currentProject.isOnlineProject()) { // this is needed because // I_CmsUserDriver#removeAccessControlEntriesForPrincipal(CmsDbContext, CmsProject, CmsProject, CmsUUID) // expects an offline project, if not, data will become inconsistent // if the current project is the online project, check if there is a valid offline project at all List<CmsProject> projects = m_driverManager.getProjectDriver(dbc).readProjects(dbc, ""); for (CmsProject project : projects) { if (!project.isOnlineProject()) { try { dbc.setProjectId(project.getUuid()); if (null != m_driverManager.readResource(dbc, "/", CmsResourceFilter.ALL)) { // shallow clone the context with project adjusted context = new CmsRequestContext( context.getCurrentUser(), project, context.getUri(), context.getRequestMatcher(), context.getSiteRoot(), context.isSecureRequest(), context.getLocale(), context.getEncoding(), context.getRemoteAddress(), context.getRequestTime(), context.getDirectoryTranslator(), context.getFileTranslator(), context.getOuFqn(), context.isForceAbsoluteLinks()); dbc = m_dbContextFactory.getDbContext(context); projectId = dbc.getProjectId(); break; } } catch (Exception e) { // ignore } } } } dbc.setProjectId(projectId); return dbc; } }
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
Java
lgpl-2.1
301,511
/* * eXist Open Source Native XML Database * Copyright (C) 2000-04, Wolfgang M. Meier (wolfgang@exist-db.org) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * $Id$ */ package org.exist.xmldb.concurrent; import java.io.IOException; import java.util.*; import java.util.concurrent.*; import org.exist.test.ExistXmldbEmbeddedServer; import org.exist.xmldb.concurrent.action.Action; import org.exist.xmldb.IndexQueryService; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.xmldb.api.base.Collection; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.CollectionManagementService; import static org.junit.Assert.*; /** * Abstract base class for concurrent tests. * * @author wolf * @author aretter */ public abstract class ConcurrentTestBase { private static String COLLECTION_CONFIG = "<collection xmlns=\"http://exist-db.org/collection-config/1.0\">" + " <index>" + " <lucene>" + " <text match=\"/*\"/>" + " </lucene>" + " </index>" + "</collection>"; protected Collection testCol; @ClassRule public static final ExistXmldbEmbeddedServer existXmldbEmbeddedServer = new ExistXmldbEmbeddedServer(false, true, true); @Before public final void startupDb() throws Exception { final Collection rootCol = existXmldbEmbeddedServer.getRoot(); assertNotNull(rootCol); final IndexQueryService idxConf = (IndexQueryService) rootCol.getService("IndexQueryService", "1.0"); idxConf.configureCollection(COLLECTION_CONFIG); testCol = rootCol.getChildCollection(getTestCollectionName()); if (testCol != null) { CollectionManagementService mgr = DBUtils.getCollectionManagementService(rootCol); mgr.removeCollection(getTestCollectionName()); } testCol = DBUtils.addCollection(rootCol, getTestCollectionName()); assertNotNull(testCol); } @After public final void tearDownDb() throws XMLDBException { final Collection rootCol = existXmldbEmbeddedServer.getRoot(); DBUtils.removeCollection(rootCol, getTestCollectionName()); testCol = null; } /** * Get the name of the test collection. * * @return the name of the test collection. */ public abstract String getTestCollectionName(); /** * Get the runners for the test * * @return the runners for the test. */ public abstract List<Runner> getRunners(); public Collection getTestCollection() { return testCol; } @Test public void concurrent() throws Exception { // make a copy of the actions final List<Runner> runners = Collections.unmodifiableList(getRunners()); // start all threads final ExecutorService executorService = Executors.newFixedThreadPool(runners.size()); final List<Future<Boolean>> futures = new ArrayList<>(); for (final Runner runner : runners) { futures.add(executorService.submit(runner)); } // await first error, or all results boolean failed = false; Exception failedException = null; while (true) { if (futures.isEmpty()) { break; } Future<Boolean> completedFuture = null; for (final Future<Boolean> future : futures) { if (future.isDone()) { completedFuture = future; break; // exit for-loop } } if (completedFuture != null) { // remove the completed future from the list of futures futures.remove(completedFuture); try { final boolean success = completedFuture.get(); if (!success) { failed = true; break; // exit while-loop } } catch (final InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { // Restore the interrupted status Thread.currentThread().interrupt(); } failed = true; failedException = e; break; // exit while-loop } } else { // sleep, repeat... try { Thread.sleep(50); } catch (final InterruptedException e) { failed = true; failedException = e; break; // exit while-loop } } } // repeat while-loop if (failed) { executorService.shutdownNow(); if (failedException != null) { throw failedException; } else { assertFalse(failed); } } assertAdditional(); } /** * Override this if you need to make * additional assertions after the {@link #concurrent()} * test has completed. */ protected void assertAdditional() throws XMLDBException { // no-op } /** * Runs the specified Action a number of times. * * @author wolf */ class Runner implements Callable<Boolean> { private final Action action; private final int repeat; private final long delayBeforeStart; private final long delay; public Runner(final Action action, final int repeat, final long delayBeforeStart, final long delay) { super(); this.action = action; this.repeat = repeat; this.delayBeforeStart = delayBeforeStart; this.delay = delay; } /** * Returns true if execution completes. * * @return true if execution completes, false otherwise */ @Override public Boolean call() throws XMLDBException, IOException { if (delayBeforeStart > 0) { if (!sleep(delayBeforeStart)) { return false; } } for (int i = 0; i < repeat; i++) { if (!action.execute()) { return false; } if (delay > 0) { if (!sleep(delay)) { return false; } } } return true; } /** * Sleeps the current thread for a period of time. * * @param period the period to sleep for. * * @return true if the thread slept for the period and was not interrupted */ private boolean sleep(final long period) { try { Thread.sleep(period); return true; } catch (final InterruptedException e) { // Restore the interrupted status Thread.currentThread().interrupt(); return false; } } } }
windauer/exist
exist-core/src/test/java/org/exist/xmldb/concurrent/ConcurrentTestBase.java
Java
lgpl-2.1
7,921
/* Copyright 2005 - 2006 Roman Plasil http://foo-title.sourceforge.net This file is part of foo_title. foo_title is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. foo_title is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with foo_title; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "stdafx.h" #include "mainMenuCommands.h" #include "ManagedWrapper.h" namespace fooManagedWrapper { CMainMenuCommandsImpl::CMainMenuCommandsImpl(List<CCommand ^> ^_cmds) { commonInit(); cmds = _cmds; }; CMainMenuCommandsImpl::CMainMenuCommandsImpl() { commonInit(); } void CMainMenuCommandsImpl::commonInit() { cmds = gcnew List<CCommand ^>(); CManagedWrapper::GetInstance()->AddService(this); wrapper = new CMainMenuCommandsFactoryWrapper(); wrapper->mainMenuCommands.get_static_instance().SetImplementation(this); } CMainMenuCommandsImpl::!CMainMenuCommandsImpl() { this->~CMainMenuCommandsImpl(); } CMainMenuCommandsImpl::~CMainMenuCommandsImpl() { delete wrapper; } unsigned int CMainMenuCommandsImpl::CommandsCount::get() { return cmds->Count; } Guid CMainMenuCommandsImpl::GetGuid(unsigned int index) { return cmds[index]->GetGuid(); } String ^CMainMenuCommandsImpl::GetName(unsigned int index) { return cmds[index]->GetName(); } bool CMainMenuCommandsImpl::GetDescription(unsigned int index, String ^ %desc) { return cmds[index]->GetDescription(desc); } void CMainMenuCommandsImpl::Execute(unsigned int index) { return cmds[index]->Execute(); } bool CMainMenuCommandsImpl::GetDisplay(unsigned int index, String ^ %text, unsigned int %flags) { return cmds[index]->GetDisplay(text, flags); } void CCustomMainMenuCommands::SetImplementation(gcroot<CMainMenuCommandsImpl ^> impl) { managedMainMenuCommands = impl; } t_uint32 CCustomMainMenuCommands::get_command_count() { return managedMainMenuCommands->CommandsCount; } GUID CCustomMainMenuCommands::get_command(t_uint32 p_index) { return CManagedWrapper::ToGUID(managedMainMenuCommands->GetGuid(p_index)); } void CCustomMainMenuCommands::get_name(t_uint32 p_index, pfc::string_base & p_out) { p_out = CManagedWrapper::StringToPfcString(managedMainMenuCommands->GetName(p_index)); } bool CCustomMainMenuCommands::get_description(t_uint32 p_index, pfc::string_base &p_out) { String ^str; bool res = managedMainMenuCommands->GetDescription(p_index, str); p_out = CManagedWrapper::StringToPfcString(str); return res; } GUID CCustomMainMenuCommands::get_parent() { return CManagedWrapper::ToGUID(managedMainMenuCommands->Parent); } void CCustomMainMenuCommands::execute(t_uint32 p_index, service_ptr_t<service_base> p_callback) { managedMainMenuCommands->Execute(p_index); } unsigned int CCustomMainMenuCommands::get_sort_priority() { return managedMainMenuCommands->SortPriority; } bool CCustomMainMenuCommands::get_display(t_uint32 p_index,pfc::string_base & p_text,t_uint32 & p_flags) { String ^str; bool res = managedMainMenuCommands->GetDisplay(p_index, str, p_flags); p_text = CManagedWrapper::StringToPfcString(str); return res; } CMainMenuCommands::CMainMenuCommands(const service_ptr_t<mainmenu_commands> &_ptr) { this->ptr = new service_ptr_t<mainmenu_commands>(_ptr); } CMainMenuCommands::~CMainMenuCommands() { FT_NULL_DELETE(ptr); } String ^CMainMenuCommands::GetName(unsigned int index) { pfc::string8 pfcName; (*ptr)->get_name(index, pfcName); return CManagedWrapper::PfcStringToString(pfcName); } Guid CMainMenuCommands::Parent::get() { return safe_cast<Guid>(CManagedWrapper::FromGUID((*ptr)->get_parent())); } Guid ^CMainMenuCommands::GetCommand(unsigned int index) { return CManagedWrapper::FromGUID((*ptr)->get_command(index)); } void CMainMenuCommands::Execute(unsigned int index) { (*ptr)->execute(index, NULL); } };
TheQwertiest/foo_title
foo_title/fooManagedWrapper/mainMenuCommands.cpp
C++
lgpl-2.1
4,558
/****************************************************************************** * * Copyright (C) 2007 Peter G. Vavaroutsos <pete AT vavaroutsos DOT com> * * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2.1 of the GNU General * Public License as published by the Free Software Foundation. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA * * THE AUTHORS OF THIS LIBRARY ACCEPT ABSOLUTELY NO LIABILITY FOR * ANY HARM OR LOSS RESULTING FROM ITS USE. IT IS _EXTREMELY_ UNWISE * TO RELY ON SOFTWARE ALONE FOR SAFETY. Any machinery capable of * harming persons must have provisions for completely removing power * from all motors, etc, before persons enter any danger area. All * machinery must be designed to comply with local and national safety * codes, and the authors of this software can not, and do not, take * any responsibility for such compliance. * * This code was written as part of the EMC project. For more * information, go to www.linuxcnc.org. * ******************************************************************************/ #include <math.h> // M_PI. #include "emcIniFile.hh" IniFile::StrIntPair EmcIniFile::axisTypeMap[] = { {"LINEAR", EMC_AXIS_LINEAR}, {"ANGULAR", EMC_AXIS_ANGULAR}, { NULL, 0 }, }; EmcIniFile::ErrorCode EmcIniFile::Find(EmcAxisType *result, const char *tag, const char *section, int num) { return(IniFile::Find((int *)result, axisTypeMap, tag, section, num)); } IniFile::StrIntPair EmcIniFile::jointTypeMap[] = { {"LINEAR", EMC_LINEAR}, {"ANGULAR", EMC_ANGULAR}, { NULL, 0 }, }; EmcIniFile::ErrorCode EmcIniFile::Find(EmcJointType *result, const char *tag, const char *section, int num) { return(IniFile::Find((int *)result, jointTypeMap, tag, section, num)); } IniFile::StrIntPair EmcIniFile::boolMap[] = { {"TRUE", 1}, {"YES", 1}, {"1", 1}, {"FALSE", 0}, {"NO", 0}, {"0", 0}, { NULL, 0 }, }; EmcIniFile::ErrorCode EmcIniFile::Find(bool *result, const char *tag, const char *section, int num) { ErrorCode errCode; int value; if((errCode = IniFile::Find(&value, boolMap, tag,section,num)) == ERR_NONE){ *result = (bool)value; } return(errCode); } // The next const struct holds pairs for linear units which are // valid under the [TRAJ] section. These are of the form {"name", value}. // If the name "name" is encountered in the ini, the value will be used. EmcIniFile::StrDoublePair EmcIniFile::linearUnitsMap[] = { { "mm", 1.0 }, { "metric", 1.0 }, { "in", 1/25.4 }, { "inch", 1/25.4 }, { "imperial", 1/25.4 }, { NULL, 0 }, }; EmcIniFile::ErrorCode EmcIniFile::FindLinearUnits(EmcLinearUnits *result, const char *tag, const char *section, int num) { return(IniFile::Find((double *)result, linearUnitsMap, tag, section, num)); } // The next const struct holds pairs for angular units which are // valid under the [TRAJ] section. These are of the form {"name", value}. // If the name "name" is encountered in the ini, the value will be used. EmcIniFile::StrDoublePair EmcIniFile::angularUnitsMap[] = { { "deg", 1.0 }, { "degree", 1.0 }, { "grad", 0.9 }, { "gon", 0.9 }, { "rad", M_PI / 180 }, { "radian", M_PI / 180 }, { NULL, 0 }, }; EmcIniFile::ErrorCode EmcIniFile::FindAngularUnits(EmcAngularUnits *result, const char *tag, const char *section, int num) { return(IniFile::Find((double *)result, angularUnitsMap, tag, section, num)); }
araisrobo/linuxcnc
src/emc/ini/emcIniFile.cc
C++
lgpl-2.1
4,149
/**************************************************************************** ** Meta object code from reading C++ file 'qscriptenginedebugger.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../debugging/qscriptenginedebugger.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'qscriptenginedebugger.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.6. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_QScriptEngineDebugger[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 2, // signalCount // signals: signature, parameters, type, tag, flags 23, 22, 22, 22, 0x05, 45, 22, 22, 22, 0x05, // slots: signature, parameters, type, tag, flags 65, 22, 22, 22, 0x08, 0 // eod }; static const char qt_meta_stringdata_QScriptEngineDebugger[] = { "QScriptEngineDebugger\0\0evaluationSuspended()\0" "evaluationResumed()\0_q_showStandardWindow()\0" }; void QScriptEngineDebugger::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); QScriptEngineDebugger *_t = static_cast<QScriptEngineDebugger *>(_o); switch (_id) { case 0: _t->evaluationSuspended(); break; case 1: _t->evaluationResumed(); break; case 2: _t->d_func()->_q_showStandardWindow(); break; default: ; } } Q_UNUSED(_a); } const QMetaObjectExtraData QScriptEngineDebugger::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject QScriptEngineDebugger::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_QScriptEngineDebugger, qt_meta_data_QScriptEngineDebugger, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &QScriptEngineDebugger::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *QScriptEngineDebugger::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *QScriptEngineDebugger::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_QScriptEngineDebugger)) return static_cast<void*>(const_cast< QScriptEngineDebugger*>(this)); return QObject::qt_metacast(_clname); } int QScriptEngineDebugger::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 3) qt_static_metacall(this, _c, _id, _a); _id -= 3; } return _id; } // SIGNAL 0 void QScriptEngineDebugger::evaluationSuspended() { QMetaObject::activate(this, &staticMetaObject, 0, 0); } // SIGNAL 1 void QScriptEngineDebugger::evaluationResumed() { QMetaObject::activate(this, &staticMetaObject, 1, 0); } QT_END_MOC_NAMESPACE
nonrational/qt-everywhere-opensource-src-4.8.6
src/scripttools/.moc/release-shared/moc_qscriptenginedebugger.cpp
C++
lgpl-2.1
3,527
package com.cherokeelessons.dict.ui; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.logging.Logger; import org.fusesource.restygwt.client.Method; import org.fusesource.restygwt.client.MethodCallback; import org.gwtbootstrap3.client.ui.Button; import org.gwtbootstrap3.client.ui.FormGroup; import org.gwtbootstrap3.client.ui.FormLabel; import org.gwtbootstrap3.client.ui.Heading; import org.gwtbootstrap3.client.ui.Label; import org.gwtbootstrap3.client.ui.Panel; import org.gwtbootstrap3.client.ui.PanelBody; import org.gwtbootstrap3.client.ui.PanelFooter; import org.gwtbootstrap3.client.ui.PanelHeader; import org.gwtbootstrap3.client.ui.TextArea; import org.gwtbootstrap3.client.ui.constants.HeadingSize; import org.gwtbootstrap3.client.ui.constants.LabelType; import org.gwtbootstrap3.client.ui.constants.PanelType; import org.gwtbootstrap3.client.ui.gwt.HTMLPanel; import com.cherokeelessons.dict.client.ConsoleLogHandler2; import com.cherokeelessons.dict.client.DictEntryPoint; import com.cherokeelessons.dict.client.DictionaryApplication; import com.cherokeelessons.dict.events.AddAnalysisPanelEvent; import com.cherokeelessons.dict.events.AddSearchResultPanelEvent; import com.cherokeelessons.dict.events.AnalysisCompleteEvent; import com.cherokeelessons.dict.events.AnalyzeEvent; import com.cherokeelessons.dict.events.ClearResultsEvent; import com.cherokeelessons.dict.events.EnableSearchEvent; import com.cherokeelessons.dict.events.HistoryTokenEvent; import com.cherokeelessons.dict.events.MessageEvent; import com.cherokeelessons.dict.events.RemovePanelEvent; import com.cherokeelessons.dict.events.ReplaceTextInputEvent; import com.cherokeelessons.dict.events.ResetInputEvent; import com.cherokeelessons.dict.events.SearchResponseEvent; import com.cherokeelessons.dict.events.UiEnableEvent; import com.cherokeelessons.dict.shared.DictEntry; import com.cherokeelessons.dict.shared.FormattedEntry; import com.cherokeelessons.dict.shared.Log; import com.cherokeelessons.dict.shared.SearchResponse; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window.Location; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Widget; import com.google.web.bindery.event.shared.HandlerRegistration; import com.google.web.bindery.event.shared.binder.EventBinder; import com.google.web.bindery.event.shared.binder.EventHandler; import commons.lang3.StringUtils; public class AnalysisView extends Composite { private final Logger logger = Log.getGwtLogger(new ConsoleLogHandler2(), this.getClass().getSimpleName()); protected interface AnalysisViewEventBinder extends EventBinder<AnalysisView> { public final AnalysisViewEventBinder binder_analysisView = GWT .create(AnalysisViewEventBinder.class); }; // @UiField // protected PageHeader pageHeader; @UiField protected FormGroup formGroup; @UiField protected FormLabel formLabel; @UiField protected TextArea textArea; @UiField protected Button btn_analyze; @UiField protected Button btn_search; @UiField protected Button btn_reset; @UiField protected Button btn_clear; @EventHandler public void setText(ReplaceTextInputEvent event) { logger.info(this.getClass().getSimpleName() + "#Event#setText"); textArea.setValue(event.text); } @EventHandler public void enable(UiEnableEvent event) { logger.info(this.getClass().getSimpleName() + "#Event#enable"); btn_analyze.setEnabled(event.enable); btn_search.setEnabled(event.enable); btn_reset.setEnabled(event.enable); btn_clear.setEnabled(event.enable); textArea.setEnabled(event.enable); if (event.enable) { btn_analyze.state().reset(); btn_search.state().reset(); } } @EventHandler public void onClearResults(ClearResultsEvent event) { logger.info(this.getClass().getSimpleName() + "#Event#onClearResults"); Iterator<Panel> ip = panels.iterator(); while (ip.hasNext()) { Panel next = ip.next(); next.clear(); next.removeFromParent(); ip.remove(); } } @EventHandler public void onCompletion(AnalysisCompleteEvent event) { logger.info(this.getClass().getSimpleName() + "#Event#onCompletion"); DictEntryPoint.eventBus.fireEvent(new UiEnableEvent(true)); } private static MainMenuUiBinder uiBinder = GWT .create(MainMenuUiBinder.class); protected interface MainMenuUiBinder extends UiBinder<Widget, AnalysisView> { } private final RootPanel rp; private KeyPressHandler keypress = new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { if (event.isControlKeyDown() && event.isAltKeyDown() && event.getCharCode() == 's') { DictEntryPoint.eventBus.fireEvent(new EnableSearchEvent(!btn_search .isVisible())); } } }; private HandlerRegistration reg; private String prevTitle; @Override protected void onLoad() { super.onLoad(); reg = AnalysisViewEventBinder.binder_analysisView.bindEventHandlers( this, DictEntryPoint.eventBus); logger.info("onLoad#" + String.valueOf(AnalysisViewEventBinder.binder_analysisView)); prevTitle = Document.get().getTitle(); Document.get().setTitle("ᎤᎪᎵᏰᏗ - ᏣᎳᎩ ᏗᏕᏠᏆᏙᏗ"); } @Override protected void onUnload() { super.onUnload(); reg.removeHandler(); logger.info("onUnload#" + String.valueOf(AnalysisViewEventBinder.binder_analysisView)); Document.get().setTitle(prevTitle); } public AnalysisView(RootPanel rp) { initWidget(uiBinder.createAndBindUi(this)); this.rp = rp; addDomHandler(keypress, KeyPressEvent.getType()); textArea.getElement().getStyle().setProperty("marginLeft", "auto"); textArea.getElement().getStyle().setProperty("marginRight", "auto"); textArea.setHeight("6.7em"); } @UiHandler("btn_reset") public void onResetAll(final ClickEvent event) { DictEntryPoint.eventBus.fireEvent(new ClearResultsEvent()); DictEntryPoint.eventBus.fireEvent(new ResetInputEvent()); String token = StringUtils.substringAfter(Location.getHref(), "#"); token = token.replaceAll("&text=[^&]*", ""); DictEntryPoint.eventBus.fireEvent(new HistoryTokenEvent(token)); } @UiHandler("btn_clear") public void onClearResults(final ClickEvent event) { DictEntryPoint.eventBus.fireEvent(new ClearResultsEvent()); } @EventHandler public void onResetInput(ResetInputEvent event) { logger.info(this.getClass().getSimpleName() + "#Event#resetInput"); textArea.setValue(""); } private final List<Panel> panels = new ArrayList<Panel>(); @UiHandler("btn_analyze") public void onAnalyze(final ClickEvent event) { // this.pageHeader.setVisible(false); formLabel.setVisible(false); btn_analyze.state().loading(); final String value = textArea.getValue(); if (StringUtils.isBlank(value)) { DictEntryPoint.eventBus.fireEvent(new MessageEvent("ERROR", "NOTHING TO ANALYZE.")); btn_analyze.state().reset(); return; } String token = StringUtils.substringAfter(Location.getHref(), "#"); token = token.replaceAll("&text=[^&]*", ""); token = token + "&text=" + value; final String h = token; logger.info("1 fire#history " + h); DictEntryPoint.eventBus.fireEvent(new HistoryTokenEvent(h)); logger.info("2 fire#analyze " + value); DictEntryPoint.eventBus.fireEvent(new AnalyzeEvent(value)); logger.info("3 fire#done"); } @UiHandler("btn_search") public void onSearch(final ClickEvent event) { // this.pageHeader.setVisible(false); this.formLabel.setVisible(false); btn_search.state().loading(); String value = textArea.getValue(); if (StringUtils.isBlank(value)) { DictEntryPoint.eventBus.fireEvent(new MessageEvent("ERROR", "EMPTY SEARCHES ARE NOT ALLOWED.")); btn_search.state().reset(); return; } String token = StringUtils.substringAfter(Location.getHref(), "#"); token = token.replaceAll("&text=[^&]*", ""); token = token + "&text=" + value; DictEntryPoint.eventBus.fireEvent(new HistoryTokenEvent(token)); DictEntryPoint.eventBus.fireEvent(new UiEnableEvent(false)); DictEntryPoint.api.syll(StringUtils.strip(value), display_it); } @EventHandler public void onEnableSearch(EnableSearchEvent event) { logger.info(this.getClass().getSimpleName() + "#Event#enableSearch"); if (event.enable) { btn_search.setVisible(true); } else { btn_search.setVisible(false); } } @EventHandler public void removePanel(RemovePanelEvent event) { logger.info(this.getClass().getSimpleName() + "#Event#removePanel"); Panel p = event.p; p.clear(); p.removeFromParent(); } @EventHandler public void addPanel(AddAnalysisPanelEvent event) { logger.info(this.getClass().getSimpleName() + "#Event#addPanel(analysis)"); rp.add(event.p); panels.add(event.p); } @EventHandler public void addPanel(AddSearchResultPanelEvent event) { logger.info(this.getClass().getSimpleName() + "#Event#addPanel"); rp.add(event.p); panels.add(event.p); } @EventHandler public void process(SearchResponseEvent event) { logger.info(this.getClass().getSimpleName() + "#Event#process"); int dupes = 0; Set<Integer> already = new HashSet<>(); Set<Integer> duplicates = new HashSet<>(); SearchResponse sr = event.response; logger.info("COUNT: " + sr.data.size()); Iterator<DictEntry> isr = sr.data.iterator(); while (isr.hasNext()) { DictEntry entry = isr.next(); if (already.contains(entry.id)) { logger.info("DUPLICATE RECORD IN RESPONSE: " + entry.id); dupes++; duplicates.add(entry.id); isr.remove(); continue; } already.add(entry.id); } for (DictEntry entry : sr.data) { final Panel p = new Panel(PanelType.SUCCESS); Style style = p.getElement().getStyle(); style.setWidth((DictionaryApplication.WIDTH - 20) / 2 - 6, Unit.PX); style.setDisplay(Display.INLINE_BLOCK); style.setMarginRight(5, Unit.PX); style.setVerticalAlign(Style.VerticalAlign.TOP); PanelHeader ph = new PanelHeader(); Heading h = new Heading(HeadingSize.H5); ph.add(h); String hdr = entry.definitiond + "<br/>[" + entry.id + "]"; if (duplicates.contains(entry.id)) { hdr += " (DUPE DETECTED!)"; } h.getElement().setInnerHTML(hdr); h.getElement().getStyle().setDisplay(Display.INLINE_BLOCK); Label source = new Label(LabelType.INFO); ph.add(source); source.getElement().getStyle().setFloat(Style.Float.RIGHT); source.setText("[" + entry.source + "]"); PanelBody pb = new PanelBody(); HTMLPanel hp = new HTMLPanel(new FormattedEntry(entry).getHtml()); Button dismiss = new Button("DISMISS"); dismiss.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { DictEntryPoint.eventBus.fireEvent(new RemovePanelEvent(p)); } }); PanelFooter pf = new PanelFooter(); pf.add(dismiss); p.add(ph); p.add(pb); p.add(pf); pb.add(hp); DictEntryPoint.eventBus.fireEvent(new AddSearchResultPanelEvent(p)); } if (dupes > 0) { DictEntryPoint.eventBus.fireEvent(new MessageEvent("ERROR", dupes + " DUPES IN RESPONSE!")); } DictEntryPoint.eventBus.fireEvent(new UiEnableEvent(true)); } private MethodCallback<SearchResponse> display_it = new MethodCallback<SearchResponse>() { @Override public void onFailure(Method method, Throwable exception) { btn_search.state().reset(); DictEntryPoint.eventBus.fireEvent(new MessageEvent("FAILURE", "onFailure: ᎤᏲᏳ!<br/>" + exception.getMessage())); DictEntryPoint.eventBus.fireEvent(new UiEnableEvent(true)); throw new RuntimeException(exception); } @Override public void onSuccess(Method method, final SearchResponse sr) { btn_search.state().reset(); if (sr == null) { DictEntryPoint.eventBus.fireEvent(new MessageEvent("FAILURE", "ᎤᏲᏳ! SearchResponse is NULL")); return; } logger.info("SearchResponse: " + sr.data.size()); DictEntryPoint.eventBus.fireEvent(new ClearResultsEvent()); DictEntryPoint.eventBus.fireEvent(new SearchResponseEvent(sr)); } }; }
mjoyner-vbservices-net/CherokeeDictionary
src/main/java/com/cherokeelessons/dict/ui/AnalysisView.java
Java
lgpl-2.1
12,628
/*! * \file CBaslineSolver.hpp * \brief Headers of the CBaselineSolver class * \author F. Palacios, T. Economon * \version 7.3.0 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2022, SU2 Contributors (cf. AUTHORS.md) * * SU2 is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * SU2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with SU2. If not, see <http://www.gnu.org/licenses/>. */ #include "CSolver.hpp" #include "../variables/CBaselineVariable.hpp" /*! * \class CBaselineSolver * \brief Main class for defining a baseline solution from a restart file (for output). * \author F. Palacios, T. Economon. */ class CBaselineSolver final : public CSolver { protected: CBaselineVariable* nodes = nullptr; /*!< \brief Variables of the baseline solver. */ /*! * \brief Return nodes to allow CSolver::base_nodes to be set. */ inline CVariable* GetBaseClassPointerToNodes() override { return nodes; } public: /*! * \brief Constructor of the class. */ CBaselineSolver(void); /*! * \overload * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ CBaselineSolver(CGeometry *geometry, CConfig *config); /*! * \overload * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. * \param[in] nVar - Number of variables. * \param[in] field_names - Vector of variable names. */ CBaselineSolver(CGeometry *geometry, CConfig *config, unsigned short val_nvar, vector<string> field_names); /*! * \brief Destructor of the class. */ ~CBaselineSolver(void) override; /*! * \brief Load a solution from a restart file. * \param[in] geometry - Geometrical definition of the problem. * \param[in] solver - Container vector with all of the solvers. * \param[in] config - Definition of the particular problem. * \param[in] val_iter - Current external iteration number. * \param[in] val_update_geo - Flag for updating coords and grid velocity. */ void LoadRestart(CGeometry **geometry, CSolver ***solver, CConfig *config, int val_iter, bool val_update_geo) override; /*! * \brief Load a FSI solution from a restart file. * \param[in] geometry - Geometrical definition of the problem. * \param[in] solver - Container vector with all of the solvers. * \param[in] config - Definition of the particular problem. * \param[in] val_iter - Current external iteration number. */ void LoadRestart_FSI(CGeometry *geometry, CConfig *config, int val_iter) final; /*! * \brief Set the number of variables and string names from the restart file. * \param[in] config - Definition of the particular problem. */ void SetOutputVariables(CGeometry *geometry, CConfig *config); };
su2code/SU2
SU2_CFD/include/solvers/CBaselineSolver.hpp
C++
lgpl-2.1
3,503
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "organizeritemdetailtransform.h" OrganizerItemDetailTransform::OrganizerItemDetailTransform() { } OrganizerItemDetailTransform::~OrganizerItemDetailTransform() { } void OrganizerItemDetailTransform::modifyBaseSchemaDefinitions(QMap<QString, QMap<QString, QOrganizerItemDetailDefinition> > &schemaDefs) const { Q_UNUSED(schemaDefs); // empty default implementation } void OrganizerItemDetailTransform::transformToDetailL(const CCalInstance& instance, QOrganizerItem *itemOccurrence) { // In most cases we can use the other transformToDetailL function without modification transformToDetailL(instance.Entry(), itemOccurrence); } void OrganizerItemDetailTransform::transformToDetailPostSaveL(const CCalEntry& entry, QOrganizerItem *item) { Q_UNUSED(entry); Q_UNUSED(item); // empty default implementation }
KDE/android-qt-mobility
plugins/organizer/symbian/transform/organizeritemdetailtransform.cpp
C++
lgpl-2.1
2,333
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2005-2008, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.filter.function.math; // this code is autogenerated - you shouldnt be modifying it! import static org.geotools.filter.capability.FunctionNameImpl.parameter; import org.geotools.filter.FunctionExpressionImpl; import org.geotools.filter.capability.FunctionNameImpl; import org.geotools.util.Converters; import org.geotools.util.factory.Hints; import org.opengis.filter.capability.FunctionName; public class FilterFunction_atan extends FunctionExpressionImpl { // public static FunctionName NAME = new FunctionNameImpl("atan","value"); public static FunctionName NAME = new FunctionNameImpl( "atan", parameter("arc tan", Double.class), parameter("value", Double.class)); public FilterFunction_atan() { super("atan"); functionName = NAME; } @Override public Object evaluate(Object feature) { Object arg0 = getExpression(0).evaluate(feature); if (arg0 == null) { return null; } arg0 = Converters.convert(arg0, Double.class, new Hints()); if (arg0 == null) { throw new IllegalArgumentException( "Filter Function problem for function atan argument #0 - expected type double"); } return Math.atan((Double) arg0); } }
geotools/geotools
modules/library/main/src/main/java/org/geotools/filter/function/math/FilterFunction_atan.java
Java
lgpl-2.1
1,964
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ** the names of its contributors may be used to endorse or promote ** products derived from this software without specific prior written ** permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtGui> #include "controllerwindow.h" //! [0] ControllerWindow::ControllerWindow() { previewWindow = new PreviewWindow(this); createTypeGroupBox(); createHintsGroupBox(); quitButton = new QPushButton(tr("&Quit")); connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); QHBoxLayout *bottomLayout = new QHBoxLayout; bottomLayout->addStretch(); bottomLayout->addWidget(quitButton); QHBoxLayout *mainLayout = new QHBoxLayout; mainLayout->addWidget(typeGroupBox); mainLayout->addWidget(hintsGroupBox); mainLayout->addLayout(bottomLayout); setLayout(mainLayout); setWindowTitle(tr("Window Flags")); updatePreview(); } //! [0] //! [1] void ControllerWindow::updatePreview() { Qt::WindowFlags flags = 0; if (windowRadioButton->isChecked()) { flags = Qt::Window; } else if (dialogRadioButton->isChecked()) { flags = Qt::Dialog; } else if (sheetRadioButton->isChecked()) { flags = Qt::Sheet; } else if (drawerRadioButton->isChecked()) { flags = Qt::Drawer; } else if (popupRadioButton->isChecked()) { flags = Qt::Popup; } else if (toolRadioButton->isChecked()) { flags = Qt::Tool; } else if (toolTipRadioButton->isChecked()) { flags = Qt::ToolTip; } else if (splashScreenRadioButton->isChecked()) { flags = Qt::SplashScreen; //! [1] //! [2] } //! [2] //! [3] if (msWindowsFixedSizeDialogCheckBox->isChecked()) flags |= Qt::MSWindowsFixedSizeDialogHint; if (x11BypassWindowManagerCheckBox->isChecked()) flags |= Qt::X11BypassWindowManagerHint; if (framelessWindowCheckBox->isChecked()) flags |= Qt::FramelessWindowHint; if (windowTitleCheckBox->isChecked()) flags |= Qt::WindowTitleHint; if (windowSystemMenuCheckBox->isChecked()) flags |= Qt::WindowSystemMenuHint; if (windowMinimizeButtonCheckBox->isChecked()) flags |= Qt::WindowMinimizeButtonHint; if (windowMaximizeButtonCheckBox->isChecked()) flags |= Qt::WindowMaximizeButtonHint; if (windowCloseButtonCheckBox->isChecked()) flags |= Qt::WindowCloseButtonHint; if (windowContextHelpButtonCheckBox->isChecked()) flags |= Qt::WindowContextHelpButtonHint; if (windowShadeButtonCheckBox->isChecked()) flags |= Qt::WindowShadeButtonHint; if (windowStaysOnTopCheckBox->isChecked()) flags |= Qt::WindowStaysOnTopHint; if (windowStaysOnBottomCheckBox->isChecked()) flags |= Qt::WindowStaysOnBottomHint; if (customizeWindowHintCheckBox->isChecked()) flags |= Qt::CustomizeWindowHint; previewWindow->setWindowFlags(flags); //! [3] //! [4] QPoint pos = previewWindow->pos(); if (pos.x() < 0) pos.setX(0); if (pos.y() < 0) pos.setY(0); previewWindow->move(pos); previewWindow->show(); } //! [4] //! [5] void ControllerWindow::createTypeGroupBox() { typeGroupBox = new QGroupBox(tr("Type")); windowRadioButton = createRadioButton(tr("Window")); dialogRadioButton = createRadioButton(tr("Dialog")); sheetRadioButton = createRadioButton(tr("Sheet")); drawerRadioButton = createRadioButton(tr("Drawer")); popupRadioButton = createRadioButton(tr("Popup")); toolRadioButton = createRadioButton(tr("Tool")); toolTipRadioButton = createRadioButton(tr("Tooltip")); splashScreenRadioButton = createRadioButton(tr("Splash screen")); windowRadioButton->setChecked(true); QGridLayout *layout = new QGridLayout; layout->addWidget(windowRadioButton, 0, 0); layout->addWidget(dialogRadioButton, 1, 0); layout->addWidget(sheetRadioButton, 2, 0); layout->addWidget(drawerRadioButton, 3, 0); layout->addWidget(popupRadioButton, 0, 1); layout->addWidget(toolRadioButton, 1, 1); layout->addWidget(toolTipRadioButton, 2, 1); layout->addWidget(splashScreenRadioButton, 3, 1); typeGroupBox->setLayout(layout); } //! [5] //! [6] void ControllerWindow::createHintsGroupBox() { hintsGroupBox = new QGroupBox(tr("Hints")); msWindowsFixedSizeDialogCheckBox = createCheckBox(tr("MS Windows fixed size dialog")); x11BypassWindowManagerCheckBox = createCheckBox(tr("X11 bypass window manager")); framelessWindowCheckBox = createCheckBox(tr("Frameless window")); windowTitleCheckBox = createCheckBox(tr("Window title")); windowSystemMenuCheckBox = createCheckBox(tr("Window system menu")); windowMinimizeButtonCheckBox = createCheckBox(tr("Window minimize button")); windowMaximizeButtonCheckBox = createCheckBox(tr("Window maximize button")); windowCloseButtonCheckBox = createCheckBox(tr("Window close button")); windowContextHelpButtonCheckBox = createCheckBox(tr("Window context help button")); windowShadeButtonCheckBox = createCheckBox(tr("Window shade button")); windowStaysOnTopCheckBox = createCheckBox(tr("Window stays on top")); windowStaysOnBottomCheckBox = createCheckBox(tr("Window stays on bottom")); customizeWindowHintCheckBox= createCheckBox(tr("Customize window")); QGridLayout *layout = new QGridLayout; layout->addWidget(msWindowsFixedSizeDialogCheckBox, 0, 0); layout->addWidget(x11BypassWindowManagerCheckBox, 1, 0); layout->addWidget(framelessWindowCheckBox, 2, 0); layout->addWidget(windowTitleCheckBox, 3, 0); layout->addWidget(windowSystemMenuCheckBox, 4, 0); layout->addWidget(windowMinimizeButtonCheckBox, 0, 1); layout->addWidget(windowMaximizeButtonCheckBox, 1, 1); layout->addWidget(windowCloseButtonCheckBox, 2, 1); layout->addWidget(windowContextHelpButtonCheckBox, 3, 1); layout->addWidget(windowShadeButtonCheckBox, 4, 1); layout->addWidget(windowStaysOnTopCheckBox, 5, 1); layout->addWidget(windowStaysOnBottomCheckBox, 6, 1); layout->addWidget(customizeWindowHintCheckBox, 5, 0); hintsGroupBox->setLayout(layout); } //! [6] //! [7] QCheckBox *ControllerWindow::createCheckBox(const QString &text) { QCheckBox *checkBox = new QCheckBox(text); connect(checkBox, SIGNAL(clicked()), this, SLOT(updatePreview())); return checkBox; } //! [7] //! [8] QRadioButton *ControllerWindow::createRadioButton(const QString &text) { QRadioButton *button = new QRadioButton(text); connect(button, SIGNAL(clicked()), this, SLOT(updatePreview())); return button; } //! [8]
sunblithe/qt-everywhere-opensource-src-4.7.1
examples/widgets/windowflags/controllerwindow.cpp
C++
lgpl-2.1
8,485
<?php /* * $Id$ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\ORM\Tools\Cli\Tasks; use Doctrine\Common\Cli\Tasks\AbstractTask, Doctrine\Common\Version; /** * CLI Task to display the doctrine version * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @version $Revision$ * @author Benjamin Eberlei <kontakt@beberlei.de> * @author Guilherme Blanco <guilhermeblanco@hotmail.com> * @author Jonathan Wage <jonwage@gmail.com> * @author Roman Borschel <roman@code-factory.org> */ class VersionTask extends AbstractTask { /** * @inheritdoc */ public function buildDocumentation() { // There're no options on this task $this->getDocumentation()->getOptionGroup()->clear(); $doc = $this->getDocumentation(); $doc->setName('version') ->setDescription('Displays the current installed Doctrine version.'); } /** * Displays the current version of Doctrine * */ public function run() { $this->getPrinter()->writeln('You are currently running Doctrine ' . Version::VERSION, 'INFO'); } }
giorgiosironi/NakedPhp
library/Doctrine/ORM/Tools/Cli/Tasks/VersionTask.php
PHP
lgpl-2.1
2,130
///* // * MAST: Multidisciplinary-design Adaptation and Sensitivity Toolkit // * Copyright (C) 2013-2020 Manav Bhatia and MAST authors // * // * This library is free software; you can redistribute it and/or // * modify it under the terms of the GNU Lesser General Public // * License as published by the Free Software Foundation; either // * version 2.1 of the License, or (at your option) any later version. // * // * This library is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // * Lesser General Public License for more details. // * // * You should have received a copy of the GNU Lesser General Public // * License along with this library; if not, write to the Free Software // * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // */ // //// MAST includes //#include "examples/base/multilinear_interpolation.h" //#include "examples/structural/beam_optimization/beam_optimization_base.h" //#include "property_cards/solid_1d_section_element_property_card.h" //#include "property_cards/material_property_card_base.h" // // // //MAST::BeamWeight::BeamWeight(MAST::PhysicsDisciplineBase& discipline): //MAST::FieldFunction<Real>("BeamWeight"), //_discipline(discipline) //{ } // // // //MAST::BeamWeight::~BeamWeight() { } // // // //void //MAST::BeamWeight::operator() (const libMesh::Point& p, // Real t, // Real& v) const { // // // get a reference to the mesh // const libMesh::MeshBase& // mesh = _discipline.get_equation_systems().get_mesh(); // libMesh::MeshBase::const_element_iterator // eit = mesh.active_local_elements_begin(), // eend = mesh.active_local_elements_end(); // // Real h, rho, x0, x1, dx; // v = 0.; // // libMesh::Point elem_p; // const unsigned int n_sec = 3; // number of quadrature divs // // for ( ; eit != eend; eit++ ) { // // // get a pointer to the element and then as the discipline // // for the element property // const libMesh::Elem* e = *eit; // // const MAST::ElementPropertyCardBase& prop = // _discipline.get_property_card(*e); // // // assuming that the element is one-dimensional, we need // // its section area value // // // before that, convert the property to a 1D section property // // card // const MAST::Solid1DSectionElementPropertyCard& prop1d = // dynamic_cast<const MAST::Solid1DSectionElementPropertyCard&>(prop); // // // get a reference to the section area // const MAST::FieldFunction<Real>& area = prop1d.A(); // // // get a reference to the density variable // const MAST::MaterialPropertyCardBase& mat = prop.get_material(); // const MAST::FieldFunction<Real> &rhof = // mat.get<MAST::FieldFunction<Real> >("rho"); // // // // for each element iterate over the length and calculate the // // BeamWeight from the section area and section density // // use three point trapezoidal rule to calculate the integral // x0 = e->point(0)(0); // x1 = e->point(1)(0); // dx = (x1-x0)/n_sec; // for (unsigned int i=0; i<n_sec; i++) { // elem_p(0) = x0 + dx*(i+0.5); // area(elem_p, 0., h); // rhof(elem_p, 0., rho); // v += h * rho * dx; // } // // } //} // // // // // //void //MAST::BeamWeight::derivative(const MAST::FunctionBase& f, // const libMesh::Point& p, // Real t, // Real& v) const { // // // get a reference to the mesh // const libMesh::MeshBase& // mesh = _discipline.get_equation_systems().get_mesh(); // libMesh::MeshBase::const_element_iterator // eit = mesh.active_local_elements_begin(), // eend = mesh.active_local_elements_end(); // // Real h, rho, dh, drho, x0, x1, dx; // v = 0.; // // libMesh::Point elem_p; // const unsigned int n_sec = 3; // number of quadrature divs // // for ( ; eit != eend; eit++ ) { // // // get a pointer to the element and then as the discipline // // for the element property // const libMesh::Elem* e = *eit; // // const MAST::ElementPropertyCardBase& prop = // _discipline.get_property_card(*e); // // // assuming that the element is one-dimensional, we need // // its section area value // // // before that, convert the property to a 1D section property // // card // const MAST::Solid1DSectionElementPropertyCard& prop1d = // dynamic_cast<const MAST::Solid1DSectionElementPropertyCard&>(prop); // // // get a reference to the section area // const MAST::FieldFunction<Real>& // area = prop1d.A(); // // // get a reference to the density variable // const MAST::MaterialPropertyCardBase& mat = // prop.get_material(); // const MAST::FieldFunction<Real> &rhof = // mat.get<MAST::FieldFunction<Real> >("rho"); // // // // for each element iterate over the length and calculate the // // BeamWeight from the section area and section density // // use three point trapezoidal rule to calculate the integral // x0 = e->point(0)(0); // x1 = e->point(1)(0); // dx = (x1-x0)/n_sec; // for (unsigned int i=0; i<n_sec; i++) { // elem_p(0) = x0 + dx*(i+0.5); // area(elem_p, 0., h); // area.derivative( f, elem_p, 0., dh); // rhof(elem_p, 0., rho); // rhof.derivative( f, elem_p, 0., drho); // v += (dh * rho + h * drho) * dx; // } // // } //} // //
MASTmultiphysics/mast-multiphysics
examples/old/structural/beam_optimization/beam_optimization_base.cpp
C++
lgpl-2.1
6,007
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * * Created on 01-21-2010 */ package org.biojava3.core.sequence.features; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import org.biojava3.core.sequence.location.SequenceLocation; import org.biojava3.core.sequence.template.AbstractSequence; import org.biojava3.core.sequence.template.Compound; /** * A feature is currently any descriptive item that can be associated with a sequence position(s) * A feature has a type and a source which is currently a string to allow flexibility for the user * Ideally well defined features should have a class to describe attributes of that feature * @author Scooter Willis <willishf at gmail dot com> */ public abstract class AbstractFeature<S extends AbstractSequence<C>, C extends Compound> implements FeatureInterface<S, C> { List<FeatureInterface<S, C>> childrenFeatures = new ArrayList<FeatureInterface<S, C>>(); FeatureInterface<S, C> parentFeature; SequenceLocation<S, C> sequenceLocation; String type = ""; String source = ""; private String description = ""; private String shortDescription = ""; private Object userObject = null; private HashMap<String,Qualifier> Qualifiers = new HashMap<String,Qualifier>(); /** * A feature has a type and a source * @param type * @param source */ public AbstractFeature(String type,String source){ this.type = type; this.source = source; } /** * A feature could be a single sequence position like a mutation or a post translational modification of an amino acid. * It could also be the docking interface of N number of amino acids on the surface. The location wold then be a collection * of sequence positions instead of a single sequence position or the begin and end of a sequence seqment. * @return */ @Override public SequenceLocation<S, C> getLocations() { return sequenceLocation; } /** * A feature could be a single sequence position like a mutation or a post translational modification of an amino acid. * It could also be the docking interface of N number of amino acids on the surface. The location wold then be a collection * of sequence positions instead of a single sequence position or the begin and end of a sequence seqment. * @param loc */ @Override public void setLocation(SequenceLocation<S, C> loc) { sequenceLocation = loc; } /** * The feature type * @return */ @Override public String getType() { return type; } /** * Set the feature type * @param type */ @Override public void setType(String type) { this.type = type; } /** * The feature source * @return */ @Override public String getSource() { return source; } /** * Set the feature source * @param source */ @Override public void setSource(String source) { this.source = source; } /** * A feature can be the child or contained by a parent feature. An example is a Helix feature could contain * children features. A PFAM domain could contain secondary structures. * @param feature */ @Override public void setParentFeature(FeatureInterface<S, C> feature) { parentFeature = feature; } /** * Get the parent Feature * @return */ @Override public FeatureInterface<S, C> getParentFeature() { return parentFeature; } /** * Get the children features * @return */ @Override public List<FeatureInterface<S, C>> getChildrenFeatures() { return childrenFeatures; } /** * Set the children features * @param features */ @Override public void setChildrenFeatures(List<FeatureInterface<S, C>> features) { childrenFeatures = features; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the shortDescription */ public String getShortDescription() { return shortDescription; } /** * @param shortDescription the shortDescription to set */ public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } /** * Sort features by start position and then longest length. When features are added * having them sorted by start position and then longest length helps on the layout * of overlapping features so they are delivered in a proper order. */ public static final Comparator<FeatureInterface<?, ?>> LOCATION_LENGTH = new Comparator<FeatureInterface<?, ?>>() { public int compare(FeatureInterface<?, ?> e1, FeatureInterface<?, ?> e2) { double v1 = e1.getLocations().getStart().getPosition(); double v2 = e2.getLocations().getStart().getPosition(); if (v1 < v2) { return -1; } else if (v1 > v2) { return 1; } else { double end1 = e1.getLocations().getEnd().getPosition(); double end2 = e2.getLocations().getEnd().getPosition(); if(end1 > end2) return -1; else if(end1 < end2) return 1; else return 0; } } }; /** * Sort features by length. //TODO need to handle cases where features have multiple locations, strand etc * */ static public final Comparator<FeatureInterface<?, ?>> LENGTH = new Comparator<FeatureInterface<?, ?>>() { public int compare(FeatureInterface<?, ?> e1, FeatureInterface<?, ?> e2) { double v1 = Math.abs(e1.getLocations().getEnd().getPosition()- e1.getLocations().getStart().getPosition()); double v2 = Math.abs(e2.getLocations().getEnd().getPosition() - e2.getLocations().getStart().getPosition()); if (v1 < v2) { return -1; } else if (v1 > v2) { return 1; } else { return 0; } } }; /** * Sort features by type */ public static final Comparator<FeatureInterface<?, ?>> TYPE = new Comparator<FeatureInterface<?, ?>>() { @Override public int compare(FeatureInterface<?, ?> o1, FeatureInterface<?, ?> o2) { return o1.getType().compareTo(o2.getType()); } }; /** * @return the userObject */ public Object getUserObject() { return userObject; } /** * Allow the user to associate an object with the feature. This way if a feature which is displayed in a GUI * is clicked on the application can then get a user defined object associated with the feature. * @param userObject the userObject to set */ public void setUserObject(Object userObject) { this.userObject = userObject; } @Override public HashMap<String, Qualifier> getQualifiers() { // TODO Auto-generated method stub return Qualifiers; } @Override public void setQualifiers(HashMap<String, Qualifier> qualifiers) { // TODO Auto-generated method stub Qualifiers = qualifiers; } @Override public void addQualifier(String key, Qualifier qualifier) { // TODO Auto-generated method stub Qualifiers.put(key, qualifier); } }
JolantaWojcik/biojavaOwn
biojava3-core/src/main/java/org/biojava3/core/sequence/features/AbstractFeature.java
Java
lgpl-2.1
8,290
package com.megathirio.thekingdom.network; import com.megathirio.thekingdom.client.gui.GuiTKTileEntity; import com.megathirio.thekingdom.guicontainer.ContainerTKTileEntity; import com.megathirio.thekingdom.tileentities.TKTileEntity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.IGuiHandler; /** * Created by TheJackyl on 11/18/2015. */ public class TKGuiHandler implements IGuiHandler { public static final int MOD_TILE_ENTITY_GUI = 0; @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { if (ID == MOD_TILE_ENTITY_GUI) return new ContainerTKTileEntity(player.inventory, (TKTileEntity) world.getTileEntity(new BlockPos(x, y, z))); return null; } @Override public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { if (ID == MOD_TILE_ENTITY_GUI) return new GuiTKTileEntity(player.inventory, (TKTileEntity) world.getTileEntity(new BlockPos(x, y, z))); return null; } }
DaJackyl/TheKingdom-1.8
src/main/java/com/megathirio/thekingdom/network/TKGuiHandler.java
Java
lgpl-2.1
1,176
package de.fiduciagad.anflibrary.anFReceiver.anFStorage.anFServiceHandling; import android.content.Context; import android.database.Cursor; import de.fiduciagad.anflibrary.anFReceiver.anFStorage.AnFOpenHandler; import java.util.ArrayList; import java.util.List; /** * Created by Felix Schiefer on 09.01.2016. */ public class ServiceDB extends AnFOpenHandler { Context context; public ServiceDB(Context context) { super(context); this.context = context; } public List<String> getServiceList() { List<String> serviceList = new ArrayList<>(); Cursor c = this.queryServices(); int ciService = c.getColumnIndex(this.SERVICE); while (c.moveToNext()) { String service = c.getString(ciService); serviceList.add(service); } c.close(); this.close(); return serviceList; } public boolean insert(String service) { Cursor c = this.queryService(service); if (c.getCount() < 1) { long rowId = this.insertServices(service); if (rowId != -1) { CreateDefaultValues defaultValues = new CreateDefaultValues(context); defaultValues.setDefaultValues(service); return true; } } return false; } }
fiduciagad/active-notification-framework
src/main/java/de/fiduciagad/anflibrary/anFReceiver/anFStorage/anFServiceHandling/ServiceDB.java
Java
lgpl-2.1
1,332
<?php //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__)) !== false) { header("location: index.php"); exit; } /*This file is part of J4PHP - Ensembles de propriétés et méthodes permettant le developpment rapide d'application web modulaire Copyright (c) 2002-2004 @PICNet This program is free software; you can redistribute it and/or modify it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU LESSER GENERAL PUBLIC LICENSE for more details. You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ APIC::import("org.apicnet.io.OOo.absOOo"); /** * OOoStyle * * @package * @author apicnet * @copyright Copyright (c) 2004 * @version $Id: OOoStyle.php,v 1.3 2005-05-18 11:01:39 mose Exp $ * @access public **/ class OOoStyle extends absOOo { var $type; var $STYLNUM = array( 'style_family_text' => 1, 'style_family_para' => 1, 'style_page_style' => 1 ); function OOoStyle($dir){ parent::absOOo(); $this->DIRXML = $dir; $this->FILENAME = "styles.xml"; $file = new File($dir."/".$this->FILENAME); if ($file->exists()) { $this->xml = new DOMIT_Document(); $this->xml->loadXML($dir."/".$this->FILENAME, false); } else { $this->xml = new DOMIT_Document(); $this->create(); } $this->xml->setDocType("<!DOCTYPE office:document-styles PUBLIC \"-//OpenOffice.org//DTD OfficeDocument 1.0//EN\" \"office.dtd\">"); } function create(){ $docStyleNode =& $this->xml->createElement("office:document-styles"); $docStyleNode->setAttribute("xmlns:office", "http://openoffice.org/2000/office"); $docStyleNode->setAttribute("xmlns:style", "http://openoffice.org/2000/style" ); $docStyleNode->setAttribute("xmlns:text", "http://openoffice.org/2000/text" ); $docStyleNode->setAttribute("xmlns:table", "http://openoffice.org/2000/table" ); $docStyleNode->setAttribute("xmlns:draw", "http://openoffice.org/2000/drawing" ); $docStyleNode->setAttribute("xmlns:fo", "http://www.w3.org/1999/XSL/Format" ); $docStyleNode->setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink" ); $docStyleNode->setAttribute("xmlns:number", "http://openoffice.org/2000/datastyle" ); $docStyleNode->setAttribute("xmlns:svg", "http://www.w3.org/2000/svg" ); $docStyleNode->setAttribute("xmlns:chart", "http://openoffice.org/2000/chart" ); $docStyleNode->setAttribute("xmlns:dr3d", "http://openoffice.org/2000/dr3d" ); $docStyleNode->setAttribute("xmlns:math", "http://www.w3.org/1998/Math/MathML" ); $docStyleNode->setAttribute("xmlns:form", "http://openoffice.org/2000/form" ); $docStyleNode->setAttribute("xmlns:script", "http://openoffice.org/2000/script" ); $docStyleNode->setAttribute("office:version", "1.0"); $fontDeclsNode =& $this->xml->createElement("office:font-decls"); $fontDeclNode =& $this->xml->createElement("style:font-decl"); $fontDeclNode->setAttribute("style:name", "Tahoma1"); $fontDeclNode->setAttribute("fo:font-family", "Tahoma"); $fontDeclsNode->appendChild($fontDeclNode); $fontDeclNode =& $this->xml->createElement("style:font-decl"); $fontDeclNode->setAttribute("style:name", "Andale Sans UI"); $fontDeclNode->setAttribute("fo:font-family", "&amp;apos;Andale Sans UI&amp;apos;"); $fontDeclNode->setAttribute("style:font-pitch", "variable"); $fontDeclsNode->appendChild($fontDeclNode); $fontDeclNode =& $this->xml->createElement("style:font-decl"); $fontDeclNode->setAttribute("style:name", "Tahoma"); $fontDeclNode->setAttribute("fo:font-family", "Tahoma"); $fontDeclNode->setAttribute("style:font-pitch", "variable"); $fontDeclsNode->appendChild($fontDeclNode); $fontDeclNode =& $this->xml->createElement("style:font-decl"); $fontDeclNode->setAttribute("style:name", "Thorndale"); $fontDeclNode->setAttribute("fo:font-family", "Thorndale"); $fontDeclNode->setAttribute("style:font-family-generic", "roman"); $fontDeclNode->setAttribute("style:font-pitch", "variable"); $fontDeclsNode->appendChild($fontDeclNode); $fontDeclNode =& $this->xml->createElement("style:font-decl"); $fontDeclNode->setAttribute("style:name", "Arial"); $fontDeclNode->setAttribute("fo:font-family", "Arial"); $fontDeclNode->setAttribute("style:font-family-generic", "swiss"); $fontDeclNode->setAttribute("style:font-pitch", "variable"); $fontDeclsNode->appendChild($fontDeclNode); $docStyleNode->appendChild($fontDeclsNode); $docStyleNode->appendChild($this->ChildText("office:automatic-styles", "")); $docStyleNode->appendChild($this->ChildText("office:master-styles", "")); $stylesNode =& $this->xml->createElement("office:styles"); $styleNode = & $this->xml->createElement("style:style"); $styleNode->setAttribute("style:name", $type); $styleNode->setAttribute("style:family", "paragraph"); $styleNode->setAttribute("style:parent-style-name", "Standard"); $styleNode->setAttribute("style:class", "extra"); $propertiesNode =& $this->xml->createElement("style:properties"); $propertiesNode->setAttribute("text:number-lines", "false"); $propertiesNode->setAttribute("text:line-number", "0"); $tabStopsNode =& $this->xml->createElement("style:tab-stops"); $tabStopNode =& $this->xml->createElement("style:tab-stop"); $tabStopNode->setAttribute("style:position", "8.498cm"); $tabStopNode->setAttribute("style:type", "center"); $tabStopsNode->appendChild($tabStopNode); $tabStopNode =& $this->xml->createElement("style:tab-stop"); $tabStopNode->setAttribute("style:position", "16.999cm"); $tabStopNode->setAttribute("style:type", "right"); $tabStopsNode->appendChild($tabStopNode); $propertiesNode->appendChild($tabStopsNode); $styleNode->appendChild($propertiesNode); $stylesNode->appendChild($styleNode); $styleNode = & $this->xml->createElement("style:style"); $styleNode->setAttribute("style:name", "Standard"); $styleNode->setAttribute("style:family", "paragraph"); $styleNode->setAttribute("style:class", "text"); $propertiesNode =& $this->xml->createElement("style:properties"); $propertiesNode->setAttribute("fo:text-align", "justify"); $propertiesNode->setAttribute("style:justify-single-word", "false"); $stylesNode->appendChild($styleNode); $docStyleNode->appendChild($stylesNode); $this->xml->setDocumentElement($docStyleNode); $this->xml->setXMLDeclaration("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); $argPage = array( "NameStyle" => "Standard", "pageWidth" => "20.999", "pageHeight" => "29.699", "printOrient" => "portrait", "marginT" => "2", "marginB" => "2", "marginL" => "2", "marginR" => "2", "writingMode" => "lr-tb" ); $this->addStylePage($argPage); $this->addGraphicStyle(); } function main(){ echo $this->toString(); } /** * OOoStyle::addStyle() * * @param Array $styleArg * @return none **/ function addStyle($styleArg){ /* * style:name * style:family * style:parent-style-name * style:class * style:next-style-name * style:list-style-name * style:master-page-name */ /* <style:style style:name="Text body" style:family="paragraph" style:parent-style-name="Standard" style:class="text"> <style:properties fo:margin-top="0cm" fo:margin-bottom="0.212cm" style:font-name="Arial" fo:font-weight="bold" /> </style:style>*/ } /** * OOoStyle::addStylePage() est une méthode d'ajout d'un entête ou d'un pied de page. * * @param Array $argPage de type * $argPage = array( "NameStyle" => "Standard", "NameStyleSuiv" => "Standard", "pageWidth" => "20.999", //text "pageHeight" => "29.699", // (top, bottom, or center) (left, right, or center) "printOrient" => "portrait", // Ecart entre l'entête et le corp du document "marginT" => "2", "marginB" => "2", "marginL" => "2", // Mager de gauche de l'entête "marginR" => "2", // Mager de Droite de l'entête "writingMode" => "lr-tb" // Hauteur de l'entête ); * @return none **/ function addStylePage($argPage){ $this->verifIntegrite($argPage, "PageStyle"); $automaticStylesNode = & $this->getNode("/office:document-styles/office:automatic-styles"); $pageMasterNode =& $this->xml->createElement("style:page-master"); $pageName = "pm".$this->STYLNUM['style_page_style']; $pageMasterNode->setAttribute("style:name", $pageName ); $this->STYLNUM['style_page_style']++; $propertieNode =& $this->xml->createElement("style:properties"); $propertieNode->setAttribute("fo:page-width", $argPage["pageWidth"]."cm"); $propertieNode->setAttribute("fo:page-height", $argPage["pageHeight"]."cm" ); $propertieNode->setAttribute("style:num-format", "1" ); $propertieNode->setAttribute("style:print-orientation", $argPage["printOrient"] ); $propertieNode->setAttribute("fo:margin-top", $argPage["marginT"]."cm" ); $propertieNode->setAttribute("fo:margin-bottom", $argPage["marginB"]."cm" ); $propertieNode->setAttribute("fo:margin-left", $argPage["marginL"]."cm" ); $propertieNode->setAttribute("fo:margin-right", $argPage["marginR"]."cm" ); $propertieNode->setAttribute("style:writing-mode", $argPage["writingMode"] ); $propertieNode->setAttribute("style:footnote-max-height", "0cm"); $footnoteSepNode =& $this->xml->createElement("style:footnote-sep"); $footnoteSepNode->setAttribute("style:width", "0.018cm"); $footnoteSepNode->setAttribute("style:distance-before-sep", "0.101cm"); $footnoteSepNode->setAttribute("style:distance-after-sep", "0.101cm"); $footnoteSepNode->setAttribute("style:adjustment", "left"); $footnoteSepNode->setAttribute("style:rel-width", "25%"); $footnoteSepNode->setAttribute("style:color", "#000000"); $propertieNode->appendChild($footnoteSepNode); $pageMasterNode->appendChild($propertieNode); $pageMasterNode->appendChild($this->ChildText("style:header-style", "")); $pageMasterNode->appendChild($this->ChildText("style:footer-style", "")); $automaticStylesNode->appendChild($pageMasterNode); $masterStylesNode = & $this->getNode("/office:document-styles/office:master-styles"); $masterPageNode =& $this->xml->createElement("style:master-page"); $masterPageNode->setAttribute("style:name", $argPage["NameStyle"]); $masterPageNode->setAttribute("style:page-master-name", $pageName); if (isset($argPage["NameStyleSuiv"])) $masterPageNode->setAttribute("style:next-style-name", $argPage["NameStyleSuiv"]); $masterStylesNode->appendChild($masterPageNode); return $pageName; } /** * OOoStyle::addStyleHeadFoot() est une méthode d'ajout d'un entête ou d'un pied de page. * * @param Array $styleArg de type * $argHeager = array( "Text" => "@PICNet", //text "img" => array( // information sur l'image "scr" => "E:/_WebDev/www/cOOlWare2/cache/c_projekte.png", "type" => "no-repeat", // (no-repeat|repeat|stretch) "position" => "bottom right"), // (top, bottom, or center) (left, right, or center) "marginB" => "0.499", // Ecart entre l'entête et le corp du document "marginL" => "0.499", // Mager de gauche de l'entête "marginR" => "0.499", // Mager de Droite de l'entête "minHeight" => "0.998", // Hauteur de l'entête "align" => "center", // Alignement du texte de l'entête (left|center|right) "BgColor" => "CEFFB5", // Couleur de fond de l'entête dans le cas ou ce dernier n'a pas d'image ); * @param String $type est le type a créer, soit un entête soit un pied de page * @param $pageMasterName * @return none **/ function addStyleHeadFoot($styleArg, $type, $pageMasterName){ if ($type != "Header" && $type != "Footer") { $this -> ErrorTracker(4, "Le type demander doit être Header ou Footer", 'addStyleHeadFoot', __FILE__, __LINE__); } $this->verifIntegrite($styleArg, $type); $headerStyleNode = & $this->getNode("/office:document-styles/office:automatic-styles/style:page-master@[style:name='".$pageMasterName."']/style:".strtolower($type)."-style"); $headerStyleNode->appendChild($this->setProperties($styleArg, $this->DIRXML)); $automaticStylesNode = & $this->getNode("/office:document-styles/office:automatic-styles"); $StyleName = "S".$this->STYLNUM['style_family_text']; if (!$this->ssNodeExist($automaticStylesNode, "style:style@[style:name='".$StyleName."']")){ $styleNode = & $this->xml->createElement("style:style"); $styleNode->setAttribute("style:name", $StyleName); $STYLNUM['style_family_text']++; $styleNode->setAttribute("style:family", "paragraph"); $styleNode->setAttribute("style:parent-style-name", $type); } $propertiesNode =& $this->xml->createElement("style:properties"); $propertiesNode->setAttribute("fo:text-align", $styleArg["align"]); $propertiesNode->setAttribute("style:justify-single-word", "false"); $styleNode->appendChild($propertiesNode); $automaticStylesNode->appendChild($styleNode); $masterPageNode = & $this->getNode("/office:document-styles/office:master-styles/style:master-page@[style:page-master-name='".$pageMasterName."']"); $headerNode =& $this->xml->createElement("style:".strtolower($type)); /********************Création de la cellule********************/ if (isset($styleArg["Text"]) && is_object($styleArg["Text"])){ if ($styleArg["Text"]->className() == "oooimg") { $pNode =& $this->xml->createElement("text:p"); $pNode->setAttribute("text:style-name", $StyleName); $headerNode->appendChild($pNode); $styleArg["Text"]->run($pNode, $automaticStylesNode, $this->DIRXML); } else { $styleArg["Text"]->run($headerNode, $automaticStylesNode, $this->DIRXML); } } else { $pNode =& $this->xml->createElement("text:p"); $pNode->setAttribute("text:style-name", $StyleName); $pNode->appendChild($this->xml->createTextNode($styleArg["Text"])); $headerNode->appendChild($pNode); } /**********************Fin de Création*************************/ $masterPageNode->appendChild($headerNode); } function addGraphicStyle(){ $stylesNode = & $this->getNode("/office:document-styles/office:styles"); $styleNode = & $this->xml->createElement("style:default-style"); $styleNode->setAttribute("style:family", "graphics"); $propertiesNode =& $this->xml->createElement("style:properties"); $propertiesNode->setAttribute("draw:start-line-spacing-horizontal", "0.283cm"); $propertiesNode->setAttribute("draw:start-line-spacing-vertical", "0.283cm"); $propertiesNode->setAttribute("style:use-window-font-color", "true"); $propertiesNode->setAttribute("style:font-name", "Thorndale"); $propertiesNode->setAttribute("fo:font-size", "12pt"); $propertiesNode->setAttribute("fo:language", "fr"); $propertiesNode->setAttribute("fo:country", "FR"); $propertiesNode->setAttribute("style:font-name-asian", "Andale Sans UI"); $propertiesNode->setAttribute("style:font-size-asian", "12pt"); $propertiesNode->setAttribute("style:language-asian", "none"); $propertiesNode->setAttribute("style:font-name-complex", "none"); $propertiesNode->setAttribute("style:country-complex", "none"); $propertiesNode->setAttribute("style:text-autospace", "ideograph-alpha"); $propertiesNode->setAttribute("style:line-break", "strict"); $propertiesNode->setAttribute("style:writing-mode", "lr-tb"); $propertiesNode->setAttribute("country-asian", "none"); $tabStopsNode =& $this->xml->createElement("style:tab-stops"); $propertiesNode->appendChild($tabStopsNode); $styleNode->appendChild($propertiesNode); $stylesNode->appendChild($styleNode); } } ?>
4thAce/evilhow
lib/sheet/include/org/apicnet/io/OOo/OOoStyle.php
PHP
lgpl-2.1
16,370
/******************************************************************************* * Copyright 2011 Adrian Cristian Ionescu * * 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 ro.zg.mdb.core.filter.constraints; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; import ro.zg.mdb.core.exceptions.MdbException; import ro.zg.mdb.core.filter.Constraint; import ro.zg.mdb.core.filter.ConstraintSet; import ro.zg.mdb.core.filter.FieldConstraintContext; import ro.zg.mdb.core.filter.ObjectConstraint; import ro.zg.mdb.core.filter.ObjectConstraintContext; import ro.zg.mdb.core.meta.persistence.data.PersistentFieldMetadata; import ro.zg.mdb.core.meta.persistence.data.PersistentObjectMetadata; public class Or<T> extends ConstraintSet<T> implements ObjectConstraint { public Or() { super(); // TODO Auto-generated constructor stub } public Or(Set<Constraint<T>> constraints) { super(constraints); // TODO Auto-generated constructor stub } public Or(Constraint<T>... contraints) { setConstraints(new HashSet<Constraint<T>>(Arrays.asList(contraints))); } @Override public Constraint<T> compile() { Constraint<T> result = null; boolean isFirst = true; for (Constraint<T> c : constraints) { if (isFirst) { result = c; isFirst = false; } else { result = result.or(c); if (result == null) { return null; } } } if (result == null) { return new All<T>(); } if (equals(result)) { return this; } return result; } @SuppressWarnings("unchecked") @Override public Constraint<T> and(Constraint<T> c) { return new And<T>(this, c); } @Override public boolean isPossible(PersistentFieldMetadata fieldDataModel) { for (Constraint<T> c : constraints) { if (c.isPossible(fieldDataModel)) { return true; } } return false; } @Override public boolean isSatisfied(T value) { Constraint<T> result = getCompiledValue(); if (result == this) { for (Constraint<T> c : constraints) { if (c.isSatisfied(value)) { return true; } } return false; } else { return result.isSatisfied(value); } } @Override public Constraint<T> not() { And<T> and = new And<T>(); for (Constraint<T> c : constraints) { and.addConstraint(c.not()); } return and; } @Override public Constraint<T> or(Constraint<T> c) { addConstraint(c); return this; } @Override public boolean process(FieldConstraintContext context) { Constraint<T> result = getCompiledValue(); if (result != null) { /* * if constraint set couldn't be reduced anymore, we'll have to process each constraint separately */ if (result == this) { boolean isPossible = false; for (Constraint<T> c : constraints) { isPossible = c.process(context) || isPossible; } return isPossible; } return result.process(context); } return false; } @Override public boolean process(ObjectConstraintContext objectContext) throws MdbException { int processed = 0; for (Constraint<T> c : constraints) { ObjectConstraint oc = (ObjectConstraint) c; boolean isProcessed = oc.process(objectContext); if (isProcessed) { processed++; } if (processed == 2) { objectContext.applyOr(); processed--; } } return (processed > 0); } @Override public boolean isSatisfied(Map<String, Object> values) { for (Constraint<T> c : constraints) { ObjectConstraint oc = (ObjectConstraint) c; if (oc.isSatisfied(values)) { return true; } } return false; } @Override public boolean isPossible(PersistentObjectMetadata objectDataModel) { for (Constraint<T> c : constraints) { ObjectConstraint oc = (ObjectConstraint) c; if (oc.isPossible(objectDataModel)) { return true; } } return false; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Or [constraints=" + constraints + "]"; } }
acionescu/mdb-commons
src/main/java/ro/zg/mdb/core/filter/constraints/Or.java
Java
lgpl-2.1
4,685
/* * Copyright 2013, TengJianfa , and other individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.free_erp.client.ui.forms.system; import com.jdatabeans.beans.data.IDataRow; import com.jdatabeans.beans.data.IDbSupport; import com.jdatabeans.beans.data.ObjectDataRow; import com.jdatabeans.beans.data.table.ITableColumnModel; import com.jdatabeans.beans.data.table.ITableModel; import com.jdatabeans.beans.data.table.JDataTableColumn; import com.jdatabeans.util.MessageBox; import org.free_erp.client.ui.core.ObjectsPool; import org.free_erp.client.ui.forms.CBaseListManageDialog; import org.free_erp.client.ui.main.Main; import org.free_erp.service.entity.system.ProductTaxrate; import org.free_erp.service.logic.IOptionSetService; import java.awt.Frame; import java.util.Collection; import java.util.List; import javax.swing.JOptionPane; /** * * @author TengJianfa mobile:086-13003311398 qq:575633370 www.free-erp.com */ public class CProTaxrateListDialog extends CBaseListManageDialog { protected CProTaxrateAddDialog dialog; public CProTaxrateListDialog(Frame parent) { super(parent); this.createDbSupport(); this.initCs(); this.initDatas(); } private void initCs() { this.setTitle("ÉÌÆ·Ë°ÂÊÏÂÀ­¿òÉèÖÃ"); } @Override protected void initColumns() { ITableColumnModel columnModel = dataTable.getTableColumnModel(); JDataTableColumn column = new JDataTableColumn(); column.setHeaderText("ÉÌÆ·Ë°ÂÊ"); column.setColumnName("proTaxrate"); column.setWidth(165); columnModel.addColumn(column); } @Override public void initDatas() { ITableModel model = this.dataTable.getTableModel(); List<ProductTaxrate> productTaxrates = service.getListProductTaxrates(Main.getMainFrame().getCompany()); for(ProductTaxrate po:productTaxrates) { IDataRow dataRow = new ObjectDataRow(po, "id",dbSupport); model.insertDataRow(dataRow); } } @Override public void doAdd() { if (this.dialog == null) { this.dialog = new CProTaxrateAddDialog(this, this.dataSource); } dialog.newDataRow(); dialog.setTitle("Ìí¼ÓÉÌÆ·Ë°ÂÊ"); dialog.setVisible(true); this.dataSource.clearTempDataRows(); } @Override public void doEdit() { if (this.dialog == null) { this.dialog = new CProTaxrateAddDialog(this, this.dataSource); } if (this.dataTable.getSelectedRow() < 0) { MessageBox.showErrorDialog(Main.getMainFrame(), "ûÓÐÈκÎÊý¾ÝÐб»Ñ¡ÖÐ!"); return; } this.dataSource.setCurrentDataRow(this.dataTable.getSelectedDataRow()); dialog.setTitle("ÐÞ¸ÄÉÌÆ·Ë°ÂÊ"); dialog.setVisible(true); } public void createDbSupport() { dbSupport = new IDbSupport() { ObjectsPool pool = Main.getMainFrame().getObjectsPool(); IOptionSetService optionSetService = Main.getServiceManager().getOptionSetService(); public void delete(Object obj) { if (obj instanceof ProductTaxrate) { ProductTaxrate po = (ProductTaxrate) obj; optionSetService.deleteProductTaxrate(po); pool.refreshProductTaxrates(); } else { throw new IllegalArgumentException("²ÎÊýÀàÐͲ»·ûºÏ!´«ÈëµÄÀàÐÍΪ" + obj.getClass().getName()); } } public void save(Object obj) { if (obj instanceof ProductTaxrate) { ProductTaxrate po = (ProductTaxrate) obj; optionSetService.saveProductTaxrate(po); pool.refreshProductTaxrates(); } else { throw new IllegalArgumentException("²ÎÊýÀàÐͲ»·ûºÏ!´«ÈëµÄÀàÐÍΪ" + obj.getClass().getName()); } } public void deleteAll(Collection<Object> objs) { JOptionPane.showMessageDialog(null, "ÔÝδʵÏÖ!"); } public void saveAll(Collection<Object> objs) { JOptionPane.showMessageDialog(null, "ÔÝδʵÏÖ!"); } }; } }
free-erp/invoicing
invoicing_client/src/org/free_erp/client/ui/forms/system/CProTaxrateListDialog.java
Java
lgpl-2.1
5,036
// // CardBox library - framework for matchmaking networked games // Copyright (C) 2005-2011 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/game-gardens // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.hextilla.cardbox.client; import com.threerings.presents.client.InvocationService; /** * Provides access to CardBox invocation services. */ public interface CardBoxService extends InvocationService { /** * Issues a request for the oid of the lobby associated with the * specified game. */ public void getLobbyOid (int gameId, ResultListener rl); }
house13/CardBox
projects/cardbox/src/main/java/com/hextilla/cardbox/client/CardBoxService.java
Java
lgpl-2.1
1,308
package tk.hotelcalifornia.oredictcc.item; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; /** * This file created by Alex Brooke * please seek the author's permission before * distributing this software. * 'Do you know Java? Because your method body is sexy' * :3 */ public class ItemOredictPeripheral extends Item { public ItemOredictPeripheral(int id) { super(id); setCreativeTab(CreativeTabs.tabMisc); } }
HotelCalifornia/oredictCC
src/main/java/tk/hotelcalifornia/oredictcc/item/ItemOredictPeripheral.java
Java
lgpl-2.1
473
using System; using HumanRightsTracker.Models; namespace Views { public partial class InstitutionPersonDetailWindow : Gtk.Window { public event EventHandler OnSaved = null; public InstitutionPersonDetailWindow () : base(Gtk.WindowType.Toplevel) { this.Build (); } public InstitutionPersonDetailWindow (Institution i, EventHandler OnSave, Gtk.Window parent) : base(Gtk.WindowType.Toplevel) { this.Build (); this.Modal = true; this.OnSaved = OnSave; this.TransientFor = parent; InstitutionPerson ip = new InstitutionPerson(); ip.Institution = i; show.InstitutionPerson = ip; show.InstitutionReadOnly (); show.IsEditable = true; } public InstitutionPersonDetailWindow (InstitutionPerson ip, EventHandler OnSave, Gtk.Window parent) : base(Gtk.WindowType.Toplevel) { this.Build (); this.Modal = true; this.OnSaved = OnSave; this.TransientFor = parent; show.InstitutionPerson = ip; show.InstitutionReadOnly (); show.IsEditable = false; } public InstitutionPersonDetailWindow (InstitutionPerson ip, Gtk.Window parent) : base(Gtk.WindowType.Toplevel) { this.Build (); this.Modal = true; this.TransientFor = parent; show.InstitutionPerson = ip; show.IsEditable = true; show.HideActionButtons (); } public InstitutionPersonDetailWindow (Person p, EventHandler OnSave, Gtk.Window parent) : base(Gtk.WindowType.Toplevel) { this.Build (); this.Modal = true; this.OnSaved = OnSave; this.TransientFor = parent; InstitutionPerson ip = new InstitutionPerson(); ip.Person = p; show.InstitutionPerson = ip; show.PersonReadOnly (); show.IsEditable = true; } public InstitutionPersonDetailWindow (InstitutionPerson ip, EventHandler OnSave, Gtk.Window parent, bool usingPerson) : base(Gtk.WindowType.Toplevel) { this.Build (); this.Modal = true; this.OnSaved = OnSave; this.TransientFor = parent; show.InstitutionPerson = ip; show.PersonReadOnly (); show.IsEditable = false; } protected void OnShowSaved (object sender, System.EventArgs e) { OnSaved (sender, e); this.Destroy (); } protected void OnShowCanceled (object sender, System.EventArgs e) { if (show.InstitutionPerson.Id < 1) { this.Destroy (); } } } }
monsterlabs/HumanRightsTracker
Views/InstitutionPeople/InstitutionPersonDetailWindow.cs
C#
lgpl-2.1
2,863
//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // QUESO - a library to support the Quantification of Uncertainty // for Estimation, Simulation and Optimization // // Copyright (C) 2008-2015 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- #include <queso/MpiComm.h> #include <queso/Environment.h> namespace QUESO { // QUESO MpiComm MPI Constructor ------------------ MpiComm::MpiComm(const BaseEnvironment& env, RawType_MPI_Comm inputRawComm) : m_env (env), #ifdef QUESO_HAS_TRILINOS m_epetraMpiComm( new Epetra_MpiComm(inputRawComm) ), #endif m_rawComm (inputRawComm), m_worldRank (-1), m_myPid (-1), m_numProc (-1) { int mpiRC = MPI_Comm_rank(inputRawComm,&m_worldRank); queso_require_equal_to_msg(mpiRC, MPI_SUCCESS, "failed MPI_Comm_rank() on full rank"); mpiRC = MPI_Comm_rank(inputRawComm,&m_myPid); queso_require_equal_to_msg(mpiRC, MPI_SUCCESS, "failed MPI_Comm_rank() on inputRawComm"); mpiRC = MPI_Comm_size(inputRawComm,&m_numProc); queso_require_equal_to_msg(mpiRC, MPI_SUCCESS, "failed MPI_Comm_size() on inputRawComm"); } // Copy constructor --------------------------------- MpiComm::MpiComm(const MpiComm& src) : m_env (src.m_env) #ifdef QUESO_HAS_TRILINOS , m_epetraMpiComm(NULL) #endif { this->copy(src); } // Destructor --------------------------------------- MpiComm::~MpiComm() { #ifdef QUESO_HAS_TRILINOS delete m_epetraMpiComm; m_epetraMpiComm = NULL; #endif } // -------------------------------------------------- // Set methodos ------------------------------------- MpiComm& MpiComm::operator=(const MpiComm& rhs) { this->copy(rhs); return *this; } // Attribute access methods ------------------------- RawType_MPI_Comm MpiComm::Comm() const { #ifdef QUESO_HAS_TRILINOS return m_epetraMpiComm->Comm(); #endif return m_rawComm; } // -------------------------------------------------- int MpiComm::MyPID() const { #ifdef QUESO_HAS_TRILINOS return m_epetraMpiComm->MyPID(); #endif return m_myPid; } // -------------------------------------------------- int MpiComm::NumProc() const { #ifdef QUESO_HAS_TRILINOS return m_epetraMpiComm->NumProc(); #endif return m_numProc; } // Methods overridden from Comm --------------------- void MpiComm::Allreduce(void* sendbuf, void* recvbuf, int count, RawType_MPI_Datatype datatype, RawType_MPI_Op op, const char* whereMsg, const char* whatMsg) const { int mpiRC = MPI_Allreduce(sendbuf, recvbuf, count, datatype, op, m_rawComm); queso_require_equal_to_msg(mpiRC, MPI_SUCCESS, whatMsg); return; } //-------------------------------------------------- void MpiComm::Barrier() const // const char* whereMsg, const char* whatMsg) const { #ifdef QUESO_HAS_TRILINOS return m_epetraMpiComm->Barrier(); #endif int mpiRC = MPI_Barrier(m_rawComm); queso_require_equal_to_msg(mpiRC, MPI_SUCCESS, "mpiRC indicates failure"); // whatMsg); return; } //-------------------------------------------------- void MpiComm::Bcast(void* buffer, int count, RawType_MPI_Datatype datatype, int root, const char* whereMsg, const char* whatMsg) const { int mpiRC = MPI_Bcast(buffer, count, datatype, root, m_rawComm); queso_require_equal_to_msg(mpiRC, MPI_SUCCESS, whatMsg); return; } //-------------------------------------------------- void MpiComm::Gather( void* sendbuf, int sendcnt, RawType_MPI_Datatype sendtype, void* recvbuf, int recvcount, RawType_MPI_Datatype recvtype, int root, const char* whereMsg, const char* whatMsg) const { //int MPI_Gather (void *sendbuf, int sendcnt, MPI_Datatype sendtype, // void *recvbuf, int recvcount, MPI_Datatype recvtype, // int root, MPI_Comm comm ) int mpiRC = MPI_Gather(sendbuf, sendcnt, sendtype, recvbuf, recvcount, recvtype, root, m_rawComm); queso_require_equal_to_msg(mpiRC, MPI_SUCCESS, whatMsg); return; } //-------------------------------------------------- void MpiComm::Gatherv( void* sendbuf, int sendcnt, RawType_MPI_Datatype sendtype, void* recvbuf, int* recvcnts, int* displs, RawType_MPI_Datatype recvtype, int root, const char* whereMsg, const char* whatMsg) const { //int MPI_Gatherv(void *sendbuf, int sendcnt, MPI_Datatype sendtype, // void *recvbuf, int *recvcnts, int *displs, MPI_Datatype recvtype, // int root, MPI_Comm comm ) int mpiRC = MPI_Gatherv(sendbuf, sendcnt, sendtype, recvbuf, recvcnts, displs, recvtype, root, m_rawComm); queso_require_equal_to_msg(mpiRC, MPI_SUCCESS, whatMsg); return; } //-------------------------------------------------- void MpiComm::Recv( void* buf, int count, RawType_MPI_Datatype datatype, int source, int tag, RawType_MPI_Status* status, const char* whereMsg, const char* whatMsg) const { int mpiRC = MPI_Recv(buf, count, datatype, source, tag, m_rawComm, status); queso_require_equal_to_msg(mpiRC, MPI_SUCCESS, whatMsg); return; } //-------------------------------------------------- void MpiComm::Send( void* buf, int count, RawType_MPI_Datatype datatype, int dest, int tag, const char* whereMsg, const char* whatMsg) const { int mpiRC = MPI_Send(buf, count, datatype, dest, tag, m_rawComm); queso_require_equal_to_msg(mpiRC, MPI_SUCCESS, whatMsg); return; } // Misc methods ------------------------------------ void MpiComm::syncPrintDebugMsg(const char* msg, unsigned int msgVerbosity, unsigned int numUSecs) const { if (m_env.syncVerbosity() >= msgVerbosity) { this->Barrier(); for (int i = 0; i < this->NumProc(); ++i) { if (i == this->MyPID()) { std::cout << msg << ": fullRank " << m_env.fullRank() << ", subEnvironment " << m_env.subId() << ", subRank " << m_env.subRank() << ", inter0Rank " << m_env.inter0Rank() << std::endl; } usleep(numUSecs); this->Barrier(); } //if (this->fullRank() == 0) std::cout << "Sleeping " << numUSecs << " microseconds..." // << std::endl; //usleep(numUSecs); this->Barrier(); } return; } // ------------------------------------------------- #ifdef QUESO_HAS_TRILINOS const Epetra_MpiComm& MpiComm::epetraMpiComm() const { return *m_epetraMpiComm; } #endif // Private methods---------------------------------- void MpiComm::copy(const MpiComm& src) { #ifdef QUESO_HAS_TRILINOS delete m_epetraMpiComm; m_epetraMpiComm = new Epetra_MpiComm(*src.m_epetraMpiComm); #endif m_rawComm = src.m_rawComm; m_worldRank = src.m_worldRank; m_myPid = src.m_myPid; m_numProc = src.m_numProc; return; } // ------------------------------------------------- } // End namespace QUESO
roystgnr/queso
src/core/src/MpiComm.C
C++
lgpl-2.1
7,683
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.xades.signature; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Set; import javax.security.auth.x500.X500Principal; import javax.xml.crypto.dsig.CanonicalizationMethod; import javax.xml.datatype.XMLGregorianCalendar; import org.apache.xml.security.transforms.Transforms; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; import eu.europa.esig.dss.DomUtils; import eu.europa.esig.dss.definition.DSSElement; import eu.europa.esig.dss.definition.xmldsig.XMLDSigAttribute; import eu.europa.esig.dss.definition.xmldsig.XMLDSigElement; import eu.europa.esig.dss.enumerations.DigestAlgorithm; import eu.europa.esig.dss.enumerations.EncryptionAlgorithm; import eu.europa.esig.dss.enumerations.MaskGenerationFunction; import eu.europa.esig.dss.enumerations.SignatureAlgorithm; import eu.europa.esig.dss.enumerations.SignaturePackaging; import eu.europa.esig.dss.enumerations.TimestampType; import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.DSSException; import eu.europa.esig.dss.model.MimeType; import eu.europa.esig.dss.model.Policy; import eu.europa.esig.dss.model.SignerLocation; import eu.europa.esig.dss.model.x509.CertificateToken; import eu.europa.esig.dss.signature.BaselineBCertificateSelector; import eu.europa.esig.dss.spi.DSSUtils; import eu.europa.esig.dss.utils.Utils; import eu.europa.esig.dss.validation.CertificateVerifier; import eu.europa.esig.dss.validation.timestamp.TimestampInclude; import eu.europa.esig.dss.validation.timestamp.TimestampToken; import eu.europa.esig.dss.xades.DSSXMLUtils; import eu.europa.esig.dss.xades.SignatureBuilder; import eu.europa.esig.dss.xades.XAdESSignatureParameters; import eu.europa.esig.dss.xades.definition.xades132.XAdES132Attribute; import eu.europa.esig.dss.xades.reference.DSSReference; import eu.europa.esig.dss.xades.reference.DSSTransform; /** * This class implements all the necessary mechanisms to build each form of the XML signature. * */ public abstract class XAdESSignatureBuilder extends XAdESBuilder implements SignatureBuilder { private static final Logger LOG = LoggerFactory.getLogger(XAdESSignatureBuilder.class); /** * Indicates if the signature was already built. (Two steps building) */ protected boolean built = false; /** * This is the reference to the original document to sign */ protected DSSDocument detachedDocument; /** * The default Canonicalization method. * Will be used if another is not specified. */ protected static final String DEFAULT_CANONICALIZATION_METHOD = CanonicalizationMethod.EXCLUSIVE; protected String keyInfoCanonicalizationMethod; protected String signedInfoCanonicalizationMethod; protected String signedPropertiesCanonicalizationMethod; protected final String deterministicId; /* * This variable represents the current DOM signature object. */ protected Element signatureDom; protected Element keyInfoDom; protected Element signedInfoDom; protected Element signatureValueDom; protected Element qualifyingPropertiesDom; protected Element signedPropertiesDom; protected Element signedSignaturePropertiesDom; protected Element signedDataObjectPropertiesDom; protected Element unsignedSignaturePropertiesDom; /** * id-suffixes for DOM elements */ protected static final String KEYINFO_SUFFIX = "keyInfo-"; protected static final String TIMESTAMP_SUFFIX = "TS-"; protected static final String VALUE_SUFFIX = "value-"; protected static final String XADES_SUFFIX = "xades-"; protected static final String OBJECT_ID_SUFFIX = "o-"; protected static final String REFERENCE_ID_SUFFIX = "r-"; /** * Creates the signature according to the packaging * * @param params * The set of parameters relating to the structure and process of the creation or extension of the * electronic signature. * @param document * The original document to sign. * @param certificateVerifier * the certificate verifier with its OCSPSource,... * @return the signature builder linked to the packaging */ public static XAdESSignatureBuilder getSignatureBuilder(final XAdESSignatureParameters params, final DSSDocument document, final CertificateVerifier certificateVerifier) { Objects.requireNonNull(params.getSignaturePackaging(), "Cannot create a SignatureBuilder. SignaturePackaging is not defined!"); switch (params.getSignaturePackaging()) { case ENVELOPED: return new EnvelopedSignatureBuilder(params, document, certificateVerifier); case ENVELOPING: return new EnvelopingSignatureBuilder(params, document, certificateVerifier); case DETACHED: return new DetachedSignatureBuilder(params, document, certificateVerifier); case INTERNALLY_DETACHED: return new InternallyDetachedSignatureBuilder(params, document, certificateVerifier); default: throw new DSSException("Unsupported packaging " + params.getSignaturePackaging()); } } /** * The default constructor for SignatureBuilder. * * @param params * The set of parameters relating to the structure and process of the creation or extension of the * electronic signature. * @param detachedDocument * The original document to sign. * @param certificateVerifier * the certificate verifier with its OCSPSource,... */ public XAdESSignatureBuilder(final XAdESSignatureParameters params, final DSSDocument detachedDocument, final CertificateVerifier certificateVerifier) { super(certificateVerifier); this.params = params; this.detachedDocument = detachedDocument; this.deterministicId = params.getDeterministicId(); } protected void setCanonicalizationMethods(final XAdESSignatureParameters params, final String canonicalizationMethod) { keyInfoCanonicalizationMethod = getCanonicalizationMethod(params.getKeyInfoCanonicalizationMethod(), canonicalizationMethod); signedInfoCanonicalizationMethod = getCanonicalizationMethod(params.getSignedInfoCanonicalizationMethod(), canonicalizationMethod); signedPropertiesCanonicalizationMethod = getCanonicalizationMethod(params.getSignedPropertiesCanonicalizationMethod(), canonicalizationMethod); } /** * Returns {@value signatureParameterCanonicalizationMethod} if exist, {@value defaultCanonicalizationMethod} otherwise * @param signatureParameterCanonicalizationMethod - Canonicalization method parameter defined in {@link XAdESSignatureParameters} * @param defaultCanonicalizationMethod - default Canonicalization method to apply if {@value signatureParameterCanonicalizationMethod} is not specified * @return - canonicalization method String */ private String getCanonicalizationMethod(final String signatureParameterCanonicalizationMethod, final String defaultCanonicalizationMethod) { if (Utils.isStringNotBlank(signatureParameterCanonicalizationMethod)) { return signatureParameterCanonicalizationMethod; } else { return defaultCanonicalizationMethod; } } /** * This is the main method which is called to build the XML signature * * @return A byte array is returned with XML that represents the canonicalized SignedInfo segment of signature. * This data are used to define the SignatureValue element. * @throws DSSException * if an error occurred */ public byte[] build() throws DSSException { xadesPaths = getCurrentXAdESPaths(); documentDom = buildRootDocumentDom(); final List<DSSReference> references = params.getReferences(); if (Utils.isCollectionEmpty(references)) { final List<DSSReference> defaultReferences = createDefaultReferences(); // The SignatureParameters object is updated with the default references. params.setReferences(defaultReferences); } else { checkReferencesValidity(); } incorporateFiles(); incorporateSignatureDom(); incorporateSignedInfo(); incorporateSignatureValue(); incorporateKeyInfo(); incorporateObject(); /** * We create <ds:Reference> segment only now, because we need first to define the SignedProperties segment to * calculate the digest of references. */ if (Utils.isArrayEmpty(params.getSignedData())) { incorporateReferences(); incorporateReferenceSignedProperties(); incorporateReferenceKeyInfo(); } // Preparation of SignedInfo byte[] canonicalizedSignedInfo = DSSXMLUtils.canonicalizeSubtree(signedInfoCanonicalizationMethod, getNodeToCanonicalize(signedInfoDom)); if (LOG.isTraceEnabled()) { LOG.trace("Canonicalized SignedInfo --> {}", new String(canonicalizedSignedInfo)); final byte[] digest = DSSUtils.digest(DigestAlgorithm.SHA256, canonicalizedSignedInfo); LOG.trace("Canonicalized SignedInfo SHA256 --> {}", Utils.toBase64(digest)); } built = true; return canonicalizedSignedInfo; } /** * Verifies a compatibility of defined signature parameters and reference transformations */ private void checkReferencesValidity() { String referenceWrongMessage = "Reference setting is not correct! "; for (DSSReference reference : params.getReferences()) { List<DSSTransform> transforms = reference.getTransforms(); if (Utils.isCollectionNotEmpty(transforms)) { boolean incorrectUsageOfEnvelopedSignature = false; for (DSSTransform transform : transforms) { switch (transform.getAlgorithm()) { case Transforms.TRANSFORM_BASE64_DECODE: if (params.isEmbedXML()) { throw new DSSException(referenceWrongMessage + "The embedXML(true) parameter is not compatible with base64 transform."); } else if (params.isManifestSignature()) { throw new DSSException(referenceWrongMessage + "Manifest signature is not compatible with base64 transform."); } else if (SignaturePackaging.ENVELOPED.equals(params.getSignaturePackaging())) { throw new DSSException(referenceWrongMessage + "Base64 transform is not compatible with Enveloped signature format."); } else if (transforms.size() > 1) { throw new DSSException(referenceWrongMessage + "Base64 transform cannot be used with other transformations."); } break; case Transforms.TRANSFORM_ENVELOPED_SIGNATURE: incorrectUsageOfEnvelopedSignature = true; break; case Transforms.TRANSFORM_C14N11_OMIT_COMMENTS: case Transforms.TRANSFORM_C14N11_WITH_COMMENTS: case Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS: case Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS: case Transforms.TRANSFORM_C14N_OMIT_COMMENTS: case Transforms.TRANSFORM_C14N_WITH_COMMENTS: // enveloped signature must follow up by a canonicalization incorrectUsageOfEnvelopedSignature = false; break; default: // do nothing break; } } if (incorrectUsageOfEnvelopedSignature) { throw new DSSException(referenceWrongMessage + "Enveloped Signature Transform must be followed up by a Canonicalization Transform."); } } else { String uri = reference.getUri(); if (Utils.isStringBlank(uri) || DomUtils.isElementReference(uri)) { LOG.warn("A reference with id='{}' and uri='{}' points to an XML Node, while no transforms are defines! " + "The configuration can lead to an unexpected result!", reference.getId(), uri); } if (SignaturePackaging.ENVELOPED.equals(params.getSignaturePackaging()) && Utils.isStringBlank(uri)) { throw new DSSException(referenceWrongMessage + "Enveloped signature must have an enveloped transformation!"); } } } } protected void incorporateFiles() { } protected Document buildRootDocumentDom() { return DomUtils.buildDOM(); } /** * This method creates a new instance of Signature element. */ public void incorporateSignatureDom() { signatureDom = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.SIGNATURE); DomUtils.addNamespaceAttribute(signatureDom, getXmldsigNamespace()); signatureDom.setAttribute(XMLDSigAttribute.ID.getAttributeName(), deterministicId); final Node parentNodeOfSignature = getParentNodeOfSignature(); incorporateSignatureDom(parentNodeOfSignature); } protected Node getParentNodeOfSignature() { return documentDom; } protected void incorporateSignatureDom(Node parentNodeOfSignature) { parentNodeOfSignature.appendChild(signatureDom); } /** * This method incorporates the SignedInfo tag * * <pre> * {@code * <ds:SignedInfo> * <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> * <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/> * ... * </ds:SignedInfo> * } * </pre> */ public void incorporateSignedInfo() { if (Utils.isArrayNotEmpty(params.getSignedData())) { LOG.debug("Using explict SignedInfo from parameter"); signedInfoDom = DomUtils.buildDOM(params.getSignedData()).getDocumentElement(); signedInfoDom = (Element) documentDom.importNode(signedInfoDom, true); signatureDom.appendChild(signedInfoDom); return; } signedInfoDom = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.SIGNED_INFO); signatureDom.appendChild(signedInfoDom); incorporateCanonicalizationMethod(signedInfoDom, signedInfoCanonicalizationMethod); final Element signatureMethod = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.SIGNATURE_METHOD); signedInfoDom.appendChild(signatureMethod); final EncryptionAlgorithm encryptionAlgorithm = params.getEncryptionAlgorithm(); final DigestAlgorithm digestAlgorithm = params.getDigestAlgorithm(); final MaskGenerationFunction mgf = params.getMaskGenerationFunction(); final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.getAlgorithm(encryptionAlgorithm, digestAlgorithm, mgf); final String signatureAlgorithmXMLId = signatureAlgorithm.getUri(); if (Utils.isStringBlank(signatureAlgorithmXMLId)) { throw new DSSException("Unsupported signature algorithm " + signatureAlgorithm); } signatureMethod.setAttribute(XMLDSigAttribute.ALGORITHM.getAttributeName(), signatureAlgorithmXMLId); } /** * This method created the CanonicalizationMethod tag like : * * <pre> * {@code * <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> * } * </pre> * * @param parentDom * the parent element * @param signedInfoCanonicalizationMethod * the canonicalization algorithm */ private void incorporateCanonicalizationMethod(final Element parentDom, final String signedInfoCanonicalizationMethod) { final Element canonicalizationMethodDom = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.CANONICALIZATION_METHOD); parentDom.appendChild(canonicalizationMethodDom); canonicalizationMethodDom.setAttribute(XMLDSigAttribute.ALGORITHM.getAttributeName(), signedInfoCanonicalizationMethod); } /** * This method creates the first reference (this is a reference to the file to sign) which is specific for each form * of signature. Here, the value of the URI is the name of the file to sign or if the information is not available * the URI will use the default value: "detached-file". */ private void incorporateReferences() { final List<DSSReference> references = params.getReferences(); for (final DSSReference reference : references) { incorporateReference(reference); } } /** * Creates KeyInfo tag. * NOTE: when trust anchor baseline profile policy is defined only the certificates previous to the trust anchor are * included. * * <pre> * {@code * <ds:KeyInfo> * <ds:X509Data> * <ds:X509Certificate> * MIIB.... * </ds:X509Certificate> * <ds:X509Certificate> * MIIB+... * </ds:X509Certificate> * </ds:X509Data> * </ds:KeyInfo> * } * </pre> * * <pre> * {@code * <ds:KeyInfo> * <ds:X509Data> * <ds:X509Certificate> * MIIB.... * </ds:X509Certificate> * <ds:X509Certificate> * MIIB+... * </ds:X509Certificate> * </ds:X509Data> * </ds:KeyInfo> * } * </pre> * * @throws DSSException * if an error occurred */ protected void incorporateKeyInfo() throws DSSException { if (params.getSigningCertificate() == null && params.isGenerateTBSWithoutCertificate()) { LOG.debug("Signing certificate not available and must be added to signature DOM later"); return; } // <ds:KeyInfo> final Element keyInfoDom = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.KEY_INFO); signatureDom.appendChild(keyInfoDom); if (params.isSignKeyInfo()) { keyInfoDom.setAttribute(XMLDSigAttribute.ID.getAttributeName(), KEYINFO_SUFFIX + deterministicId); } BaselineBCertificateSelector certSelector = new BaselineBCertificateSelector(certificateVerifier, params); List<CertificateToken> certificates = certSelector.getCertificates(); if (params.isAddX509SubjectName()) { for (CertificateToken token : certificates) { // <ds:X509Data> final Element x509DataDom = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.X509_DATA); keyInfoDom.appendChild(x509DataDom); addSubjectAndCertificate(x509DataDom, token); } } else { // <ds:X509Data> final Element x509DataDom = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.X509_DATA); keyInfoDom.appendChild(x509DataDom); for (CertificateToken token : certificates) { addCertificate(x509DataDom, token); } } this.keyInfoDom = keyInfoDom; } /** * This method creates the X509SubjectName (optional) and X509Certificate (mandatory) tags * * <pre> * {@code * <ds:X509SubjectName>...</X509SubjectName> * <ds:X509Certificate>...</ds:X509Certificate> * } * </pre> * * @param x509DataDom * the parent X509Data tag * @param token * the certificate to add */ private void addSubjectAndCertificate(final Element x509DataDom, final CertificateToken token) { DomUtils.addTextElement(documentDom, x509DataDom, getXmldsigNamespace(), XMLDSigElement.X509_SUBJECT_NAME, token.getSubjectX500Principal().getName(X500Principal.RFC2253)); addCertificate(x509DataDom, token); } /** * This method creates the X509Certificate tag which is mandatory * * <pre> * {@code * <ds:X509Certificate>...</ds:X509Certificate> * } * </pre> * * @param x509DataDom * the parent X509Data tag * @param token * the certificate to add */ private void addCertificate(final Element x509DataDom, final CertificateToken token) { DomUtils.addTextElement(documentDom, x509DataDom, getXmldsigNamespace(), XMLDSigElement.X509_CERTIFICATE, Utils.toBase64(token.getEncoded())); } /** * This method incorporates the ds:Object tag * * <pre> * {@code * <ds:Object> * <xades:QualifyingProperties> * <xades:SignedProperties> * ... * </xades:SignedProperties> * </xades:QualifyingProperties> * </ds:Object> * } * </pre> * */ protected void incorporateObject() { if (Utils.isArrayNotEmpty(params.getSignedAdESObject())) { LOG.debug("Incorporating signed XAdES Object from parameter"); Node signedObjectDom = DomUtils.buildDOM(params.getSignedAdESObject()).getDocumentElement(); signedObjectDom = documentDom.importNode(signedObjectDom, true); signatureDom.appendChild(signedObjectDom); return; } final Element objectDom = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.OBJECT); signatureDom.appendChild(objectDom); qualifyingPropertiesDom = DomUtils.addElement(documentDom, objectDom, getXadesNamespace(), getCurrentXAdESElements().getElementQualifyingProperties()); DomUtils.addNamespaceAttribute(qualifyingPropertiesDom, getXadesNamespace()); qualifyingPropertiesDom.setAttribute(TARGET, "#" + deterministicId); incorporateSignedProperties(); } /** * This method incorporates ds:References * * <pre> * {@code * <ds:Reference Type="http://uri.etsi.org/01903#SignedProperties" URI= "#xades-id-A43023AFEB149830C242377CC941360F"> * <ds:Transforms> * <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> * </ds:Transforms> * <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> * <ds:DigestValue>uijX/nvuu8g10ZVEklEnYatvFe8=</ds:DigestValue> * </ds:Reference> * } * </pre> */ protected void incorporateReferenceSignedProperties() { final Element reference = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.REFERENCE); signedInfoDom.appendChild(reference); reference.setAttribute(XMLDSigAttribute.TYPE.getAttributeName(), xadesPaths.getSignedPropertiesUri()); reference.setAttribute(XMLDSigAttribute.URI.getAttributeName(), "#" + XADES_SUFFIX + deterministicId); final Element transforms = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.TRANSFORMS); reference.appendChild(transforms); final Element transform = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.TRANSFORM); transforms.appendChild(transform); transform.setAttribute(XMLDSigAttribute.ALGORITHM.getAttributeName(), signedPropertiesCanonicalizationMethod); final DigestAlgorithm digestAlgorithm = getReferenceDigestAlgorithmOrDefault(params); incorporateDigestMethod(reference, digestAlgorithm); final byte[] canonicalizedBytes = DSSXMLUtils.canonicalizeSubtree(signedPropertiesCanonicalizationMethod, getNodeToCanonicalize(signedPropertiesDom)); if (LOG.isTraceEnabled()) { LOG.trace("Canonicalization method --> {}", signedPropertiesCanonicalizationMethod); LOG.trace("Canonicalised REF_2 --> {}", new String(canonicalizedBytes)); } incorporateDigestValueOfReference(reference, digestAlgorithm, canonicalizedBytes); } /** * Method incorporates KeyInfo ds:References. * * <pre> * {@code * <ds:Reference URI="#keyInfo-id-A43023AFEB149830C242377CC941360F"> * <ds:Transforms> * <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> * </ds:Transforms> * <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> * <ds:DigestValue>uijX/nvuu2g10ZVEklEnYatvFe4=</ds:DigestValue> * </ds:Reference> * } * </pre> */ protected void incorporateReferenceKeyInfo() { if (!params.isSignKeyInfo()) { return; } final Element reference = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.REFERENCE); signedInfoDom.appendChild(reference); reference.setAttribute(XMLDSigAttribute.URI.getAttributeName(), "#" + KEYINFO_SUFFIX + deterministicId); final Element transforms = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.TRANSFORMS); reference.appendChild(transforms); final Element transform = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.TRANSFORM); transforms.appendChild(transform); transform.setAttribute(XMLDSigAttribute.ALGORITHM.getAttributeName(), keyInfoCanonicalizationMethod); final DigestAlgorithm digestAlgorithm = getReferenceDigestAlgorithmOrDefault(params); incorporateDigestMethod(reference, digestAlgorithm); final byte[] canonicalizedBytes = DSSXMLUtils.canonicalizeSubtree(keyInfoCanonicalizationMethod, getNodeToCanonicalize(keyInfoDom)); if (LOG.isTraceEnabled()) { LOG.trace("Canonicalization method --> {}", keyInfoCanonicalizationMethod); LOG.trace("Canonicalised REF_KeyInfo --> {}", new String(canonicalizedBytes)); } incorporateDigestValueOfReference(reference, digestAlgorithm, canonicalizedBytes); } /** * Returns params.referenceDigestAlgorithm if exists, params.digestAlgorithm otherwise * @return {@link DigestAlgorithm} */ protected DigestAlgorithm getReferenceDigestAlgorithmOrDefault(XAdESSignatureParameters params) { return params.getReferenceDigestAlgorithm() != null ? params.getReferenceDigestAlgorithm() : params.getDigestAlgorithm(); } /** * This method incorporates a reference within the signedInfoDom * * @param dssReference * the {@code DSSReference} */ private void incorporateReference(final DSSReference dssReference) { final Element referenceDom = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.REFERENCE); signedInfoDom.appendChild(referenceDom); if (dssReference.getId() != null) { referenceDom.setAttribute(XMLDSigAttribute.ID.getAttributeName(), dssReference.getId()); } final String uri = dssReference.getUri(); if (uri != null) { referenceDom.setAttribute(XMLDSigAttribute.URI.getAttributeName(), uri); } final String referenceType = dssReference.getType(); if (referenceType != null) { referenceDom.setAttribute(XMLDSigAttribute.TYPE.getAttributeName(), referenceType); } final List<DSSTransform> dssTransforms = dssReference.getTransforms(); if (dssTransforms != null) { // Detached signature may not have transformations final Element transformsDom = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.TRANSFORMS); referenceDom.appendChild(transformsDom); for (final DSSTransform dssTransform : dssTransforms) { dssTransform.createTransform(documentDom, transformsDom); } } final DigestAlgorithm digestAlgorithm = dssReference.getDigestMethodAlgorithm(); incorporateDigestMethod(referenceDom, digestAlgorithm); final DSSDocument canonicalizedDocument = transformReference(dssReference); if (LOG.isTraceEnabled()) { LOG.trace("Reference canonicalization method --> {}", signedInfoCanonicalizationMethod); } incorporateDigestValue(referenceDom, dssReference, digestAlgorithm, canonicalizedDocument); } /** * Creates the ds:DigectValue DOM object for the given {@value canonicalizedBytes} * @param referenceDom - the parent element to append new DOM element to * @param digestAlgorithm - {@link DigestAlgorithm} to use * @param canonicalizedBytes - canonicalized byte array of the relevant reference DOM to hash */ private void incorporateDigestValueOfReference(final Element referenceDom, final DigestAlgorithm digestAlgorithm, final byte[] canonicalizedBytes) { final Element digestValueDom = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.DIGEST_VALUE); final String base64EncodedDigestBytes = Utils.toBase64(DSSUtils.digest(digestAlgorithm, canonicalizedBytes)); final Text textNode = documentDom.createTextNode(base64EncodedDigestBytes); digestValueDom.appendChild(textNode); referenceDom.appendChild(digestValueDom); } /** * When the user does not want to create its own references (only when signing one contents) the default one are * created. * * @return {@code List} of {@code DSSReference} */ private List<DSSReference> createDefaultReferences() { final List<DSSReference> references = new ArrayList<>(); references.add(createReference(detachedDocument, 1)); return references; } List<DSSReference> createReferencesForDocuments(List<DSSDocument> documents) { List<DSSReference> references = new ArrayList<>(); int referenceIndex = 1; for (DSSDocument dssDocument : documents) { references.add(createReference(dssDocument, referenceIndex)); referenceIndex++; } return references; } protected abstract DSSReference createReference(DSSDocument document, int referenceIndex); /** * This method performs the reference transformation. Note that for the time being (4.3.0-RC) only two types of * transformation are implemented: canonicalization {@code * Transforms.TRANSFORM_XPATH} and can be applied only for {@code SignaturePackaging.ENVELOPED}. * * @param reference * {@code DSSReference} to be transformed * @return {@code DSSDocument} containing transformed reference's data */ protected abstract DSSDocument transformReference(final DSSReference reference); /** * This method incorporates the signature value. */ protected void incorporateSignatureValue() { signatureValueDom = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.SIGNATURE_VALUE); signatureDom.appendChild(signatureValueDom); signatureValueDom.setAttribute(XMLDSigAttribute.ID.getAttributeName(), VALUE_SUFFIX + deterministicId); } /** * Creates the SignedProperties DOM object element. * * <pre> * {@code * <SignedProperties Id="xades-ide5c549340079fe19f3f90f03354a5965"> * } * </pre> */ protected void incorporateSignedProperties() { signedPropertiesDom = DomUtils.addElement(documentDom, qualifyingPropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementSignedProperties()); signedPropertiesDom.setAttribute(XMLDSigAttribute.ID.getAttributeName(), XADES_SUFFIX + deterministicId); incorporateSignedSignatureProperties(); incorporateSignedDataObjectProperties(); } /** * Creates the SignedSignatureProperties DOM object element. * * <pre> * {@code * <SignedSignatureProperties> * ... * </SignedSignatureProperties> * } * </pre> * */ protected void incorporateSignedSignatureProperties() { signedSignaturePropertiesDom = DomUtils.addElement(documentDom, signedPropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementSignedSignatureProperties()); incorporateSigningTime(); incorporateSigningCertificate(); incorporatePolicy(); incorporateSignatureProductionPlace(); incorporateSignerRole(); } private void incorporatePolicy() { final Policy signaturePolicy = params.bLevel().getSignaturePolicy(); if ((signaturePolicy != null)) {// && (signaturePolicy.getId() != null)) { final Element signaturePolicyIdentifierDom = DomUtils.addElement(documentDom, signedSignaturePropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementSignaturePolicyIdentifier()); String signaturePolicyId = signaturePolicy.getId(); if (Utils.isStringEmpty(signaturePolicyId)) { // implicit DomUtils.addElement(documentDom, signaturePolicyIdentifierDom, getXadesNamespace(), getCurrentXAdESElements().getElementSignaturePolicyImplied()); } else { // explicit final Element signaturePolicyIdDom = DomUtils.addElement(documentDom, signaturePolicyIdentifierDom, getXadesNamespace(), getCurrentXAdESElements().getElementSignaturePolicyId()); final Element sigPolicyIdDom = DomUtils.addElement(documentDom, signaturePolicyIdDom, getXadesNamespace(), getCurrentXAdESElements().getElementSigPolicyId()); Element identifierDom = DomUtils.addTextElement(documentDom, sigPolicyIdDom, getXadesNamespace(), getCurrentXAdESElements().getElementIdentifier(), signaturePolicyId); String qualifier = signaturePolicy.getQualifier(); if (Utils.isStringNotBlank(qualifier)) { identifierDom.setAttribute(XAdES132Attribute.QUALIFIER.getAttributeName(), qualifier); } String description = signaturePolicy.getDescription(); if (Utils.isStringNotEmpty(description)) { DomUtils.addTextElement(documentDom, sigPolicyIdDom, getXadesNamespace(), getCurrentXAdESElements().getElementDescription(), description); } if ((signaturePolicy.getDigestAlgorithm() != null) && (signaturePolicy.getDigestValue() != null)) { final Element sigPolicyHashDom = DomUtils.addElement(documentDom, signaturePolicyIdDom, getXadesNamespace(), getCurrentXAdESElements().getElementSigPolicyHash()); final DigestAlgorithm digestAlgorithm = signaturePolicy.getDigestAlgorithm(); incorporateDigestMethod(sigPolicyHashDom, digestAlgorithm); final byte[] hashValue = signaturePolicy.getDigestValue(); final String bas64EncodedHashValue = Utils.toBase64(hashValue); DomUtils.addTextElement(documentDom, sigPolicyHashDom, getXmldsigNamespace(), XMLDSigElement.DIGEST_VALUE, bas64EncodedHashValue); } String spuri = signaturePolicy.getSpuri(); if (Utils.isStringNotEmpty(spuri)) { Element sigPolicyQualifiers = DomUtils.addElement(documentDom, signaturePolicyIdDom, getXadesNamespace(), getCurrentXAdESElements().getElementSigPolicyQualifiers()); Element sigPolicyQualifier = DomUtils.addElement(documentDom, sigPolicyQualifiers, getXadesNamespace(), getCurrentXAdESElements().getElementSigPolicyQualifier()); DomUtils.addTextElement(documentDom, sigPolicyQualifier, getXadesNamespace(), getCurrentXAdESElements().getElementSPURI(), spuri); } } } } /** * Creates SigningTime DOM object element like : * * <pre> * {@code * <SigningTime>2013-11-23T11:22:52Z</SigningTime> * } * </pre> */ private void incorporateSigningTime() { final Date signingDate = params.bLevel().getSigningDate(); final XMLGregorianCalendar xmlGregorianCalendar = DomUtils.createXMLGregorianCalendar(signingDate); final String xmlSigningTime = xmlGregorianCalendar.toXMLFormat(); final Element signingTimeDom = DomUtils.createElementNS(documentDom, getXadesNamespace(), getCurrentXAdESElements().getElementSigningTime()); signedSignaturePropertiesDom.appendChild(signingTimeDom); final Text textNode = documentDom.createTextNode(xmlSigningTime); signingTimeDom.appendChild(textNode); } /** * Creates SigningCertificate(V2) building block DOM object: * * <pre> * {@code * <SigningCertificate> * <Cert> * <CertDigest> * <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> * <ds:DigestValue>fj8SJujSXU4fi342bdtiKVbglA0=</ds:DigestValue> * </CertDigest> * <IssuerSerial> * <ds:X509IssuerName>CN=ICA A,O=DSS,C=AA</ds:X509IssuerName> * <ds:X509SerialNumber>4</ds:X509SerialNumber> * </IssuerSerial> * </Cert> * </SigningCertificate> * } * </pre> */ private void incorporateSigningCertificate() { if (params.getSigningCertificate() == null && params.isGenerateTBSWithoutCertificate()) { return; } final Set<CertificateToken> certificates = new HashSet<>(); certificates.add(params.getSigningCertificate()); if (params.isEn319132()) { incorporateSigningCertificateV2(certificates); } else { incorporateSigningCertificateV1(certificates); } } private void incorporateSigningCertificateV1(Set<CertificateToken> certificates) { Element signingCertificateDom = DomUtils.addElement(documentDom, signedSignaturePropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementSigningCertificate()); for (final CertificateToken certificate : certificates) { final Element certDom = incorporateCert(signingCertificateDom, certificate); incorporateIssuerV1(certDom, certificate); } } private void incorporateSigningCertificateV2(Set<CertificateToken> certificates) { Element signingCertificateDom = DomUtils.addElement(documentDom, signedSignaturePropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementSigningCertificateV2()); for (final CertificateToken certificate : certificates) { final Element certDom = incorporateCert(signingCertificateDom, certificate); incorporateIssuerV2(certDom, certificate); } } /** * This method incorporates the SignedDataObjectProperties DOM element like : * * <pre> * {@code * <SignedDataObjectProperties> ... * <DataObjectFormat ObjectReference="#detached-ref-id"> * <MimeType>text/plain</MimeType> * ... * </DataObjectFormat> * </SignedDataObjectProperties> * } * </pre> */ private void incorporateSignedDataObjectProperties() { signedDataObjectPropertiesDom = DomUtils.addElement(documentDom, signedPropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementSignedDataObjectProperties()); final List<DSSReference> references = params.getReferences(); for (final DSSReference reference : references) { final String dataObjectFormatObjectReference = "#" + reference.getId(); final Element dataObjectFormatDom = DomUtils.addElement(documentDom, signedDataObjectPropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementDataObjectFormat()); dataObjectFormatDom.setAttribute(XAdES132Attribute.OBJECT_REFERENCE.getAttributeName(), dataObjectFormatObjectReference); final Element mimeTypeDom = DomUtils.addElement(documentDom, dataObjectFormatDom, getXadesNamespace(), getCurrentXAdESElements().getElementMimeType()); MimeType dataObjectFormatMimeType = getReferenceMimeType(reference); DomUtils.setTextNode(documentDom, mimeTypeDom, dataObjectFormatMimeType.getMimeTypeString()); } incorporateCommitmentTypeIndications(); incorporateContentTimestamps(); } /** * This method returns the mimetype of the given reference * * @param reference * the reference to compute * @return the {@code MimeType} of the reference or the default value {@code MimeType.BINARY} */ private MimeType getReferenceMimeType(final DSSReference reference) { MimeType dataObjectFormatMimeType = MimeType.BINARY; DSSDocument content = reference.getContents(); if (content != null && content.getMimeType() != null) { dataObjectFormatMimeType = content.getMimeType(); } return dataObjectFormatMimeType; } /** * This method incorporate the content-timestamps within the signature being created. */ private void incorporateContentTimestamps() { final List<TimestampToken> contentTimestamps = params.getContentTimestamps(); if (contentTimestamps == null) { return; } for (final TimestampToken contentTimestamp : contentTimestamps) { final String timestampId = TIMESTAMP_SUFFIX + contentTimestamp.getDSSIdAsString(); final TimestampType timeStampType = contentTimestamp.getTimeStampType(); if (TimestampType.ALL_DATA_OBJECTS_TIMESTAMP.equals(timeStampType)) { Element allDataObjectsTimestampDom = DomUtils.addElement(documentDom, signedDataObjectPropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementAllDataObjectsTimeStamp()); allDataObjectsTimestampDom.setAttribute(XMLDSigAttribute.ID.getAttributeName(), timestampId); addTimestamp(allDataObjectsTimestampDom, contentTimestamp); } else if (TimestampType.INDIVIDUAL_DATA_OBJECTS_TIMESTAMP.equals(timeStampType)) { Element individualDataObjectsTimestampDom = DomUtils.addElement(documentDom, signedDataObjectPropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementIndividualDataObjectsTimeStamp()); individualDataObjectsTimestampDom.setAttribute(XMLDSigAttribute.ID.getAttributeName(), timestampId); addTimestamp(individualDataObjectsTimestampDom, contentTimestamp); } else { throw new DSSException("Only types ALL_DATA_OBJECTS_TIMESTAMP and INDIVIDUAL_DATA_OBJECTS_TIMESTAMP are allowed"); } } } /** * This method incorporates the signer claimed roleType into signed signature properties. */ private void incorporateSignerRole() { final List<String> claimedSignerRoles = params.bLevel().getClaimedSignerRoles(); if (claimedSignerRoles != null) { final Element signerRoleDom; if (params.isEn319132()) { signerRoleDom = DomUtils.addElement(documentDom, signedSignaturePropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementSignerRoleV2()); } else { signerRoleDom = DomUtils.addElement(documentDom, signedSignaturePropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementSignerRole()); } if (Utils.isCollectionNotEmpty(claimedSignerRoles)) { final Element claimedRolesDom = DomUtils.addElement(documentDom, signerRoleDom, getXadesNamespace(), getCurrentXAdESElements().getElementClaimedRoles()); addRoles(claimedSignerRoles, claimedRolesDom, getCurrentXAdESElements().getElementClaimedRole()); } } } private void addRoles(final List<String> signerRoles, final Element rolesDom, final DSSElement roleType) { for (final String signerRole : signerRoles) { final Element roleDom = DomUtils.addElement(documentDom, rolesDom, getXadesNamespace(), roleType); DomUtils.setTextNode(documentDom, roleDom, signerRole); } } private void incorporateSignatureProductionPlace() { final SignerLocation signatureProductionPlace = params.bLevel().getSignerLocation(); if (signatureProductionPlace != null) { final Element signatureProductionPlaceDom; if (params.isEn319132()) { signatureProductionPlaceDom = DomUtils.addElement(documentDom, signedSignaturePropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementSignatureProductionPlaceV2()); } else { signatureProductionPlaceDom = DomUtils.addElement(documentDom, signedSignaturePropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementSignatureProductionPlace()); } final String city = signatureProductionPlace.getLocality(); if (city != null) { DomUtils.addTextElement(documentDom, signatureProductionPlaceDom, getXadesNamespace(), getCurrentXAdESElements().getElementCity(), city); } if (params.isEn319132()) { final String streetAddress = signatureProductionPlace.getStreet(); if (streetAddress != null) { DomUtils.addTextElement(documentDom, signatureProductionPlaceDom, getXadesNamespace(), getCurrentXAdESElements().getElementStreetAddress(), streetAddress); } } final String stateOrProvince = signatureProductionPlace.getStateOrProvince(); if (stateOrProvince != null) { DomUtils.addTextElement(documentDom, signatureProductionPlaceDom, getXadesNamespace(), getCurrentXAdESElements().getElementStateOrProvince(), stateOrProvince); } final String postalCode = signatureProductionPlace.getPostalCode(); if (postalCode != null) { DomUtils.addTextElement(documentDom, signatureProductionPlaceDom, getXadesNamespace(), getCurrentXAdESElements().getElementPostalCode(), postalCode); } final String country = signatureProductionPlace.getCountry(); if (country != null) { DomUtils.addTextElement(documentDom, signatureProductionPlaceDom, getXadesNamespace(), getCurrentXAdESElements().getElementCountryName(), country); } } } /** * Below follows the schema definition for this element. * * <xsd:element name="CommitmentTypeIndication" type="CommitmentTypeIndicationType"/> * <xsd:complexType name="CommitmentTypeIndicationType"> * ...<xsd:sequence> * ......<xsd:element name="CommitmentTypeId" type="ObjectIdentifierType"/> * ......<xsd:choice> * .........<xsd:element name="ObjectReference" type="xsd:anyURI" maxOccurs="unbounded"/> * .........<xsd:element name="AllSignedDataObjects"/> * ......</xsd:choice> * ......<xsd:element name="CommitmentTypeQualifiers" type="CommitmentTypeQualifiersListType" minOccurs="0"/> * ...</xsd:sequence> * </xsd:complexType> * * <xsd:complexType name="CommitmentTypeQualifiersListType"> * ......<xsd:sequence> * .........<xsd:element name="CommitmentTypeQualifier"* type="AnyType" minOccurs="0" maxOccurs="unbounded"/> * ......</xsd:sequence> * </xsd:complexType */ private void incorporateCommitmentTypeIndications() { final List<String> commitmentTypeIndications = params.bLevel().getCommitmentTypeIndications(); if (Utils.isCollectionNotEmpty(commitmentTypeIndications)) { for (final String commitmentTypeIndication : commitmentTypeIndications) { final Element commitmentTypeIndicationDom = DomUtils.addElement(documentDom, signedDataObjectPropertiesDom, getXadesNamespace(), getCurrentXAdESElements().getElementCommitmentTypeIndication()); final Element commitmentTypeIdDom = DomUtils.addElement(documentDom, commitmentTypeIndicationDom, getXadesNamespace(), getCurrentXAdESElements().getElementCommitmentTypeId()); DomUtils.addTextElement(documentDom, commitmentTypeIdDom, getXadesNamespace(), getCurrentXAdESElements().getElementIdentifier(), commitmentTypeIndication); // final Element objectReferenceDom = DSSXMLUtils.addElement(documentDom, commitmentTypeIndicationDom, // XADES, "ObjectReference"); // or DomUtils.addElement(documentDom, commitmentTypeIndicationDom, getXadesNamespace(), getCurrentXAdESElements().getElementAllSignedDataObjects()); // final Element commitmentTypeQualifiersDom = DSSXMLUtils.addElement(documentDom, // commitmentTypeIndicationDom, XADES, "CommitmentTypeQualifiers"); } } } /** * Adds signature value to the signature and returns XML signature (InMemoryDocument) * * @param signatureValue * @return {@link DSSDocument} representing the signature * @throws DSSException */ @Override public DSSDocument signDocument(final byte[] signatureValue) throws DSSException { if (!built) { build(); } final EncryptionAlgorithm encryptionAlgorithm = params.getEncryptionAlgorithm(); final byte[] signatureValueBytes = DSSSignatureUtils.convertToXmlDSig(encryptionAlgorithm, signatureValue); final String signatureValueBase64Encoded = Utils.toBase64(signatureValueBytes); final Text signatureValueNode = documentDom.createTextNode(signatureValueBase64Encoded); signatureValueDom.appendChild(signatureValueNode); return createXmlDocument(); } /** * Adds the content of a timestamp into a given timestamp element * * @param timestampElement */ protected void addTimestamp(final Element timestampElement, final TimestampToken token) { // List<TimestampInclude> includes, String canonicalizationMethod, TimestampToken encapsulatedTimestamp) { // add includes: URI + referencedData = "true" // add canonicalizationMethod: Algorithm // add encapsulatedTimestamp: Encoding, Id, while its textContent is the base64 encoding of the data to digest final List<TimestampInclude> includes = token.getTimestampIncludes(); if (includes != null) { for (final TimestampInclude include : includes) { final Element timestampIncludeElement = DomUtils.createElementNS(documentDom, getXadesNamespace(), getCurrentXAdESElements().getElementInclude()); String uri = include.getURI(); if (!uri.startsWith("#")) { uri = "#" + uri; } timestampIncludeElement.setAttribute(URI, uri); timestampIncludeElement.setAttribute(REFERENCED_DATA, "true"); timestampElement.appendChild(timestampIncludeElement); } } String canonicalizationMethod = token.getCanonicalizationMethod(); if (Utils.isStringNotEmpty(canonicalizationMethod)) { final Element canonicalizationMethodElement = DomUtils.createElementNS(documentDom, getXmldsigNamespace(), XMLDSigElement.CANONICALIZATION_METHOD); canonicalizationMethodElement.setAttribute(XMLDSigAttribute.ALGORITHM.getAttributeName(), canonicalizationMethod); timestampElement.appendChild(canonicalizationMethodElement); } Element encapsulatedTimestampElement = DomUtils.createElementNS(documentDom, getXadesNamespace(), getCurrentXAdESElements().getElementEncapsulatedTimeStamp()); encapsulatedTimestampElement.setTextContent(Utils.toBase64(token.getEncoded())); timestampElement.appendChild(encapsulatedTimestampElement); } protected byte[] applyTransformations(DSSDocument dssDocument, final List<DSSTransform> transforms, Node nodeToTransform) { byte[] transformedReferenceBytes = null; Iterator<DSSTransform> iterator = transforms.iterator(); while (iterator.hasNext()) { DSSTransform transform = iterator.next(); if (nodeToTransform == null) { nodeToTransform = DomUtils.buildDOM(dssDocument); } transformedReferenceBytes = transform.getBytesAfterTranformation(nodeToTransform); if (iterator.hasNext()) { nodeToTransform = DomUtils.buildDOM(transformedReferenceBytes); } } if (LOG.isDebugEnabled()) { LOG.debug("Reference bytes after transforms: "); LOG.debug(new String(transformedReferenceBytes)); } return transformedReferenceBytes; } protected Node getNodeToCanonicalize(Node node) { if (params.isPrettyPrint()) { return DSSXMLUtils.getIndentedNode(documentDom, node); } return node; } @Override protected void alignNodes() { if (unsignedSignaturePropertiesDom != null) { DSSXMLUtils.alignChildrenIndents(unsignedSignaturePropertiesDom); } if (qualifyingPropertiesDom != null) { DSSXMLUtils.alignChildrenIndents(qualifyingPropertiesDom); } } }
openlimit-signcubes/dss
dss-xades/src/main/java/eu/europa/esig/dss/xades/signature/XAdESSignatureBuilder.java
Java
lgpl-2.1
49,435
package org.cytoscape.filter.internal; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.cytoscape.application.CyUserLog; import org.cytoscape.filter.internal.view.FilterPanel; import org.cytoscape.filter.internal.view.FilterPanelController; import org.cytoscape.filter.internal.view.TransformerPanel; import org.cytoscape.filter.internal.view.TransformerPanelController; import org.cytoscape.session.events.SessionAboutToBeLoadedEvent; import org.cytoscape.session.events.SessionAboutToBeLoadedListener; import org.cytoscape.session.events.SessionAboutToBeSavedEvent; import org.cytoscape.session.events.SessionAboutToBeSavedListener; import org.cytoscape.session.events.SessionLoadedEvent; import org.cytoscape.session.events.SessionLoadedListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * #%L * Cytoscape Filters 2 Impl (filter2-impl) * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2006 - 2021 The Cytoscape Consortium * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class FilterSettingsManager implements SessionAboutToBeSavedListener, SessionAboutToBeLoadedListener, SessionLoadedListener { static final Logger logger = LoggerFactory.getLogger(CyUserLog.NAME); static final String SESSION_NAMESPACE = "org.cytoscape.filter"; final FilterPanel filterPanel; final TransformerPanel transformerPanel; private FilterIO filterIo; public FilterSettingsManager(FilterPanel filterPanel, TransformerPanel transformerPanel, FilterIO filterIo) { this.filterPanel = filterPanel; this.transformerPanel = transformerPanel; this.filterIo = filterIo; } @Override public void handleEvent(SessionAboutToBeLoadedEvent e) { filterPanel.getController().reset(filterPanel); transformerPanel.getController().reset(transformerPanel); addDefaultsIfEmpty(); } private void addDefaultsIfEmpty() { FilterPanelController filterPanelController = filterPanel.getController(); if (filterPanelController.getElementCount() == 0) { filterPanelController.addNewElement("Default filter"); } TransformerPanelController transformerPanelController = transformerPanel.getController(); if (transformerPanelController.getElementCount() == 0) { transformerPanelController.addNewElement("Default chain"); } } @Override public void handleEvent(SessionLoadedEvent event) { List<File> files = event.getLoadedSession().getAppFileListMap().get(SESSION_NAMESPACE); if (files == null) { return; } filterPanel.getController().reset(filterPanel); transformerPanel.getController().reset(transformerPanel); for (File file : files) { try { if (file.getName().equals("filters.json")) { filterIo.readTransformers(file, filterPanel); } else if (file.getName().equals("filterChains.json")) { filterIo.readTransformers(file, transformerPanel); } } catch (IOException e) { logger.error("Unexpected error", e); } } addDefaultsIfEmpty(); } @Override public void handleEvent(SessionAboutToBeSavedEvent event) { FilterPanelController filterPanelController = filterPanel.getController(); TransformerPanelController transformerPanelController = transformerPanel.getController(); List<File> files = new ArrayList<>(); try { File root = File.createTempFile(SESSION_NAMESPACE, ".temp"); root.delete(); root.mkdir(); root.deleteOnExit(); File filtersFile = new File(root, "filters.json"); filterIo.writeFilters(filtersFile, filterPanelController.getNamedTransformers()); files.add(filtersFile); File filterChainsFile = new File(root, "filterChains.json"); filterIo.writeFilters(filterChainsFile, transformerPanelController.getNamedTransformers()); files.add(filterChainsFile); for (File file : files) { file.deleteOnExit(); } event.addAppFiles(SESSION_NAMESPACE, files); } catch (Exception e) { logger.error("Unexpected error", e); } } }
cytoscape/cytoscape-impl
filter2-impl/src/main/java/org/cytoscape/filter/internal/FilterSettingsManager.java
Java
lgpl-2.1
4,622
package wingset; import org.wings.*; import org.wingx.XRichTextEditor; import org.wingx.XRichTextEditorType; public class XRichTextEditorSimpleExample extends WingSetPane { @Override protected SComponent createControls() { SPanel panel = new SPanel(); SButton button = new SButton("Update Textarea"); button.addActionListener(e -> textArea.setText(editor.getText())); panel.add(button); SButton button2 = new SButton("Disable/Enable"); button2.addActionListener(e -> editor.setEnabled(!editor.isEnabled())); panel.add(button2); return panel; } private XRichTextEditor editor; private STextArea textArea; private String testText = "'Hello World',\nThis is a RichTextEditor \"Test\""; @Override protected SComponent createExample() { SPanel panel = new SPanel(new SFlowDownLayout()); panel.setPreferredSize(SDimension.FULLWIDTH); editor = new XRichTextEditor(XRichTextEditorType.Simple); editor.setPreferredSize(SDimension.FULLAREA); editor.setText(testText); textArea = new STextArea(); textArea.setText(editor.getText()); textArea.setPreferredSize(SDimension.FULLAREA); panel.add(editor); panel.add(new SSpacer("100%", "5px")); panel.add(textArea); return panel; } }
dheid/wings3
wings-demos/demo-wingset/src/main/java/wingset/XRichTextEditorSimpleExample.java
Java
lgpl-2.1
1,390
/* --------------------------------------------------------------------------- commonc++ - A C++ Common Class Library Copyright (C) 2005-2012 Mark A Lindner This file is part of commonc++. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. --------------------------------------------------------------------------- */ #include "commonc++/Console.h++" #include "commonc++/TerminalAttr.h++" #ifdef CCXX_OS_POSIX #include <termios.h> #include <sys/ioctl.h> #include <unistd.h> #endif namespace ccxx { /* */ #ifdef CCXX_OS_WINDOWS #ifndef COMMON_LVB_REVERSE_VIDEO #define COMMON_LVB_REVERSE_VIDEO 0x4000 #endif #ifndef COMMON_LVB_UNDERSCORE #define COMMON_LVB_UNDERSCORE 0x8000 #endif Console::Console() : _attributes(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE), _intense(false), _bold(false) { _console = ::GetStdHandle(STD_ERROR_HANDLE); ::SetConsoleTextAttribute(_console, _attributes); } #else Console::Console() : _underline(false), _inverse(false), _bold(false) { _console = stderr; } #endif /* */ Console::~Console() { } /* */ size_t Console::read(char *text, size_t maxlen) { #ifdef CCXX_OS_WINDOWS DWORD r = 0; if(! ::ReadConsole(_console, reinterpret_cast<VOID *>(text), static_cast<DWORD>(maxlen - 1), &r, NULL)) return(0); *(text + r) = NUL; return(static_cast<size_t>(r)); #else if(! ::fgets(text, maxlen, stdin)) return(0); return(CharTraits::length(text)); #endif } /* */ void Console::write(const char *text, size_t len /* = 0 */) { #ifdef CCXX_OS_WINDOWS DWORD r; if(len == 0) len = CharTraits::length(text); ::WriteConsole(_console, reinterpret_cast<const VOID *>(text), static_cast<DWORD>(len), &r, NULL); #else ::fwrite(text, len, 1, stderr); ::fflush(stderr); #endif } /* */ bool Console::setEcho(bool on) { #ifdef CCXX_OS_WINDOWS DWORD mode = 0; if(! ::GetConsoleMode(_console, &mode)) return(false); if(on) mode |= (ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT); else mode &= ~ENABLE_ECHO_INPUT; return(::SetConsoleMode(_console, mode) == TRUE); #else struct termios tattr; if(::tcgetattr(STDIN_FILENO, &tattr) < 0) return(false); if(on) tattr.c_lflag |= ECHO; else tattr.c_lflag &= ~ECHO; return(::tcsetattr(STDIN_FILENO, TCSANOW, &tattr) == 0); #endif } /* */ void Console::moveCursor(uint_t row, uint_t column) { #ifdef CCXX_OS_WINDOWS if(column > INT16_MAX) column = 0; if(row > INT16_MAX) row = 0; COORD pos = { (SHORT)column, (SHORT)row }; ::SetConsoleCursorPosition(_console, pos); #else ::fprintf(_console, TERMATTR_ESC "[%d;%dH", row, column); ::fflush(_console); #endif } /* */ void Console::clear() { #ifdef CCXX_OS_WINDOWS CONSOLE_SCREEN_BUFFER_INFO csbi; if(! ::GetConsoleScreenBufferInfo(_console, &csbi)) return; DWORD dwConSize = csbi.dwSize.X * csbi.dwSize.Y; DWORD r; COORD coord = { 0, 0 }; ::FillConsoleOutputCharacter(_console, (TCHAR)' ', dwConSize, coord, &r); ::GetConsoleScreenBufferInfo(_console, &csbi); ::FillConsoleOutputAttribute(_console, csbi.wAttributes, dwConSize, coord, &r); ::SetConsoleCursorPosition(_console, coord); #else ::fputs(TERMATTR_CLEAR_SCREEN, _console); ::fputs(TERMATTR_CURSOR(0, 0), _console); ::fflush(_console); #endif } /* */ void Console::setTextForeground(TextColor color) { #ifdef CCXX_OS_WINDOWS _attributes &= ~(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); switch(color) { case ColorBlack: _intense = false; if(_bold) _attributes |= FOREGROUND_INTENSITY; break; case ColorRed: _attributes |= FOREGROUND_RED | FOREGROUND_INTENSITY; _intense = true; break; case ColorGreen: _attributes |= FOREGROUND_GREEN | FOREGROUND_INTENSITY; _intense = true; break; case ColorYellow: _attributes |= (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY); _intense = true; break; case ColorBlue: _attributes |= (FOREGROUND_BLUE | FOREGROUND_INTENSITY); _intense = true; break; case ColorMagenta: _attributes |= (FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY); _intense = true; break; case ColorCyan: _attributes |= (FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY); _intense = true; break; case ColorWhite: _attributes |= (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); _intense = false; if(_bold) _attributes |= FOREGROUND_INTENSITY; else _attributes &= ~FOREGROUND_INTENSITY; break; } ::SetConsoleTextAttribute(_console, _attributes); #else switch(color) { case ColorBlack: ::fputs(TERMATTR_FG_BLACK, _console); break; case ColorRed: ::fputs(TERMATTR_FG_RED, _console); break; case ColorGreen: ::fputs(TERMATTR_FG_GREEN, _console); break; case ColorYellow: ::fputs(TERMATTR_FG_YELLOW, _console); break; case ColorBlue: ::fputs(TERMATTR_FG_BLUE, _console); break; case ColorMagenta: ::fputs(TERMATTR_FG_MAGENTA, _console); break; case ColorCyan: ::fputs(TERMATTR_FG_CYAN, _console); break; case ColorWhite: ::fputs(TERMATTR_FG_WHITE, _console); break; } ::fflush(_console); #endif } /* */ void Console::setTextBackground(TextColor color) { #ifdef CCXX_OS_WINDOWS _attributes &= ~(BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE); switch(color) { case ColorBlack: break; case ColorRed: _attributes |= BACKGROUND_RED; break; case ColorGreen: _attributes |= BACKGROUND_GREEN; break; case ColorYellow: _attributes |= (BACKGROUND_RED | BACKGROUND_GREEN); break; case ColorBlue: _attributes |= BACKGROUND_BLUE; break; case ColorMagenta: _attributes |= (BACKGROUND_RED | BACKGROUND_BLUE); break; case ColorCyan: _attributes |= (BACKGROUND_GREEN | BACKGROUND_BLUE); break; case ColorWhite: _attributes |= (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE); } ::SetConsoleTextAttribute(_console, _attributes); #else switch(color) { case ColorBlack: ::fputs(TERMATTR_BG_BLACK, _console); break; case ColorRed: ::fputs(TERMATTR_BG_RED, _console); break; case ColorGreen: ::fputs(TERMATTR_BG_GREEN, _console); break; case ColorYellow: ::fputs(TERMATTR_BG_YELLOW, _console); break; case ColorBlue: ::fputs(TERMATTR_BG_BLUE, _console); break; case ColorMagenta: ::fputs(TERMATTR_BG_MAGENTA, _console); break; case ColorCyan: ::fputs(TERMATTR_BG_CYAN, _console); break; case ColorWhite: ::fputs(TERMATTR_BG_WHITE, _console); break; } ::fflush(_console); #endif } /* */ void Console::beginTextStyle(TextStyle style) { #ifdef CCXX_OS_WINDOWS switch(style) { case StyleBold: _attributes |= FOREGROUND_INTENSITY; _bold = true; break; case StyleUnderline: // currently not supported by Win32 _attributes |= COMMON_LVB_UNDERSCORE; break; case StyleInverse: // currently not supported by Win32 _attributes |= COMMON_LVB_REVERSE_VIDEO; break; } ::SetConsoleTextAttribute(_console, _attributes); #else switch(style) { case StyleBold: ::fputs(TERMATTR_BOLD, _console); _bold = true; break; case StyleUnderline: ::fputs(TERMATTR_UNDERLINE, _console); _underline = true; break; case StyleInverse: ::fputs(TERMATTR_INVERSE, _console); _inverse = true; break; } ::fflush(_console); #endif } /* */ void Console::endTextStyle(TextStyle style) { #ifdef CCXX_OS_WINDOWS switch(style) { case StyleBold: if(! _intense) _attributes &= ~FOREGROUND_INTENSITY; _bold = false; break; case StyleUnderline: _attributes &= ~COMMON_LVB_UNDERSCORE; break; case StyleInverse: _attributes &= ~COMMON_LVB_REVERSE_VIDEO; break; } ::SetConsoleTextAttribute(_console, _attributes); #else ::fputs(TERMATTR_NORMAL, _console); switch(style) { case StyleBold: _bold = false; break; case StyleUnderline: _underline = false; break; case StyleInverse: _inverse = false; break; } if(_bold) ::fputs(TERMATTR_BOLD, _console); if(_underline) ::fputs(TERMATTR_UNDERLINE, _console); if(_inverse) ::fputs(TERMATTR_INVERSE, _console); ::fflush(_console); #endif } /* */ void Console::resetTextStyle() { #ifdef CCXX_OS_WINDOWS _attributes &= ~(FOREGROUND_INTENSITY | COMMON_LVB_REVERSE_VIDEO | COMMON_LVB_UNDERSCORE); _bold = false; ::SetConsoleTextAttribute(_console, _attributes); #else _bold = _underline = _inverse = false; ::fputs(TERMATTR_NORMAL, _console); ::fflush(_console); #endif } /* */ void Console::setTitle(const String &title) { #ifdef CCXX_OS_WINDOWS ::SetConsoleTitle(title.c_str()); #else ::fputs("\033]0;", _console); ::fputs(title.c_str(), _console); ::fputs("\a", _console); ::fflush(_console); #endif } /* */ bool Console::getSize(uint_t *columns, uint_t *rows) { #ifdef CCXX_OS_WINDOWS CONSOLE_SCREEN_BUFFER_INFO csbi; if(::GetConsoleScreenBufferInfo(_console, &csbi) == FALSE) return(false); if(columns) *columns = csbi.dwSize.X; if(rows) *rows = csbi.dwSize.Y; return(true); #else #if defined(TIOCGWINSZ) struct winsize ws; if(::ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0) { if(columns) *columns = ws.ws_col; if(rows) *rows = ws.ws_row; return(true); } else return(false); #elif defined(TIOCGSIZE) struct ttysize ts; if(::ioctl(STDOUT_FILENO, TIOCGSIZE, &ts) == 0) { if(columns) *columns = ts.ts_cols; if(rows) *rows = ts.ts_lines; return(true); } else return(false); #else // no way to determine terminal size return(false); #endif // TIOCGSIZE #endif } }; // namespace ccxx /* end of source file */
PhoenixClub/libcommoncpp
lib/Console.c++
C++
lgpl-2.1
11,021
/* * (C) Copyright 2006-2014 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Nuxeo - initial API and implementation * */ package org.nuxeo.usermapper.test; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.NuxeoPrincipal; import org.nuxeo.ecm.platform.test.PlatformFeature; import org.nuxeo.ecm.user.center.profile.UserProfileService; import org.nuxeo.runtime.api.Framework; import org.nuxeo.runtime.test.runner.Deploy; import org.nuxeo.runtime.test.runner.Features; import org.nuxeo.runtime.test.runner.FeaturesRunner; import org.nuxeo.runtime.test.runner.LocalDeploy; import org.nuxeo.usermapper.service.UserMapperService; import org.nuxeo.usermapper.test.dummy.DummyUser; import com.google.inject.Inject; @Deploy({ "org.nuxeo.usermapper", "org.nuxeo.ecm.platform.userworkspace.api", "org.nuxeo.ecm.platform.userworkspace.types", "org.nuxeo.ecm.platform.userworkspace.core", "org.nuxeo.ecm.user.center.profile", "org.nuxeo.ecm.platform.login", "org.nuxeo.ecm.platform.login.default" }) @RunWith(FeaturesRunner.class) @LocalDeploy("org.nuxeo.usermapper:usermapper-contribs.xml") @Features(PlatformFeature.class) /** * * @author tiry * */ public class TestUserMapperService { @Inject CoreSession session; @Test public void shouldDeclareService() throws Exception { UserMapperService ums = Framework.getLocalService(UserMapperService.class); Assert.assertNotNull(ums); Assert.assertEquals(3, ums.getAvailableMappings().size()); } @Test public void testJavaContrib() throws Exception { // test create DummyUser dm = new DummyUser("jchan", "Jacky", "Chan"); UserMapperService ums = Framework.getLocalService(UserMapperService.class); NuxeoPrincipal principal = ums.getCreateOrUpdateNuxeoPrincipal("javaDummy", dm); Assert.assertNotNull(principal); Assert.assertEquals("jchan", principal.getName()); Assert.assertEquals("Jacky", principal.getFirstName()); Assert.assertEquals("Chan", principal.getLastName()); // test update dm = new DummyUser("jchan", null, "Chan2"); principal = ums.getCreateOrUpdateNuxeoPrincipal("javaDummy", dm); Assert.assertNotNull(principal); Assert.assertEquals("jchan", principal.getName()); Assert.assertEquals("Jacky", principal.getFirstName()); Assert.assertEquals("Chan2", principal.getLastName()); } @Test public void testGroovyContrib() throws Exception { // test create DummyUser dm = new DummyUser("bharper", "Ben", "Harper"); UserMapperService ums = Framework.getLocalService(UserMapperService.class); NuxeoPrincipal principal = ums.getCreateOrUpdateNuxeoPrincipal("groovyDummy", dm); Assert.assertNotNull(principal); Assert.assertEquals("bharper", principal.getName()); Assert.assertEquals("Ben", principal.getFirstName()); Assert.assertEquals("Harper", principal.getLastName()); dm = new DummyUser("bharper", "Bill", "Harper"); principal = ums.getCreateOrUpdateNuxeoPrincipal("groovyDummy", dm); Assert.assertNotNull(principal); Assert.assertEquals("bharper", principal.getName()); Assert.assertEquals("Bill", principal.getFirstName()); Assert.assertEquals("Harper", principal.getLastName()); UserProfileService ups = Framework.getService(UserProfileService.class); DocumentModel profile = ups.getUserProfileDocument("bharper", session); Assert.assertEquals("555.666.7777", profile.getPropertyValue("userprofile:phonenumber")); } @Test public void testNashornContrib() throws Exception { // test create DummyUser dm = new DummyUser("bharper", "Ben", "Harper"); UserMapperService ums = Framework.getLocalService(UserMapperService.class); NuxeoPrincipal principal = ums.getCreateOrUpdateNuxeoPrincipal("jsDummy", dm); Assert.assertNotNull(principal); Assert.assertEquals("bharper", principal.getName()); Assert.assertEquals("Ben", principal.getFirstName()); Assert.assertEquals("Harper", principal.getLastName()); dm = new DummyUser("bharper", "Bill", "Harper"); principal = ums.getCreateOrUpdateNuxeoPrincipal("jsDummy", dm); Assert.assertNotNull(principal); Assert.assertEquals("bharper", principal.getName()); Assert.assertEquals("Bill", principal.getFirstName()); Assert.assertEquals("Harper", principal.getLastName()); UserProfileService ups = Framework.getService(UserProfileService.class); DocumentModel profile = ups.getUserProfileDocument("bharper", session); Assert.assertEquals("555.666.7777", profile.getPropertyValue("userprofile:phonenumber")); } }
tiry/nuxeo-usermapper
src/test/java/org/nuxeo/usermapper/test/TestUserMapperService.java
Java
lgpl-2.1
5,512
/* Copyright 2016 Red Hat, 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 org.jboss.as.test.integration.domain.mixed; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILD_TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CLONE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DOMAIN_CONTROLLER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.IGNORE_UNUSED_CONFIG; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PORT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RUNNING_SERVER; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_CONFIG; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SHUTDOWN; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TO_PROFILE; import static org.jboss.as.controller.operations.common.Util.createRemoveOperation; import static org.jboss.as.test.integration.domain.management.util.DomainTestUtils.executeForResult; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.jboss.as.controller.ExpressionResolverImpl; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.domain.management.util.DomainLifecycleUtil; import org.jboss.as.test.integration.domain.management.util.DomainTestSupport; import org.jboss.as.test.integration.domain.management.util.DomainTestUtils; import org.jboss.as.test.integration.domain.management.util.WildFlyManagedConfiguration; import org.jboss.as.test.integration.management.util.MgmtOperationException; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.junit.AfterClass; import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; /** * Base class for tests of the ability of a DC to exclude resources from visibility to a slave. * * @author Brian Stansberry */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public abstract class DomainHostExcludesTest { private static final String[] EXCLUDED_EXTENSIONS_6X = { "org.wildfly.extension.batch.jberet", "org.wildfly.extension.bean-validation", "org.wildfly.extension.clustering.singleton", "org.wildfly.extension.core-management", "org.wildfly.extension.io", "org.wildfly.extension.messaging-activemq", "org.wildfly.extension.request-controller", "org.wildfly.extension.security.manager", "org.wildfly.extension.undertow", "org.wildfly.iiop-openjdk" }; private static final String[] EXCLUDED_EXTENSIONS_7X = { "org.jboss.as.web", "org.jboss.as.messaging", "org.jboss.as.threads" }; public static final Set<String> EXTENSIONS_SET_6X = new HashSet<>(Arrays.asList(EXCLUDED_EXTENSIONS_6X)); public static final Set<String> EXTENSIONS_SET_7X = new HashSet<>(Arrays.asList(EXCLUDED_EXTENSIONS_7X)); private static final PathElement HOST = PathElement.pathElement("host", "slave"); private static final PathAddress HOST_EXCLUDE = PathAddress.pathAddress("host-exclude", "test"); private static final PathElement SOCKET = PathElement.pathElement(SOCKET_BINDING, "http"); private static final PathAddress CLONE_PROFILE = PathAddress.pathAddress(PROFILE, CLONE); private static DomainTestSupport testSupport; private static Version.AsVersion version; /** Subclasses call from a @BeforeClass method */ protected static void setup(Class<?> clazz, String hostRelease, ModelVersion slaveApiVersion) throws IOException, MgmtOperationException, TimeoutException, InterruptedException { version = clazz.getAnnotation(Version.class).value(); testSupport = MixedDomainTestSuite.getSupport(clazz); if (version.getMajor() == 7) { // note that some of these 7+ specific changes may warrant creating a newer version of testing-host.xml for the newer slaves // at some point (the currently used host.xml is quite an old version). If these exceptions become more complicated than this, we should // probably do that. //Unset the ignore-unused-configuration flag ModelNode dc = DomainTestUtils.executeForResult( Util.getReadAttributeOperation(PathAddress.pathAddress(HOST), DOMAIN_CONTROLLER), testSupport.getDomainSlaveLifecycleUtil().getDomainClient()); dc = dc.get("remote"); dc.get(IGNORE_UNUSED_CONFIG).set(false); dc.get(OP).set("write-remote-domain-controller"); dc.get(OP_ADDR).set(PathAddress.pathAddress(HOST).toModelNode()); DomainTestUtils.executeForResult(dc, testSupport.getDomainSlaveLifecycleUtil().getDomainClient()); } stopSlave(); // restarting the slave will recopy the testing-host.xml file over the top, clobbering the ignore-unused-configuration above, // so use setRewriteConfigFiles(false) to prevent this. WildFlyManagedConfiguration slaveCfg = testSupport.getDomainSlaveConfiguration(); slaveCfg.setRewriteConfigFiles(false); ModelControllerClient client = testSupport.getDomainMasterLifecycleUtil().getDomainClient(); setupExclude(client, hostRelease, slaveApiVersion); // Add some ignored extensions to verify they are ignored addExtensions(true, client); startSlave(); } private static void stopSlave() throws IOException, MgmtOperationException, InterruptedException { ModelControllerClient client = testSupport.getDomainMasterLifecycleUtil().getDomainClient(); executeForResult(Util.createEmptyOperation(SHUTDOWN, PathAddress.pathAddress(HOST)), client); boolean gone = false; long timeout = TimeoutUtil.adjust(30000); long deadline = System.currentTimeMillis() + timeout; do { ModelNode hosts = readChildrenNames(client, PathAddress.EMPTY_ADDRESS, HOST.getKey()); gone = true; for (ModelNode host : hosts.asList()) { if (HOST.getValue().equals(host.asString())) { gone = false; Thread.sleep(100); break; } } } while (!gone && System.currentTimeMillis() < deadline); Assert.assertTrue("Slave was not removed within " + timeout + " ms", gone); testSupport.getDomainSlaveLifecycleUtil().stop(); } private static void setupExclude(ModelControllerClient client, String hostRelease, ModelVersion hostVersion) throws IOException, MgmtOperationException { ModelNode addOp = Util.createAddOperation(HOST_EXCLUDE); if (hostRelease != null) { addOp.get("host-release").set(hostRelease); } else { addOp.get("management-major-version").set(hostVersion.getMajor()); addOp.get("management-minor-version").set(hostVersion.getMinor()); if (hostVersion.getMicro() != 0) { addOp.get("management-micro-version").set(hostVersion.getMicro()); } } addOp.get("active-server-groups").add("other-server-group"); ModelNode asbgs = addOp.get("active-socket-binding-groups"); asbgs.add("full-sockets"); asbgs.add("full-ha-sockets"); ModelNode extensions = addOp.get("excluded-extensions"); for (String ext : getExcludedExtensions()) { extensions.add(ext); } executeForResult(addOp, client); } private static void addExtensions(boolean evens, ModelControllerClient client) throws IOException, MgmtOperationException { for (int i = 0; i < getExcludedExtensions().length; i++) { if ((i % 2 == 0) == evens) { executeForResult(Util.createAddOperation(PathAddress.pathAddress(EXTENSION, getExcludedExtensions()[i])), client); } } } private static void startSlave() throws TimeoutException, InterruptedException { DomainLifecycleUtil legacyUtil = testSupport.getDomainSlaveLifecycleUtil(); long start = System.currentTimeMillis(); legacyUtil.start(); legacyUtil.awaitServers(start); } @AfterClass public static void tearDown() throws IOException, MgmtOperationException, TimeoutException, InterruptedException { try { executeForResult(createRemoveOperation(HOST_EXCLUDE), testSupport.getDomainMasterLifecycleUtil().getDomainClient()); } finally { restoreSlave(); } } @Test public void test001SlaveBoot() throws Exception { ModelControllerClient slaveClient = testSupport.getDomainSlaveLifecycleUtil().getDomainClient(); checkExtensions(slaveClient); checkProfiles(slaveClient); checkSocketBindingGroups(slaveClient); checkSockets(slaveClient, PathAddress.pathAddress(SOCKET_BINDING_GROUP, "full-sockets")); checkSockets(slaveClient, PathAddress.pathAddress(SOCKET_BINDING_GROUP, "full-ha-sockets")); } @Test public void test002ServerBoot() throws IOException, MgmtOperationException, InterruptedException, OperationFailedException { ModelControllerClient masterClient = testSupport.getDomainMasterLifecycleUtil().getDomainClient(); PathAddress serverCfgAddr = PathAddress.pathAddress(HOST, PathElement.pathElement(SERVER_CONFIG, "server-one")); ModelNode op = Util.createEmptyOperation("start", serverCfgAddr); executeForResult(op, masterClient); PathAddress serverAddr = PathAddress.pathAddress(HOST, PathElement.pathElement(RUNNING_SERVER, "server-one")); awaitServerLaunch(masterClient, serverAddr); checkSockets(masterClient, serverAddr.append(PathElement.pathElement(SOCKET_BINDING_GROUP, "full-ha-sockets"))); } private void awaitServerLaunch(ModelControllerClient client, PathAddress serverAddr) throws InterruptedException { long timeout = TimeoutUtil.adjust(20000); long expired = System.currentTimeMillis() + timeout; ModelNode op = Util.getReadAttributeOperation(serverAddr, "server-state"); do { try { ModelNode state = DomainTestUtils.executeForResult(op, client); if ("running".equalsIgnoreCase(state.asString())) { return; } } catch (IOException | MgmtOperationException e) { // ignore and try again } TimeUnit.MILLISECONDS.sleep(250L); } while (System.currentTimeMillis() < expired); Assert.fail("Server did not start in " + timeout + " ms"); } @Test public void test003PostBootUpdates() throws IOException, MgmtOperationException { ModelControllerClient masterClient = testSupport.getDomainMasterLifecycleUtil().getDomainClient(); ModelControllerClient slaveClient = testSupport.getDomainSlaveLifecycleUtil().getDomainClient(); // Tweak an ignored profile and socket-binding-group to prove slave doesn't see it updateExcludedProfile(masterClient); updateExcludedSocketBindingGroup(masterClient); // Verify profile cloning is ignored when the cloned profile is excluded testProfileCloning(masterClient, slaveClient); // Add more ignored extensions to verify slave doesn't see the ops addExtensions(false, masterClient); checkExtensions(slaveClient); } private void checkExtensions(ModelControllerClient client) throws IOException, MgmtOperationException { ModelNode op = Util.createEmptyOperation(READ_CHILDREN_NAMES_OPERATION, PathAddress.EMPTY_ADDRESS); op.get(CHILD_TYPE).set(EXTENSION); ModelNode result = executeForResult(op, client); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.asInt() > 0); for (ModelNode ext : result.asList()) { Assert.assertFalse(ext.asString(), getExtensionsSet().contains(ext.asString())); } } private void checkProfiles(ModelControllerClient client) throws IOException, MgmtOperationException { ModelNode result = readChildrenNames(client, PathAddress.EMPTY_ADDRESS, PROFILE); Assert.assertTrue(result.isDefined()); Assert.assertEquals(result.toString(), 1, result.asInt()); Assert.assertEquals(result.toString(), "full-ha", result.get(0).asString()); } private void checkSocketBindingGroups(ModelControllerClient client) throws IOException, MgmtOperationException { ModelNode result = readChildrenNames(client, PathAddress.EMPTY_ADDRESS, SOCKET_BINDING_GROUP); Assert.assertTrue(result.isDefined()); Assert.assertEquals(result.toString(), 2, result.asInt()); Set<String> expected = new HashSet<>(Arrays.asList("full-sockets", "full-ha-sockets")); for (ModelNode sbg : result.asList()) { expected.remove(sbg.asString()); } Assert.assertTrue(result.toString(), expected.isEmpty()); } private void checkSockets(ModelControllerClient client, PathAddress baseAddress) throws IOException, MgmtOperationException, OperationFailedException { ModelNode result = readChildrenNames(client, baseAddress, SOCKET_BINDING); Assert.assertTrue(result.isDefined()); Assert.assertTrue(result.toString(), result.asInt() > 1); ModelNode op = Util.getReadAttributeOperation(baseAddress.append(SOCKET), PORT); result = executeForResult(op, client); Assert.assertTrue(result.isDefined()); result = new TestExpressionResolver().resolveExpressions(result); Assert.assertEquals(result.toString(), 8080, result.asInt()); } private void updateExcludedProfile(ModelControllerClient client) throws IOException, MgmtOperationException { ModelNode op = Util.getWriteAttributeOperation(PathAddress.pathAddress(PathElement.pathElement(PROFILE, "default"), PathElement.pathElement(SUBSYSTEM, "jmx")), "non-core-mbean-sensitivity", false); executeForResult(op, client); } private void updateExcludedSocketBindingGroup(ModelControllerClient client) throws IOException, MgmtOperationException { ModelNode op = Util.getWriteAttributeOperation(PathAddress.pathAddress(PathElement.pathElement(SOCKET_BINDING_GROUP, "standard-sockets"), PathElement.pathElement(SOCKET_BINDING, "http")), PORT, 8080); executeForResult(op, client); } private static ModelNode readChildrenNames(ModelControllerClient client, PathAddress pathAddress, String childType) throws IOException, MgmtOperationException { ModelNode op = Util.createEmptyOperation(READ_CHILDREN_NAMES_OPERATION, pathAddress); op.get(CHILD_TYPE).set(childType); return executeForResult(op, client); } private void testProfileCloning(ModelControllerClient masterClient, ModelControllerClient slaveClient) throws IOException, MgmtOperationException { ModelNode profiles = readChildrenNames(masterClient, PathAddress.EMPTY_ADDRESS, PROFILE); Assert.assertTrue(profiles.isDefined()); Assert.assertTrue(profiles.toString(), profiles.asInt() > 0); for (ModelNode mn : profiles.asList()) { String profile = mn.asString(); cloneProfile(masterClient, profile); try { checkProfiles(slaveClient); } finally { executeForResult(Util.createRemoveOperation(CLONE_PROFILE), masterClient); } } } private void cloneProfile(ModelControllerClient client, String toClone) throws IOException, MgmtOperationException { ModelNode op = Util.createEmptyOperation(CLONE, PathAddress.pathAddress(PROFILE, toClone)); op.get(TO_PROFILE).set(CLONE); executeForResult(op, client); } private static void restoreSlave() throws TimeoutException, InterruptedException { DomainLifecycleUtil slaveUtil = testSupport.getDomainSlaveLifecycleUtil(); if (!slaveUtil.isHostControllerStarted()) { startSlave(); } } private Set<String> getExtensionsSet() { if (version.getMajor() == 6) { return EXTENSIONS_SET_6X; } else if (version.getMajor() == 7) { return EXTENSIONS_SET_7X; } throw new IllegalStateException("Unknown version " + version); } private static String[] getExcludedExtensions() { if (version.getMajor() == 6) { return EXCLUDED_EXTENSIONS_6X; } else if (version.getMajor() == 7) { return EXCLUDED_EXTENSIONS_7X; } throw new IllegalStateException("Unknown version " + version); } private static class TestExpressionResolver extends ExpressionResolverImpl { public TestExpressionResolver() { } } }
tomazzupan/wildfly
testsuite/mixed-domain/src/test/java/org/jboss/as/test/integration/domain/mixed/DomainHostExcludesTest.java
Java
lgpl-2.1
18,764
/* * eXist Open Source Native XML Database * Copyright (C) 2001-06 Wolfgang M. Meier * wolfgang@exist-db.org * http://exist.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.xquery; import org.exist.dom.QName; import org.exist.xquery.util.ExpressionDumper; import org.exist.xquery.value.Item; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.Type; /** * Implements an XQuery let-expression. * * @author <a href="mailto:wolfgang@exist-db.org">Wolfgang Meier</a> */ public class LetExpr extends BindingExpression { public LetExpr(XQueryContext context) { super(context); } @Override public ClauseType getType() { return ClauseType.LET; } @Override public void analyze(final AnalyzeContextInfo contextInfo) throws XPathException { super.analyze(contextInfo); //Save the local variable stack final LocalVariable mark = context.markLocalVariables(false); try { contextInfo.setParent(this); final AnalyzeContextInfo varContextInfo = new AnalyzeContextInfo(contextInfo); inputSequence.analyze(varContextInfo); //Declare the iteration variable final LocalVariable inVar = new LocalVariable(QName.parse(context, varName, null)); inVar.setSequenceType(sequenceType); inVar.setStaticType(varContextInfo.getStaticReturnType()); context.declareVariableBinding(inVar); //Reset the context position context.setContextSequencePosition(0, null); returnExpr.analyze(contextInfo); } catch (final QName.IllegalQNameException e) { throw new XPathException(ErrorCodes.XPST0081, "No namespace defined for prefix " + varName); } finally { // restore the local variable stack context.popLocalVariables(mark); } } /* (non-Javadoc) * @see org.exist.xquery.Expression#eval(org.exist.xquery.StaticContext, org.exist.dom.persistent.DocumentSet, org.exist.xquery.value.Sequence, org.exist.xquery.value.Item) */ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException { if (context.getProfiler().isEnabled()){ context.getProfiler().start(this); context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies())); if (contextSequence != null) {context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);} if (contextItem != null) {context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());} } context.expressionStart(this); context.pushDocumentContext(); try { //Save the local variable stack LocalVariable mark = context.markLocalVariables(false); Sequence in; LocalVariable var; Sequence resultSequence = null; try { // evaluate input sequence in = inputSequence.eval(contextSequence, null); clearContext(getExpressionId(), in); // Declare the iteration variable var = createVariable(varName); var.setSequenceType(sequenceType); context.declareVariableBinding(var); var.setValue(in); if (sequenceType == null) {var.checkType();} //Just because it makes conversions ! var.setContextDocs(inputSequence.getContextDocSet()); registerUpdateListener(in); resultSequence = returnExpr.eval(contextSequence, null); if (sequenceType != null) { int actualCardinality; if (var.getValue().isEmpty()) {actualCardinality = Cardinality.EMPTY;} else if (var.getValue().hasMany()) {actualCardinality = Cardinality.MANY;} else {actualCardinality = Cardinality.ONE;} //Type.EMPTY is *not* a subtype of other types ; checking cardinality first if (!Cardinality.checkCardinality(sequenceType.getCardinality(), actualCardinality)) {throw new XPathException(this, ErrorCodes.XPTY0004, "Invalid cardinality for variable $" + varName + ". Expected " + Cardinality.getDescription(sequenceType.getCardinality()) + ", got " + Cardinality.getDescription(actualCardinality), in);} //TODO : ignore nodes right now ; they are returned as xs:untypedAtomicType if (!Type.subTypeOf(sequenceType.getPrimaryType(), Type.NODE)) { if (!var.getValue().isEmpty() && !Type.subTypeOf(var.getValue() .getItemType(), sequenceType.getPrimaryType())) { throw new XPathException(this, ErrorCodes.XPTY0004, "Invalid type for variable $" + varName + ". Expected " + Type.getTypeName(sequenceType.getPrimaryType()) + ", got " +Type.getTypeName(var.getValue().getItemType()), in); } //Here is an attempt to process the nodes correctly } else { //Same as above : we probably may factorize if (!var.getValue().isEmpty() && !Type.subTypeOf(var.getValue().getItemType(), sequenceType.getPrimaryType())) {throw new XPathException(this, ErrorCodes.XPTY0004, "Invalid type for variable $" + varName + ". Expected " + Type.getTypeName(sequenceType.getPrimaryType()) + ", got " + Type.getTypeName(var.getValue().getItemType()), in);} } } } finally { // Restore the local variable stack context.popLocalVariables(mark, resultSequence); } clearContext(getExpressionId(), in); if (context.getProfiler().isEnabled()) {context.getProfiler().end(this, "", resultSequence);} if (resultSequence == null) {return Sequence.EMPTY_SEQUENCE;} if (!(resultSequence instanceof DeferredFunctionCall)) { setActualReturnType(resultSequence.getItemType()); } if (getPreviousClause() == null) { resultSequence = postEval(resultSequence); } return resultSequence; } finally { context.popDocumentContext(); context.expressionEnd(this); } } /* (non-Javadoc) * @see org.exist.xquery.Expression#dump(org.exist.xquery.util.ExpressionDumper) */ public void dump(ExpressionDumper dumper) { dumper.display("let ", line); dumper.startIndent(); dumper.display("$").display(varName); dumper.display(" := "); inputSequence.dump(dumper); dumper.endIndent(); //TODO : QuantifiedExpr if (returnExpr instanceof LetExpr) {dumper.display(", ");} else {dumper.nl().display("return ");} dumper.startIndent(); returnExpr.dump(dumper); dumper.endIndent(); } public String toString() { final StringBuilder result = new StringBuilder(); result.append("let "); result.append("$").append(varName); result.append(" := "); result.append(inputSequence.toString()); result.append(" "); //TODO : QuantifiedExpr if (returnExpr instanceof LetExpr) {result.append(", ");} else {result.append("return ");} result.append(returnExpr.toString()); return result.toString(); } public void accept(ExpressionVisitor visitor) { visitor.visitLetExpression(this); } @Override public boolean allowMixedNodesInReturn() { return true; } }
windauer/exist
exist-core/src/main/java/org/exist/xquery/LetExpr.java
Java
lgpl-2.1
9,146
/*- * Copyright (C) 2008 Erik Larsson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.catacombae.io; /** * Interface that defines methods to access a ReadableRandomAccessStream in a thread-safe way. * * @author <a href="https://catacombae.org" target="_top">Erik Larsson</a> */ public interface SynchronizedReadable { /** Atomic seek+read. Does <b>not</b> change the file pointer of the stream permanently! */ public int readFrom(final long pos) throws RuntimeIOException; /** Atomic seek+read. Does <b>not</b> change the file pointer of the stream permanently! */ public int readFrom(final long pos, byte[] b) throws RuntimeIOException; /** Atomic seek+read. Does <b>not</b> change the file pointer of the stream permanently! */ public int readFrom(final long pos, byte[] b, int off, int len) throws RuntimeIOException; /** Atomic seek+read. Does <b>not</b> change the file pointer of the stream permanently! */ public void readFullyFrom(final long pos, byte[] data) throws RuntimeIOException; /** Atomic seek+read. Does <b>not</b> change the file pointer of the stream permanently! */ public void readFullyFrom(final long pos, byte[] data, int offset, int length) throws RuntimeIOException; /** Atomic seek+skip. Does <b>not</b> change the file pointer of the stream permanently! */ public long skipFrom(final long pos, final long length) throws RuntimeIOException; /** Atomic length() - getFilePointer(). */ public long remainingLength() throws RuntimeIOException; }
unsound/catacombaeframework
src/base/java/org/catacombae/io/SynchronizedReadable.java
Java
lgpl-2.1
2,277
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: info@deegree.org ----------------------------------------------------------------------------*/ package org.deegree.io.datastore.sql; import org.deegree.framework.xml.XMLParsingException; import org.deegree.framework.xml.XMLTools; import org.deegree.io.IODocument; import org.deegree.io.JDBCConnection; import org.deegree.io.datastore.AnnotationDocument; import org.deegree.io.datastore.Datastore; import org.w3c.dom.Element; /** * Handles the annotation parsing for SQL based datastores. * * @author <a href="mailto:schneider@lat-lon.de">Markus Schneider </a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class SQLAnnotationDocument extends AnnotationDocument { private static final long serialVersionUID = -6663755656885555966L; private Class<? extends Datastore> datastoreClass; /** * Creates a new instance of {@link SQLAnnotationDocument} for the given datastore class. * * @param datastoreClass */ public SQLAnnotationDocument (Class<? extends Datastore> datastoreClass) { this.datastoreClass = datastoreClass; } @Override public SQLDatastoreConfiguration parseDatastoreConfiguration() throws XMLParsingException { Element appinfoElement = (Element) XMLTools.getRequiredNode( getRootElement(), "xs:annotation/xs:appinfo", nsContext ); IODocument ioDoc = new IODocument( (Element) XMLTools.getRequiredNode( appinfoElement, "dgjdbc:JDBCConnection", nsContext ) ); ioDoc.setSystemId( this.getSystemId() ); JDBCConnection jdbcConnection = ioDoc.parseJDBCConnection(); return new SQLDatastoreConfiguration( jdbcConnection, datastoreClass ); } }
lat-lon/deegree2-base
deegree2-core/src/main/java/org/deegree/io/datastore/sql/SQLAnnotationDocument.java
Java
lgpl-2.1
3,040
// note file for simple notes, to do it from 'message-file-2.js' // // The old file name got as: notes-file.js, but the 's' of 'notes' looks wierd, // dropping it. // // it's an plain text file. But it render as easy and fast to writ and read. // // make_note_file(meta, callback) // - make a note file, save it to s3, callback(err, file_obj) // get_note_file(meta, callback) // - retrieve a old note file, callback(err, file_obj) // // 0221, 2015 var u = require('underscore'); var path = require('path'); var util = require('util'); var md = require("./markdown-file.js"); var bucket = require('./bucket.js'); var ft = require('../myutils/filetype.js'); var myutil = require('../myutils/myutil.js'); var folder5 = require("./folder-v5.js"); var simple = require("./simple-file-v3.js"); //var json_file= require("./json-file.js"); function note_file(file_meta, pass_file_obj){ // // It will be based on plain and simple file, without any other parents, // to be more reliable. // // The content will be utf-8 string, and render out head part of contents // during listing, by default. // // file extension would be: ".ggnotes", or ".ggn". // filetype would be : "goodagood-notes" // if need in future it should get markdown syntax work as well. // // Meta.note : a string, default utf-8 if needed, it's contents. This // makes a separate storage not necessary for small piece of text, but // do it for simple coding at first. // If there is not 'Meta.storage.key', 'Meta.note' can be used anyway. // // var Meta = file_meta; //Meta.filetype = 'goodagood-notes'; //var Editor_prefix = "/edit-note"; var Editor_prefix = "/edit-md"; var File_type = "goodagood-note"; var File_extensions = ['.ggn', '.ggnote']; simple.simple_s3_file_obj(Meta, function(err, fobj){ if(err) return pass_file_obj(err, null); // Now, we have file object and Meta data. Here it get modified // for message files: function get_parent_obj(){ return fobj; } function correct_extension(ext){ ext = ext || '.ggn'; if(ext.search(/\$$/) !== (ext.length -1)) ext += '$'; var pat = RegExp(ext); if(! pat.test(Meta.name)){ Meta.name += File_extensions[0]; Meta.path = path.join(path.dirname(Meta.path), Meta.name); } } function set_filetype(){ Meta.filetype = File_type; } // todo: prepare html ele., render as markdown function set_new_meta(_meta, callback){ Meta = _meta; build_meta(callback); } function build_meta(callback){ set_filetype(); simple.fix_file_meta(Meta); fobj.calculate_meta_defaults(); //prepare_html_elements(); // parent's render will do it. prepare_html_elements(function(err, what){ render_html_repr(function(err, md){ callback(null, Meta); }); }); } function update_storage(str, callback){ if(str.trim() == '') return callback('empty string in "update storage" for note', null); Meta.note = str; fobj.save_file_to_folder().then(function(asw_reply){ callback(null, str); }); } // need test, Sat Feb 21 06:39:35 UTC 2015 // For notes, it naturally short in length, for most notes, it will be // enough to put it in a string. In addition, if codes not change, it // should be ok to just use the string. 'update storage' is enough. function save_note_s3(callback){ // write content to a separate s3 obj var error = 'error in "save content" in "note file": ' + Meta.path; if(Meta.storage.key){ fobj.write_s3_storage(Meta.note, callback); }else{ error = 'where to store the content? ' ; return callback(error, null); } callback(err, null); } function read_to_string(callback){ // @callback is for same with other file type. p('in "read to string", Meta.note: ', Meta.note); if(callback){ return callback(null, Meta.note); } return Meta.note; } // it pass to callback function prepare_html_elements(callback){ fobj.prepare_html_elements(); render_note_as_markdown(function(err, markdonw){ callback(null, Meta.html); }); } // use markdown file to render the note as markdown. function render_note_as_markdown(callback){ if(!Meta.note) return callback('no note?', null); // make a markdown file object from Meta, then use it to render note: md.markdown_file_obj(Meta, function(err, md_file){ Meta.md_renderred = md_file.render_string(Meta.note); callback(null, Meta.md_renderred); }); } function short_note(){ Meta.short_note = Meta.note.slice(0, 15); return Meta.short_note; } function render_html_repr(callback){ // it past by callback // // Results will be saved to Meta.html.li // // Using font awesome. // fobj.render_html_repr(); //parent's way var text = Meta.note; //? Meta.note? if(!text) text = "WoW! note something and nothing."; // first, from whom: var li = '<li class="file ggnote">\n'; li += Meta.html.elements["file-selector"] + "\n"; li += '<i class="fa fa-paperclip"></i>\n'; if ( Meta.timestamp ){ li += util.format('<span class="timestamp" data-timestamp="%s"> %s </span>\n', Meta.timestamp, Meta.timestamp); } //if ( Meta.name ) li += '<span class="note-title">' + Meta.name + '</span>\n'; if( Meta.md_renderred ){ li += '<div class="note-content markdown"> <span class="markdown">' + Meta.md_renderred + '</span></div>\n'; }else{ li += '<div class="note-content"><span class="text">' + text + '</span></div>\n'; } li += '<ul class="file-info-extra"><li>'; // put others into a sub <ul>, 0515 var remove = '<span class="remove"> <i class="fa fa-trash-o"></i>' + util.format('<a href="%s">', Meta['delete_href']) + //'<span class="glyphicon glyphicon-trash"> </span>' + 'Delete</a></span>\n'; li += remove; var editor_link = path.join(Editor_prefix, Meta['path_uuid']); var editor_element = '<span class="editor"> <i class="fa fa-edit"></i>' + util.format('<a href="%s">', editor_link) + 'Edit</a></span>\n'; li += editor_element; li += '</li></ul>'; li += '</li>\n'; if( !Meta.html ) Meta.html = {}; Meta.html.li = li; callback(li); return li; } // Object with new functionalities var new_functions = { version : 'note file, 0224', set_filetype : set_filetype, get_parent_obj : get_parent_obj, set_new_meta : set_new_meta, build_meta : build_meta, save_note_s3 : save_note_s3, prepare_html_elements : prepare_html_elements, render_note_as_markdown : render_note_as_markdown, render_html_repr : render_html_repr, update_storage : update_storage, read_to_string : read_to_string, short_note : short_note, }; // u.extend(fobj, new_functions); //d, this will change the parent obj. // // This make new_functions get default functionalities from the parent // object, and keep fobj as untouched: u.defaults(new_functions, fobj); //if(typeof Meta.html.li === 'undefined') _render_html_repr(); //? pass_file_obj(null, new_functions); // This is callback }); } function json_note(note_json, callback){ // @note_json : object, where 'owner' and 'note' (content) is must. var name = 'note'; var cwd = note_json.owner; var npath= path.join(cwd, name); Meta = u.defaults(note_json, { name : name, title: name, path : npath }); note_file(Meta, function(err, note){ if (err){ p ('what err?'); return this.err = err; } note.build_meta(function(err, nmeta){ p ('err, nmeta: ', err, nmeta); // This gives promise! note.save_file_to_folder().then(function(what){ callback(null, note); }); }); }); } /* * write a note file, to work with the form post: editor.js post md-note * * meta: { * title : * text : * username : * userid : * cwd : * } */ function write_note_0514(meta, callback){ var name; // Try to make a name from meta.title: if (u.isString(meta.title) && meta.title.length > 0) name = meta.title.slice(0,32); if (name){ name = name + '.ggnote'; } else { name = "notes" + Date.now().toString() + '.ggnote'; } p('the name: ', name); var jmeta = u.defaults({}, meta); jmeta.name = name; jmeta.cwd = meta.cwd; jmeta.owner= meta.username; jmeta.id = meta.userid; jmeta.note = meta.text; jmeta.path = path.join(jmeta.cwd, jmeta.name); p('the meta: ', jmeta); note_file(jmeta, function(err, nobj){ if (err){ p ('what err?', err); callback(err, null); } nobj.build_meta (function(err, meta_){ p ('err, meta_: ', err, meta_); nobj.save_file_to_folder().then(function(what){ callback(null, nobj); }).catch(function(err){ callback(err, null); }); }); }); } // do some fast checkings // var p = console.log; function stop(seconds){ seconds = seconds || 1; setTimeout(process.exit, seconds*1000); } function empty_obj(meta){ var name = 'test-note.ggnote'; meta = meta || { name : name , path : 'abc/test/' + name , owner: 'abc' , note: 'just test, at ' + (new Date()).toString() }; note_file(meta, function(err, note){ if (err){ p ('what err?'); return this.err = err; } note.build_meta(function(err, what){ p ('err, element: ', err, what); }); stop(); }); } if (require.main === module){ empty_obj(); } module.exports.note_file = note_file; module.exports.json_note = json_note; module.exports.make_note_file = json_note; module.exports.get_note_file = note_file; module.exports.write_note_0514 = write_note_0514; // vim: set et ts=2 sw=2 fdm=indent:
goodagood/gg
plain/aws/note-file.js
JavaScript
lgpl-2.1
10,202
package org.hibernate.reflection.java; import java.beans.Introspector; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import org.hibernate.reflection.Filter; import org.hibernate.reflection.XProperty; import org.hibernate.reflection.java.generics.TypeEnvironment; import org.hibernate.reflection.java.generics.TypeUtils; /** * @author Paolo Perrotta * @author Davide Marchignoli */ class JavaXProperty extends JavaXMember implements XProperty { static boolean isProperty(Field f, Type boundType, Filter filter) { return isPropertyType( boundType ) && !f.isSynthetic() && ( filter.returnStatic() || ! Modifier.isStatic( f.getModifiers() ) ) && ( filter.returnTransient() || ! Modifier.isTransient( f.getModifiers() ) ); } private static boolean isPropertyType(Type type) { // return TypeUtils.isArray( type ) || TypeUtils.isCollection( type ) || ( TypeUtils.isBase( type ) && ! TypeUtils.isVoid( type ) ); return !TypeUtils.isVoid( type ); } static boolean isProperty(Method m, Type boundType, Filter filter) { return isPropertyType( boundType ) &&!m.isSynthetic() && !m.isBridge() && ( filter.returnStatic() || !Modifier.isStatic( m.getModifiers() ) ) && m.getParameterTypes().length == 0 && ( m.getName().startsWith( "get" ) || m.getName().startsWith( "is" ) ); // TODO should we use stronger checking on the naming of getters/setters, or just leave this to the validator? } static JavaXProperty create(Member member, final TypeEnvironment context, final JavaXFactory factory) { final Type propType = typeOf( member, context ); JavaXType xType = factory.toXType( context, propType ); return new JavaXProperty( member, propType, context, factory, xType ); } private JavaXProperty(Member member, Type type, TypeEnvironment env, JavaXFactory factory, JavaXType xType) { super(member, type, env, factory, xType); assert member instanceof Field || member instanceof Method; } public String getName() { String fullName = getMember().getName(); if ( getMember() instanceof Method ) { if ( fullName.startsWith( "get" ) ) return Introspector.decapitalize( fullName.substring( "get".length() ) ); if ( fullName.startsWith( "is" ) ) return Introspector.decapitalize( fullName.substring( "is".length() ) ); throw new RuntimeException( "Method " + fullName + " is not a property getter" ); } else return fullName; } public Object invoke(Object target, Object... parameters) { if (parameters.length != 0) throw new IllegalArgumentException("An XProperty cannot have invoke parameters"); try { if (getMember() instanceof Method) { return ( (Method) getMember() ).invoke( target ); } else { return ( (Field) getMember() ).get( target ); } } catch (NullPointerException e) { throw new IllegalArgumentException( "Invoking " + getName() + " on a null object", e ); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( "Invoking " + getName() + " with wrong parameters", e ); } catch (Exception e) { throw new IllegalStateException( "Unable to invoke " + getName(), e ); } } @Override public String toString() { return getName(); } }
raedle/univis
lib/hibernate-annotations-3.1beta9/src/org/hibernate/reflection/java/JavaXProperty.java
Java
lgpl-2.1
3,314
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: info@deegree.org ----------------------------------------------------------------------------*/ package org.deegree.portal.standard.digitizer.control; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpSession; import org.deegree.datatypes.Types; import org.deegree.enterprise.control.ajax.AbstractListener; import org.deegree.enterprise.control.ajax.ResponseHandler; import org.deegree.enterprise.control.ajax.WebEvent; import org.deegree.framework.log.ILogger; import org.deegree.framework.log.LoggerFactory; import org.deegree.framework.util.HttpUtils; import org.deegree.framework.util.StringTools; import org.deegree.model.feature.schema.FeatureType; import org.deegree.model.feature.schema.GMLSchema; import org.deegree.model.feature.schema.GMLSchemaDocument; import org.deegree.model.feature.schema.PropertyType; import org.deegree.ogcwebservices.OWSUtils; import org.deegree.ogcwebservices.wfs.capabilities.WFSCapabilities; import org.deegree.ogcwebservices.wfs.operation.DescribeFeatureType; import org.deegree.portal.Constants; import org.deegree.portal.context.DataService; import org.deegree.portal.context.Layer; import org.deegree.portal.context.ViewContext; import org.deegree.portal.standard.digitizer.model.FeatureTypeDescription; import org.deegree.portal.standard.digitizer.model.FeatureTypeProperty; /** * TODO add class documentation here * * @author <a href="mailto:name@deegree.org">Andreas Poth</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class GetFeatureTypeListener extends AbstractListener { private static final ILogger LOG = LoggerFactory.getLogger( GetFeatureTypeListener.class ); private static String baseRequest = "SERVICE=WFS&VERSION=1.1.0&REQUEST=DescribeFeatureType&TYPENAME="; @Override public void actionPerformed( WebEvent event, ResponseHandler responseHandler ) throws IOException { String layerName = (String) event.getParameter().get( "name" ); String url = (String) event.getParameter().get( "url" ); HttpSession session = event.getSession(); ViewContext vc = (ViewContext) session.getAttribute( Constants.CURRENTMAPCONTEXT ); Layer layer = vc.getLayerList().getLayer( layerName, url ); DataService ds = layer.getExtension().getDataService(); FeatureTypeDescription desc = null; try { if ( ds.getServer().getService().toLowerCase().indexOf( "wfs" ) > -1 ) { desc = handleWFS( layer, ds ); } else if ( ds.getServer().getService().toLowerCase().indexOf( "file" ) > -1 ) { // TODO } else if ( ds.getServer().getService().toLowerCase().indexOf( "database" ) > -1 ) { // TODO } } catch ( Exception e ) { handleException( responseHandler, e ); return; } String charEnc = getRequest().getCharacterEncoding(); if ( charEnc == null ) { charEnc = Charset.defaultCharset().displayName(); } responseHandler.setContentType( "application/json; charset=" + charEnc ); responseHandler.writeAndClose( false, desc ); } private FeatureTypeDescription handleWFS( Layer layer, DataService ds ) throws Exception { String url; String featureTypeName = ds.getFeatureType(); String[] tmp = StringTools.toArray( featureTypeName, "{}", false ); String req = baseRequest + "app" + tmp[1] + "&NAMESPACE=xmlns(app=" + tmp[0] + ")"; WFSCapabilities capa = (WFSCapabilities) layer.getExtension().getDataService().getServer().getCapabilities(); url = OWSUtils.getHTTPGetOperationURL( capa, DescribeFeatureType.class ).toExternalForm(); url = HttpUtils.normalizeURL( url ); InputStream is = null; try { is = HttpUtils.performHttpGet( url, req, timeout, null, null, null ).getResponseBodyAsStream(); } catch ( Exception e ) { LOG.logError( e.getMessage(), e ); throw new Exception( "can not load GML schema from: " + url ); } GMLSchema schema = null; try { GMLSchemaDocument xsd = new GMLSchemaDocument(); xsd.load( is, url ); schema = xsd.parseGMLSchema(); } catch ( Exception e ) { LOG.logError( e.getMessage(), e ); throw new Exception( "can not parse GML schema from: " + url ); } FeatureType featureType = schema.getFeatureTypes()[0]; PropertyType[] pts = featureType.getProperties(); List<FeatureTypeProperty> ftps = new ArrayList<FeatureTypeProperty>( pts.length ); FeatureTypeDescription desc = new FeatureTypeDescription(); try { for ( PropertyType propertyType : pts ) { if ( propertyType.getType() != Types.GEOMETRY && propertyType.getType() != Types.FEATURE ) { FeatureTypeProperty ftp = new FeatureTypeProperty(); ftp.setName( propertyType.getName().getLocalName() ); ftp.setNamespace( propertyType.getName().getNamespace().toASCIIString() ); ftp.setType( Types.getTypeNameForSQLTypeCode( propertyType.getType() ) ); ftp.setRepeatable( propertyType.getMaxOccurs() > 1 ); ftp.setOptional( propertyType.getMinOccurs() == 0 ); ftps.add( ftp ); } else if ( propertyType.getType() == Types.GEOMETRY ) { desc.setGeomPropertyName( propertyType.getName().getLocalName() ); desc.setGeomPropertyNamespace( propertyType.getName().getNamespace().toASCIIString() ); } } } catch ( Exception e ) { LOG.logError( e.getMessage(), e ); throw new Exception( "can not create featureType from GML schema: " + url ); } desc.setWfsURL( ds.getServer().getOnlineResource().toExternalForm() ); desc.setName( featureType.getName().getLocalName() ); desc.setNamespace( featureType.getName().getNamespace().toASCIIString() ); desc.setProperties( ftps.toArray( new FeatureTypeProperty[ftps.size()] ) ); desc.setSourceType( "OGC:WFS" ); return desc; } }
lat-lon/deegree2-base
deegree2-core/src/main/java/org/deegree/portal/standard/digitizer/control/GetFeatureTypeListener.java
Java
lgpl-2.1
7,895
/*************************************************************************** * Copyright (c) 2004 Jürgen Riegel <juergen.riegel@web.de> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #endif /// Here the FreeCAD includes sorted by Base,App,Gui...... #include <Base/Parameter.h> #include "ViewProviderBox.h" //#include "Tree.h" using namespace PartGui; using namespace std; //************************************************************************** // Construction/Destruction PROPERTY_SOURCE(PartGui::ViewProviderBox, PartGui::ViewProviderPart) ViewProviderBox::ViewProviderBox() { sPixmap = "PartFeatureImport"; } ViewProviderBox::~ViewProviderBox() { } // ********************************************************************************** std::vector<std::string> ViewProviderBox::getDisplayModes(void) const { // get the modes of the father std::vector<std::string> StrList; // add your own modes StrList.push_back("Flat Lines"); StrList.push_back("Shaded"); StrList.push_back("Wireframe"); StrList.push_back("Points"); return StrList; }
JonasThomas/free-cad
src/Mod/Part/Gui/ViewProviderBox.cpp
C++
lgpl-2.1
2,643
/** * @file Cosa/Board/PJRC/Teensy_2_0.hh * @version 1.0 * * @section License * Copyright (C) 2014-2015, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * This file is part of the Arduino Che Cosa project. */ #ifndef COSA_BOARD_PJRC_TEENSY_2_0_HH #define COSA_BOARD_PJRC_TEENSY_2_0_HH /* This board is based on ATmega32U4 */ #define BOARD_ATMEGA32U4 /** * Compiler warning on unused varable. */ #if !defined(UNUSED) #define UNUSED(x) (void) (x) #endif /** * Cosa pin symbol definitions for the PJRC Teensy 2.0, ATmega32U4 * based board. Cosa does not use pin numbers as Arduino/Wiring, * instead strong data type is used (enum types) for the specific pin * classes; DigitalPin, AnalogPin, PWMPin, etc. * * The pin numbers for Teensy 2.0 are only symbolically mapped, * i.e. a pin number/digit will not work, symbols must be used, * e.g., Board::D12. Avoid iterations assuming that the symbols * are in order. * * The static inline functions, SFR, BIT and UART, rely on compiler * optimizations to be reduced. * * @section Board * @code * Teensy 2.0 * ----- * +----| V |----+ * GND |o | | o| VCC * D0 |o ----- o| D21/A0 * D1 |o o| D20/A1 * D2 |o o| D19/A2 * D3 |o o o o| D18/A3 * PWM0/D4 |o D24 AREF o| D17/A4 * EXT0/PWM1/D5 |o o| D16/A5 * EXT1/D6 |o o| D15/A6/PWM3 * RX/EXT2/D7 |o o| D14/A7/PWM2 * TX/EXT3/D8 |o o| D13/A8 * PWM4/D9 |o ( ) o| D12/A9/PWM6 * PWM5/D10 |o o o o o o o| D11/A10/LED * +-------------+ * / / | \ \ * D23 VCC GND RST D22/A11 * @endcode */ class Board { friend class Pin; friend class UART; private: /** * Do not allow instances. This is a static singleton; name space. */ Board() {} /** * Return Special Function Register for given Teensy pin number. * @param[in] pin number. * @return special register pointer. */ static volatile uint8_t* SFR(uint8_t pin) __attribute__((always_inline)) { return (pin < 8 ? &PINB : pin < 16 ? &PINC : pin < 24 ? &PIND : pin < 32 ? &PINE : &PINF); } /** * Return bit position for given Teensy pin number in Special * Function Register. * @param[in] pin number. * @return pin bit position. */ static uint8_t BIT(uint8_t pin) __attribute__((always_inline)) { return (pin & 0x07); } /** * Return Pin Change Mask Register for given Teensy pin number. * @param[in] pin number. * @return pin change mask register pointer. */ static volatile uint8_t* PCIMR(uint8_t pin) __attribute__((always_inline)) { UNUSED(pin); return (&PCMSK0); } /** * Return UART Register for given Teensy serial port. * @param[in] port number. * @return UART register pointer. */ static volatile uint8_t* UART(uint8_t port) __attribute__((always_inline)) { UNUSED(port); return (&UCSR1A); } public: /** * Initiate board ports. Default void. */ static void init() {} /** * Digital pin symbols */ enum DigitalPin { D0 = 0, // PB0 D1 = 1, // PB1 D2 = 2, // PB2 D3 = 3, // PB3 D4 = 7, // PB7 D5 = 16, // PD0 D6 = 17, // PD1 D7 = 18, // PD2 D8 = 19, // PD3 D9 = 14, // PC6 D10 = 15, // PC7 D11 = 22, // PD6 D12 = 23, // PD7 D13 = 4, // PB4 D14 = 5, // PB5 D15 = 6, // PB6 D16 = 39, // PF7 D17 = 38, // PF6 D18 = 37, // PF5 D19 = 36, // PF4 D20 = 33, // PF1 D21 = 32, // PF0 D22 = 20, // PD4 D23 = 21, // PD5 D24 = 30, // PE6 LED = D11 } __attribute__((packed)); /** * Analog pin symbols (ADC channel numbers) */ enum AnalogPin { A0 = 0, // PF0/ADC0 A1 = 1, // PF1/ADC1 A2 = 4, // PF4/ADC4 A3 = 5, // PF5/ADC5 A4 = 6, // PF6/ADC6 A5 = 7, // PF7/ADC7 A6 = 37, // PB6/ADC13 A7 = 36, // PB5/ADC12 A8 = 35, // PB4/ADC11 A9 = 34, // PD7/ADC10 A10 = 33, // PD6/ADC9 A11 = 32 // PD4/ADC8 } __attribute__((packed)); /** * Reference voltage; ARef pin, Vcc or internal 2V56 */ enum Reference { APIN_REFERENCE = 0, AVCC_REFERENCE = _BV(REFS0), A2V56_REFERENCE = (_BV(REFS1) | _BV(REFS0)) } __attribute__((packed)); /** * PWM pin symbols; sub-set of digital pins to allow compile * time checking */ enum PWMPin { PWM0 = D4, // PB7 => OCR0A PWM1 = D5, // PD0 => OCR0B PWM2 = D14, // PB5 => OCR1A PWM3 = D15, // PB6 => OCR1B PWM4 = D9, // PC6 => OCR3A PWM5 = D10, // PC7 => OCR4A PWM6 = D12 // PD7 => OCR4D } __attribute__((packed)); /** * External interrupt pin symbols; sub-set of digital pins * to allow compile time checking. */ enum ExternalInterruptPin { EXT0 = D5, // PD0 EXT1 = D6, // PD1 EXT2 = D7, // PD2 EXT3 = D8 // PD3 } __attribute__((packed)); /** * Pin change interrupt (PCI) pins. Number of port registers. */ enum InterruptPin { PCI0 = D0, // PB0 PCI1 = D1, // PB1 PCI2 = D2, // PB2 PCI3 = D3, // PB3 PCI4 = D13, // PB4 PCI5 = D14, // PB5 PCI6 = D15, // PB6 PCI7 = D4 // PB7 } __attribute__((packed)); /** * Size of pin maps. */ enum { ANALOG_PIN_MAX = 12, DIGITAL_PIN_MAX = 25, EXT_PIN_MAX = 4, PCI_PIN_MAX = 8, PWM_PIN_MAX = 7 }; /** * Pins used for TWI interface (port D, bit 0-1, D5-D6) */ enum TWIPin { SDA = 1, // PD1/D6 SCL = 0 // PD0/D5 } __attribute__((packed)); /** * Pins used for SPI interface (port B, bit 0-3, D0-D3) */ enum SPIPin { SS = 0, // PB0/D0 SCK = 1, // PB1/D1 MOSI = 2, // PB2/D2 MISO = 3 // PB3/D3 } __attribute__((packed)); /** * Auxiliary */ enum { VBG = (_BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1)), UART_MAX = 2, EXT_MAX = 7, PCMSK_MAX = 1, PCINT_MAX = 8 } __attribute__((packed)); }; /** * Redefined symbols to allow generic code. */ #define UCSZ00 UCSZ10 #define UCSZ01 UCSZ11 #define UCSZ02 UCSZ12 #define UPM00 UPM10 #define UPM01 UPM11 #define USBS0 USBS1 #define U2X0 U2X1 #define RXCIE0 RXCIE1 #define RXEN0 RXEN1 #define TXEN0 TXEN1 #define UDRIE0 UDRIE1 #define TXCIE0 TXCIE1 #if !defined(ADCW) #define ADCW ADC #endif /** * Forward declare interrupt service routines to allow them as friends. */ extern "C" { void ADC_vect(void) __attribute__ ((signal)); void ANALOG_COMP_vect(void) __attribute__ ((signal)); void INT0_vect(void) __attribute__ ((signal)); void INT1_vect(void) __attribute__ ((signal)); void INT2_vect(void) __attribute__ ((signal)); void INT3_vect(void) __attribute__ ((signal)); void INT6_vect(void) __attribute__ ((signal)); void PCINT0_vect(void) __attribute__ ((signal)); void SPI_STC_vect(void) __attribute__ ((signal)); void TIMER0_COMPA_vect(void) __attribute__ ((signal)); void TIMER0_COMPB_vect(void) __attribute__ ((signal)); void TIMER0_OVF_vect(void) __attribute__ ((signal)); void TIMER1_CAPT_vect(void) __attribute__ ((signal)); void TIMER1_COMPA_vect(void) __attribute__ ((signal)); void TIMER1_COMPB_vect(void) __attribute__ ((signal)); void TIMER1_COMPC_vect(void) __attribute__ ((signal)); void TIMER1_OVF_vect(void) __attribute__ ((signal)); void TIMER3_CAPT_vect(void) __attribute__ ((signal)); void TIMER3_COMPA_vect(void) __attribute__ ((signal)); void TIMER3_COMPB_vect(void) __attribute__ ((signal)); void TIMER3_COMPC_vect(void) __attribute__ ((signal)); void TIMER3_OVF_vect(void) __attribute__ ((signal)); void TIMER4_COMPA_vect(void) __attribute__ ((signal)); void TIMER4_COMPB_vect(void) __attribute__ ((signal)); void TIMER4_COMPD_vect(void) __attribute__ ((signal)); void TIMER4_FPF_vect(void) __attribute__ ((signal)); void TIMER4_OVF_vect(void) __attribute__ ((signal)); void TWI_vect(void) __attribute__ ((signal)); void WDT_vect(void) __attribute__ ((signal)); void USART1_RX_vect(void) __attribute__ ((signal)); void USART1_TX_vect(void) __attribute__ ((signal)); void USART1_UDRE_vect(void) __attribute__ ((signal)); void USB_COM_vect(void) __attribute__ ((signal)); void USB_GEN_vect(void) __attribute__ ((signal)); } #endif
kc9jud/Cosa
cores/cosa/Cosa/Board/PJRC/Teensy_2_0.hh
C++
lgpl-2.1
8,986
/******************************************************************************* * Copyright (c) 2000, 2011 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 org.eclipse.swt.widgets; import org.eclipse.swt.internal.win32.*; import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; /** * Instances of this class provide the appearance and * behavior of <code>Shells</code>, but are not top * level shells or dialogs. Class <code>Shell</code> * shares a significant amount of code with this class, * and is a subclass. * <p> * IMPORTANT: This class was intended to be abstract and * should <em>never</em> be referenced or instantiated. * Instead, the class <code>Shell</code> should be used. * </p> * <p> * Instances are always displayed in one of the maximized, * minimized or normal states: * <ul> * <li> * When an instance is marked as <em>maximized</em>, the * window manager will typically resize it to fill the * entire visible area of the display, and the instance * is usually put in a state where it can not be resized * (even if it has style <code>RESIZE</code>) until it is * no longer maximized. * </li><li> * When an instance is in the <em>normal</em> state (neither * maximized or minimized), its appearance is controlled by * the style constants which were specified when it was created * and the restrictions of the window manager (see below). * </li><li> * When an instance has been marked as <em>minimized</em>, * its contents (client area) will usually not be visible, * and depending on the window manager, it may be * "iconified" (that is, replaced on the desktop by a small * simplified representation of itself), relocated to a * distinguished area of the screen, or hidden. Combinations * of these changes are also possible. * </li> * </ul> * </p> * Note: The styles supported by this class must be treated * as <em>HINT</em>s, since the window manager for the * desktop on which the instance is visible has ultimate * control over the appearance and behavior of decorations. * For example, some window managers only support resizable * windows and will always assume the RESIZE style, even if * it is not set. * <dl> * <dt><b>Styles:</b></dt> * <dd>BORDER, CLOSE, MIN, MAX, NO_TRIM, RESIZE, TITLE, ON_TOP, TOOL</dd> * <dt><b>Events:</b></dt> * <dd>(none)</dd> * </dl> * Class <code>SWT</code> provides two "convenience constants" * for the most commonly required style combinations: * <dl> * <dt><code>SHELL_TRIM</code></dt> * <dd> * the result of combining the constants which are required * to produce a typical application top level shell: (that * is, <code>CLOSE | TITLE | MIN | MAX | RESIZE</code>) * </dd> * <dt><code>DIALOG_TRIM</code></dt> * <dd> * the result of combining the constants which are required * to produce a typical application dialog shell: (that * is, <code>TITLE | CLOSE | BORDER</code>) * </dd> * </dl> * <p> * IMPORTANT: This class is intended to be subclassed <em>only</em> * within the SWT implementation. * </p> * * @see #getMinimized * @see #getMaximized * @see Shell * @see SWT * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a> * @noextend This class is not intended to be subclassed by clients. */ public class Decorations extends Canvas { Image image, smallImage, largeImage; Image [] images; Menu menuBar; Menu [] menus; Control savedFocus; Button defaultButton, saveDefault; int swFlags, nAccel; int /*long*/ hAccel; boolean moved, resized, opened; int oldX = OS.CW_USEDEFAULT, oldY = OS.CW_USEDEFAULT; int oldWidth = OS.CW_USEDEFAULT, oldHeight = OS.CW_USEDEFAULT; RECT maxRect = new RECT(); /** * Prevents uninitialized instances from being created outside the package. */ Decorations () { } /** * Constructs a new instance of this class given its parent * and a style value describing its behavior and appearance. * <p> * The style value is either one of the style constants defined in * class <code>SWT</code> which is applicable to instances of this * class, or must be built by <em>bitwise OR</em>'ing together * (that is, using the <code>int</code> "|" operator) two or more * of those <code>SWT</code> style constants. The class description * lists the style constants that are applicable to the class. * Style bits are also inherited from superclasses. * </p> * * @param parent a composite control which will be the parent of the new instance (cannot be null) * @param style the style of control to construct * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the parent is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li> * <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li> * </ul> * * @see SWT#BORDER * @see SWT#CLOSE * @see SWT#MIN * @see SWT#MAX * @see SWT#RESIZE * @see SWT#TITLE * @see SWT#NO_TRIM * @see SWT#SHELL_TRIM * @see SWT#DIALOG_TRIM * @see SWT#ON_TOP * @see SWT#TOOL * @see Widget#checkSubclass * @see Widget#getStyle */ public Decorations (Composite parent, int style) { super (parent, checkStyle (style)); } void _setMaximized (boolean maximized) { swFlags = maximized ? OS.SW_SHOWMAXIMIZED : OS.SW_RESTORE; if (OS.IsWinCE) { /* * Note: WinCE does not support SW_SHOWMAXIMIZED and SW_RESTORE. The * workaround is to resize the window to fit the parent client area. */ if (maximized) { RECT rect = new RECT (); OS.SystemParametersInfo (OS.SPI_GETWORKAREA, 0, rect, 0); int width = rect.right - rect.left, height = rect.bottom - rect.top; if (OS.IsPPC) { /* Leave space for the menu bar */ if (menuBar != null) { int /*long*/ hwndCB = menuBar.hwndCB; RECT rectCB = new RECT (); OS.GetWindowRect (hwndCB, rectCB); height -= rectCB.bottom - rectCB.top; } } int flags = OS.SWP_NOZORDER | OS.SWP_DRAWFRAME | OS.SWP_NOACTIVATE; SetWindowPos (handle, 0, rect.left, rect.top, width, height, flags); } } else { if (!OS.IsWindowVisible (handle)) return; if (maximized == OS.IsZoomed (handle)) return; OS.ShowWindow (handle, swFlags); OS.UpdateWindow (handle); } } void _setMinimized (boolean minimized) { if (OS.IsWinCE) return; swFlags = minimized ? OS.SW_SHOWMINNOACTIVE : OS.SW_RESTORE; if (!OS.IsWindowVisible (handle)) return; if (minimized == OS.IsIconic (handle)) return; int flags = swFlags; if (flags == OS.SW_SHOWMINNOACTIVE && handle == OS.GetActiveWindow ()) { flags = OS.SW_MINIMIZE; } OS.ShowWindow (handle, flags); OS.UpdateWindow (handle); } void addMenu (Menu menu) { if (menus == null) menus = new Menu [4]; for (int i=0; i<menus.length; i++) { if (menus [i] == null) { menus [i] = menu; return; } } Menu [] newMenus = new Menu [menus.length + 4]; newMenus [menus.length] = menu; System.arraycopy (menus, 0, newMenus, 0, menus.length); menus = newMenus; } void bringToTop () { /* * This code is intentionally commented. On some platforms, * the ON_TOP style creates a shell that will stay on top * of every other shell on the desktop. Using SetWindowPos () * with HWND_TOP caused problems on Windows 98 so this code is * commented out until this functionality is specified and * the problems are fixed. */ // if ((style & SWT.ON_TOP) != 0) { // int flags = OS.SWP_NOSIZE | OS.SWP_NOMOVE | OS.SWP_NOACTIVATE; // OS.SetWindowPos (handle, OS.HWND_TOP, 0, 0, 0, 0, flags); // } else { OS.BringWindowToTop (handle); // widget could be disposed at this point // } } static int checkStyle (int style) { if ((style & SWT.NO_TRIM) != 0) { style &= ~(SWT.CLOSE | SWT.TITLE | SWT.MIN | SWT.MAX | SWT.RESIZE | SWT.BORDER); } if (OS.IsWinCE) { /* * Feature in WinCE PPC. WS_MINIMIZEBOX or WS_MAXIMIZEBOX * are not supposed to be used. If they are, the result * is a button which does not repaint correctly. The fix * is to remove this style. */ if ((style & SWT.MIN) != 0) style &= ~SWT.MIN; if ((style & SWT.MAX) != 0) style &= ~SWT.MAX; return style; } if ((style & (SWT.MENU | SWT.MIN | SWT.MAX | SWT.CLOSE)) != 0) { style |= SWT.TITLE; } /* * If either WS_MINIMIZEBOX or WS_MAXIMIZEBOX are set, * we must also set WS_SYSMENU or the buttons will not * appear. */ if ((style & (SWT.MIN | SWT.MAX)) != 0) style |= SWT.CLOSE; /* * Both WS_SYSMENU and WS_CAPTION must be set in order * to for the system menu to appear. */ if ((style & SWT.CLOSE) != 0) style |= SWT.TITLE; /* * Bug in Windows. The WS_CAPTION style must be * set when the window is resizable or it does not * draw properly. */ /* * This code is intentionally commented. It seems * that this problem originally in Windows 3.11, * has been fixed in later versions. Because the * exact nature of the drawing problem is unknown, * keep the commented code around in case it comes * back. */ // if ((style & SWT.RESIZE) != 0) style |= SWT.TITLE; return style; } void checkBorder () { /* Do nothing */ } void checkComposited (Composite parent) { /* Do nothing */ } void checkOpened () { if (!opened) resized = false; } protected void checkSubclass () { if (!isValidSubclass ()) error (SWT.ERROR_INVALID_SUBCLASS); } int /*long*/ callWindowProc (int /*long*/ hwnd, int msg, int /*long*/ wParam, int /*long*/ lParam) { if (handle == 0) return 0; return OS.DefMDIChildProc (hwnd, msg, wParam, lParam); } void closeWidget () { Event event = new Event (); sendEvent (SWT.Close, event); if (event.doit && !isDisposed ()) dispose (); } int compare (ImageData data1, ImageData data2, int width, int height, int depth) { int value1 = Math.abs (data1.width - width), value2 = Math.abs (data2.width - width); if (value1 == value2) { int transparent1 = data1.getTransparencyType (); int transparent2 = data2.getTransparencyType (); if (transparent1 == transparent2) { if (data1.depth == data2.depth) return 0; return data1.depth > data2.depth && data1.depth <= depth ? -1 : 1; } if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (5, 1)) { if (transparent1 == SWT.TRANSPARENCY_ALPHA) return -1; if (transparent2 == SWT.TRANSPARENCY_ALPHA) return 1; } if (transparent1 == SWT.TRANSPARENCY_MASK) return -1; if (transparent2 == SWT.TRANSPARENCY_MASK) return 1; if (transparent1 == SWT.TRANSPARENCY_PIXEL) return -1; if (transparent2 == SWT.TRANSPARENCY_PIXEL) return 1; return 0; } return value1 < value2 ? -1 : 1; } Widget computeTabGroup () { return this; } Control computeTabRoot () { return this; } public Rectangle computeTrim (int x, int y, int width, int height) { checkWidget (); /* Get the size of the trimmings */ RECT rect = new RECT (); OS.SetRect (rect, x, y, x + width, y + height); int bits1 = OS.GetWindowLong (handle, OS.GWL_STYLE); int bits2 = OS.GetWindowLong (handle, OS.GWL_EXSTYLE); boolean hasMenu = OS.IsWinCE ? false : OS.GetMenu (handle) != 0; OS.AdjustWindowRectEx (rect, bits1, hasMenu, bits2); /* Get the size of the scroll bars */ if (horizontalBar != null) rect.bottom += OS.GetSystemMetrics (OS.SM_CYHSCROLL); if (verticalBar != null) rect.right += OS.GetSystemMetrics (OS.SM_CXVSCROLL); /* Compute the height of the menu bar */ if (hasMenu) { RECT testRect = new RECT (); OS.SetRect (testRect, 0, 0, rect.right - rect.left, rect.bottom - rect.top); OS.SendMessage (handle, OS.WM_NCCALCSIZE, 0, testRect); while ((testRect.bottom - testRect.top) < height) { if (testRect.bottom - testRect.top == 0) break; rect.top -= OS.GetSystemMetrics (OS.SM_CYMENU) - OS.GetSystemMetrics (OS.SM_CYBORDER); OS.SetRect (testRect, 0, 0, rect.right - rect.left, rect.bottom - rect.top); OS.SendMessage (handle, OS.WM_NCCALCSIZE, 0, testRect); } } return new Rectangle (rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); } void createAccelerators () { hAccel = nAccel = 0; int maxAccel = 0; MenuItem [] items = display.items; if (menuBar == null || items == null) { if (!OS.IsPPC) return; maxAccel = 1; } else { maxAccel = OS.IsPPC ? items.length + 1 : items.length; } ACCEL accel = new ACCEL (); byte [] buffer1 = new byte [ACCEL.sizeof]; byte [] buffer2 = new byte [maxAccel * ACCEL.sizeof]; if (menuBar != null && items != null) { for (int i=0; i<items.length; i++) { MenuItem item = items [i]; if (item != null && item.accelerator != 0) { Menu menu = item.parent; if (menu.parent == this) { while (menu != null && menu != menuBar) { menu = menu.getParentMenu (); } if (menu == menuBar && item.fillAccel (accel)) { OS.MoveMemory (buffer1, accel, ACCEL.sizeof); System.arraycopy (buffer1, 0, buffer2, nAccel * ACCEL.sizeof, ACCEL.sizeof); nAccel++; } } } } } if (OS.IsPPC) { /* * Note on WinCE PPC. Close the shell when user taps CTRL-Q. * IDOK represents the "Done Button" which also closes the shell. */ accel.fVirt = (byte) (OS.FVIRTKEY | OS.FCONTROL); accel.key = (short) 'Q'; accel.cmd = (short) OS.IDOK; OS.MoveMemory (buffer1, accel, ACCEL.sizeof); System.arraycopy (buffer1, 0, buffer2, nAccel * ACCEL.sizeof, ACCEL.sizeof); nAccel++; } if (nAccel != 0) hAccel = OS.CreateAcceleratorTable (buffer2, nAccel); } void createHandle () { super.createHandle (); if (parent != null || ((style & SWT.TOOL) != 0)) { setParent (); setSystemMenu (); } } void createWidget () { super.createWidget (); swFlags = OS.IsWinCE ? OS.SW_SHOWMAXIMIZED : OS.SW_SHOWNOACTIVATE; hAccel = -1; } void destroyAccelerators () { if (hAccel != 0 && hAccel != -1) OS.DestroyAcceleratorTable (hAccel); hAccel = -1; } public void dispose () { if (isDisposed()) return; if (!isValidThread ()) error (SWT.ERROR_THREAD_INVALID_ACCESS); if (!(this instanceof Shell)) { if (!traverseDecorations (true)) { Shell shell = getShell (); shell.setFocus (); } setVisible (false); } super.dispose (); } Menu findMenu (int /*long*/ hMenu) { if (menus == null) return null; for (int i=0; i<menus.length; i++) { Menu menu = menus [i]; if (menu != null && hMenu == menu.handle) return menu; } return null; } void fixDecorations (Decorations newDecorations, Control control, Menu [] menus) { if (this == newDecorations) return; if (control == savedFocus) savedFocus = null; if (control == defaultButton) defaultButton = null; if (control == saveDefault) saveDefault = null; if (menus == null) return; Menu menu = control.menu; if (menu != null) { int index = 0; while (index <menus.length) { if (menus [index] == menu) { control.setMenu (null); return; } index++; } menu.fixMenus (newDecorations); destroyAccelerators (); newDecorations.destroyAccelerators (); } } public Rectangle getBounds () { checkWidget (); if (!OS.IsWinCE) { if (OS.IsIconic (handle)) { WINDOWPLACEMENT lpwndpl = new WINDOWPLACEMENT (); lpwndpl.length = WINDOWPLACEMENT.sizeof; OS.GetWindowPlacement (handle, lpwndpl); if ((lpwndpl.flags & OS.WPF_RESTORETOMAXIMIZED) != 0) { int width = maxRect.right - maxRect.left; int height = maxRect.bottom - maxRect.top; return new Rectangle (maxRect.left, maxRect.top, width, height); } int width = lpwndpl.right - lpwndpl.left; int height = lpwndpl.bottom - lpwndpl.top; return new Rectangle (lpwndpl.left, lpwndpl.top, width, height); } } return super.getBounds (); } public Rectangle getClientArea () { checkWidget (); /* * Note: The CommandBar is part of the client area, * not the trim. Applications don't expect this so * subtract the height of the CommandBar. */ if (OS.IsHPC) { Rectangle rect = super.getClientArea (); if (menuBar != null) { int /*long*/ hwndCB = menuBar.hwndCB; int height = OS.CommandBar_Height (hwndCB); rect.y += height; rect.height = Math.max (0, rect.height - height); } return rect; } if (!OS.IsWinCE) { if (OS.IsIconic (handle)) { WINDOWPLACEMENT lpwndpl = new WINDOWPLACEMENT (); lpwndpl.length = WINDOWPLACEMENT.sizeof; OS.GetWindowPlacement (handle, lpwndpl); if ((lpwndpl.flags & OS.WPF_RESTORETOMAXIMIZED) != 0) { return new Rectangle (0, 0, oldWidth, oldHeight); } int width = lpwndpl.right - lpwndpl.left; int height = lpwndpl.bottom - lpwndpl.top; /* * Feature in Windows. For some reason WM_NCCALCSIZE does * not compute the client area when the window is minimized. * The fix is to compute it using AdjustWindowRectEx() and * GetSystemMetrics(). * * NOTE: This code fails to compute the correct client area * for a minimized window where the menu bar would wrap were * the window restored. There is no fix for this problem at * this time. */ if (horizontalBar != null) width -= OS.GetSystemMetrics (OS.SM_CYHSCROLL); if (verticalBar != null) height -= OS.GetSystemMetrics (OS.SM_CXVSCROLL); RECT rect = new RECT (); int bits1 = OS.GetWindowLong (handle, OS.GWL_STYLE); int bits2 = OS.GetWindowLong (handle, OS.GWL_EXSTYLE); boolean hasMenu = OS.IsWinCE ? false : OS.GetMenu (handle) != 0; OS.AdjustWindowRectEx (rect, bits1, hasMenu, bits2); width = Math.max (0, width - (rect.right - rect.left)); height = Math.max (0, height - (rect.bottom - rect.top)); return new Rectangle (0, 0, width, height); } } return super.getClientArea (); } /** * Returns the receiver's default button if one had * previously been set, otherwise returns null. * * @return the default button or null * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #setDefaultButton(Button) */ public Button getDefaultButton () { checkWidget (); if (defaultButton != null && defaultButton.isDisposed ()) return null; return defaultButton; } /** * Returns the receiver's image if it had previously been * set using <code>setImage()</code>. The image is typically * displayed by the window manager when the instance is * marked as iconified, and may also be displayed somewhere * in the trim when the instance is in normal or maximized * states. * <p> * Note: This method will return null if called before * <code>setImage()</code> is called. It does not provide * access to a window manager provided, "default" image * even if one exists. * </p> * * @return the image * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Image getImage () { checkWidget (); return image; } /** * Returns the receiver's images if they had previously been * set using <code>setImages()</code>. Images are typically * displayed by the window manager when the instance is * marked as iconified, and may also be displayed somewhere * in the trim when the instance is in normal or maximized * states. Depending where the icon is displayed, the platform * chooses the icon with the "best" attributes. It is expected * that the array will contain the same icon rendered at different * sizes, with different depth and transparency attributes. * * <p> * Note: This method will return an empty array if called before * <code>setImages()</code> is called. It does not provide * access to a window manager provided, "default" image * even if one exists. * </p> * * @return the images * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.0 */ public Image [] getImages () { checkWidget (); if (images == null) return new Image [0]; Image [] result = new Image [images.length]; System.arraycopy (images, 0, result, 0, images.length); return result; } public Point getLocation () { checkWidget (); if (!OS.IsWinCE) { if (OS.IsIconic (handle)) { WINDOWPLACEMENT lpwndpl = new WINDOWPLACEMENT (); lpwndpl.length = WINDOWPLACEMENT.sizeof; OS.GetWindowPlacement (handle, lpwndpl); if ((lpwndpl.flags & OS.WPF_RESTORETOMAXIMIZED) != 0) { return new Point (maxRect.left, maxRect.top); } return new Point (lpwndpl.left, lpwndpl.top); } } return super.getLocation (); } /** * Returns <code>true</code> if the receiver is currently * maximized, and false otherwise. * <p> * * @return the maximized state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #setMaximized */ public boolean getMaximized () { checkWidget (); if (OS.IsWinCE) return swFlags == OS.SW_SHOWMAXIMIZED; if (OS.IsWindowVisible (handle)) return OS.IsZoomed (handle); return swFlags == OS.SW_SHOWMAXIMIZED; } /** * Returns the receiver's menu bar if one had previously * been set, otherwise returns null. * * @return the menu bar or null * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public Menu getMenuBar () { checkWidget (); return menuBar; } /** * Returns <code>true</code> if the receiver is currently * minimized, and false otherwise. * <p> * * @return the minimized state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #setMinimized */ public boolean getMinimized () { checkWidget (); if (OS.IsWinCE) return false; if (OS.IsWindowVisible (handle)) return OS.IsIconic (handle); return swFlags == OS.SW_SHOWMINNOACTIVE; } String getNameText () { return getText (); } public Point getSize () { checkWidget (); if (!OS.IsWinCE) { if (OS.IsIconic (handle)) { WINDOWPLACEMENT lpwndpl = new WINDOWPLACEMENT (); lpwndpl.length = WINDOWPLACEMENT.sizeof; OS.GetWindowPlacement (handle, lpwndpl); if ((lpwndpl.flags & OS.WPF_RESTORETOMAXIMIZED) != 0) { int width = maxRect.right - maxRect.left; int height = maxRect.bottom - maxRect.top; return new Point (width, height); } int width = lpwndpl.right - lpwndpl.left; int height = lpwndpl.bottom - lpwndpl.top; return new Point (width, height); } } return super.getSize (); } /** * Returns the receiver's text, which is the string that the * window manager will typically display as the receiver's * <em>title</em>. If the text has not previously been set, * returns an empty string. * * @return the text * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public String getText () { checkWidget (); int length = OS.GetWindowTextLength (handle); if (length == 0) return ""; /* Use the character encoding for the default locale */ TCHAR buffer = new TCHAR (0, length + 1); OS.GetWindowText (handle, buffer, length + 1); return buffer.toString (0, length); } public boolean isReparentable () { checkWidget (); /* * Feature in Windows. Calling SetParent() for a shell causes * a kind of fake MDI to happen. It doesn't work well on Windows * and is not supported on the other platforms. The fix is to * disallow the SetParent(). */ return false; } boolean isTabGroup () { /* * Can't test WS_TAB bits because they are the same as WS_MAXIMIZEBOX. */ return true; } boolean isTabItem () { /* * Can't test WS_TAB bits because they are the same as WS_MAXIMIZEBOX. */ return false; } Decorations menuShell () { return this; } void releaseChildren (boolean destroy) { if (menuBar != null) { menuBar.release (false); menuBar = null; } super.releaseChildren (destroy); if (menus != null) { for (int i=0; i<menus.length; i++) { Menu menu = menus [i]; if (menu != null && !menu.isDisposed ()) { menu.dispose (); } } menus = null; } } void releaseWidget () { super.releaseWidget (); if (smallImage != null) smallImage.dispose (); if (largeImage != null) largeImage.dispose (); smallImage = largeImage = image = null; images = null; savedFocus = null; defaultButton = saveDefault = null; if (hAccel != 0 && hAccel != -1) OS.DestroyAcceleratorTable (hAccel); hAccel = -1; } void removeMenu (Menu menu) { if (menus == null) return; for (int i=0; i<menus.length; i++) { if (menus [i] == menu) { menus [i] = null; return; } } } void reskinChildren (int flags) { if (menuBar != null) menuBar.reskin (flags); if (menus != null) { for (int i=0; i<menus.length; i++) { Menu menu = menus [i]; if (menu != null) menu.reskin (flags); } } super.reskinChildren (flags); } boolean restoreFocus () { if (display.ignoreRestoreFocus) return true; if (savedFocus != null && savedFocus.isDisposed ()) savedFocus = null; if (savedFocus != null && savedFocus.setSavedFocus ()) return true; /* * This code is intentionally commented. When no widget * has been given focus, some platforms give focus to the * default button. Windows doesn't do this. */ // if (defaultButton != null && !defaultButton.isDisposed ()) { // if (defaultButton.setFocus ()) return true; // } return false; } void saveFocus () { Control control = display._getFocusControl (); if (control != null && control != this && this == control.menuShell ()) { setSavedFocus (control); } } void setBounds (int x, int y, int width, int height, int flags, boolean defer) { swFlags = OS.SW_SHOWNOACTIVATE; if (OS.IsWinCE) { swFlags = OS.SW_RESTORE; } else { if (OS.IsIconic (handle)) { setPlacement (x, y, width, height, flags); return; } } forceResize (); RECT rect = new RECT (); OS.GetWindowRect (handle, rect); boolean sameOrigin = true; if ((OS.SWP_NOMOVE & flags) == 0) { sameOrigin = rect.left == x && rect.top == y; if (!sameOrigin) moved = true; } boolean sameExtent = true; if ((OS.SWP_NOSIZE & flags) == 0) { sameExtent = rect.right - rect.left == width && rect.bottom - rect.top == height; if (!sameExtent) resized = true; } if (!OS.IsWinCE) { if (OS.IsZoomed (handle)) { if (sameOrigin && sameExtent) return; setPlacement (x, y, width, height, flags); _setMaximized (false); return; } } super.setBounds (x, y, width, height, flags, defer); } /** * If the argument is not null, sets the receiver's default * button to the argument, and if the argument is null, sets * the receiver's default button to the first button which * was set as the receiver's default button (called the * <em>saved default button</em>). If no default button had * previously been set, or the saved default button was * disposed, the receiver's default button will be set to * null. * <p> * The default button is the button that is selected when * the receiver is active and the user presses ENTER. * </p> * * @param button the new default button * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the button has been disposed</li> * <li>ERROR_INVALID_PARENT - if the control is not in the same widget tree</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setDefaultButton (Button button) { checkWidget (); if (button != null) { if (button.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); if (button.menuShell () != this) error(SWT.ERROR_INVALID_PARENT); } setDefaultButton (button, true); } void setDefaultButton (Button button, boolean save) { if (button == null) { if (defaultButton == saveDefault) { if (save) saveDefault = null; return; } } else { if ((button.style & SWT.PUSH) == 0) return; if (button == defaultButton) { if (save) saveDefault = defaultButton; return; } } if (defaultButton != null) { if (!defaultButton.isDisposed ()) defaultButton.setDefault (false); } if ((defaultButton = button) == null) defaultButton = saveDefault; if (defaultButton != null) { if (!defaultButton.isDisposed ()) defaultButton.setDefault (true); } if (save) saveDefault = defaultButton; if (saveDefault != null && saveDefault.isDisposed ()) saveDefault = null; } /** * Sets the receiver's image to the argument, which may * be null. The image is typically displayed by the window * manager when the instance is marked as iconified, and * may also be displayed somewhere in the trim when the * instance is in normal or maximized states. * * @param image the new image (or null) * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the image has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setImage (Image image) { checkWidget (); if (image != null && image.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); this.image = image; setImages (image, null); } void setImages (Image image, Image [] images) { /* * Feature in WinCE. WM_SETICON and WM_GETICON set the icon * for the window class, not the window instance. This means * that it is possible to set an icon into a window and then * later free the icon, thus freeing the icon for every window. * The fix is to avoid the API. * * On WinCE PPC, icons in windows are not displayed. */ if (OS.IsWinCE) return; if (smallImage != null) smallImage.dispose (); if (largeImage != null) largeImage.dispose (); smallImage = largeImage = null; int /*long*/ hSmallIcon = 0, hLargeIcon = 0; Image smallIcon = null, largeIcon = null; if (image != null) { smallIcon = largeIcon = image; } else { if (images != null && images.length > 0) { int depth = display.getIconDepth (); ImageData [] datas = null; if (images.length > 1) { Image [] bestImages = new Image [images.length]; System.arraycopy (images, 0, bestImages, 0, images.length); datas = new ImageData [images.length]; for (int i=0; i<datas.length; i++) { datas [i] = images [i].getImageData (); } images = bestImages; sort (images, datas, OS.GetSystemMetrics (OS.SM_CXSMICON), OS.GetSystemMetrics (OS.SM_CYSMICON), depth); } smallIcon = images [0]; if (images.length > 1) { sort (images, datas, OS.GetSystemMetrics (OS.SM_CXICON), OS.GetSystemMetrics (OS.SM_CYICON), depth); } largeIcon = images [0]; } } if (smallIcon != null) { switch (smallIcon.type) { case SWT.BITMAP: smallImage = Display.createIcon (smallIcon); hSmallIcon = smallImage.handle; break; case SWT.ICON: hSmallIcon = smallIcon.handle; break; } } OS.SendMessage (handle, OS.WM_SETICON, OS.ICON_SMALL, hSmallIcon); if (largeIcon != null) { switch (largeIcon.type) { case SWT.BITMAP: largeImage = Display.createIcon (largeIcon); hLargeIcon = largeImage.handle; break; case SWT.ICON: hLargeIcon = largeIcon.handle; break; } } OS.SendMessage (handle, OS.WM_SETICON, OS.ICON_BIG, hLargeIcon); /* * Bug in Windows. When WM_SETICON is used to remove an * icon from the window trimmings for a window with the * extended style bits WS_EX_DLGMODALFRAME, the window * trimmings do not redraw to hide the previous icon. * The fix is to force a redraw. */ if (!OS.IsWinCE) { if (hSmallIcon == 0 && hLargeIcon == 0 && (style & SWT.BORDER) != 0) { int flags = OS.RDW_FRAME | OS.RDW_INVALIDATE; OS.RedrawWindow (handle, null, 0, flags); } } } /** * Sets the receiver's images to the argument, which may * be an empty array. Images are typically displayed by the * window manager when the instance is marked as iconified, * and may also be displayed somewhere in the trim when the * instance is in normal or maximized states. Depending where * the icon is displayed, the platform chooses the icon with * the "best" attributes. It is expected that the array will * contain the same icon rendered at different sizes, with * different depth and transparency attributes. * * @param images the new image array * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the array of images is null</li> * <li>ERROR_INVALID_ARGUMENT - if one of the images is null or has been disposed</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @since 3.0 */ public void setImages (Image [] images) { checkWidget (); if (images == null) error (SWT.ERROR_INVALID_ARGUMENT); for (int i = 0; i < images.length; i++) { if (images [i] == null || images [i].isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); } this.images = images; setImages (null, images); } /** * Sets the maximized state of the receiver. * If the argument is <code>true</code> causes the receiver * to switch to the maximized state, and if the argument is * <code>false</code> and the receiver was previously maximized, * causes the receiver to switch back to either the minimized * or normal states. * <p> * Note: The result of intermixing calls to <code>setMaximized(true)</code> * and <code>setMinimized(true)</code> will vary by platform. Typically, * the behavior will match the platform user's expectations, but not * always. This should be avoided if possible. * </p> * * @param maximized the new maximized state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #setMinimized */ public void setMaximized (boolean maximized) { checkWidget (); Display.lpStartupInfo = null; _setMaximized (maximized); } /** * Sets the receiver's menu bar to the argument, which * may be null. * * @param menu the new menu bar * * @exception IllegalArgumentException <ul> * <li>ERROR_INVALID_ARGUMENT - if the menu has been disposed</li> * <li>ERROR_INVALID_PARENT - if the menu is not in the same widget tree</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setMenuBar (Menu menu) { checkWidget (); if (menuBar == menu) return; if (menu != null) { if (menu.isDisposed()) error(SWT.ERROR_INVALID_ARGUMENT); if ((menu.style & SWT.BAR) == 0) error (SWT.ERROR_MENU_NOT_BAR); if (menu.parent != this) error (SWT.ERROR_INVALID_PARENT); } if (OS.IsWinCE) { if (OS.IsHPC) { boolean resize = menuBar != menu; if (menuBar != null) OS.CommandBar_Show (menuBar.hwndCB, false); menuBar = menu; if (menuBar != null) OS.CommandBar_Show (menuBar.hwndCB, true); if (resize) { sendEvent (SWT.Resize); if (isDisposed ()) return; if (layout != null) { markLayout (false, false); updateLayout (true, false); } } } else { if (OS.IsPPC) { /* * Note in WinCE PPC. The menu bar is a separate popup window. * If the shell is full screen, resize its window to leave * space for the menu bar. */ boolean resize = getMaximized () && menuBar != menu; if (menuBar != null) OS.ShowWindow (menuBar.hwndCB, OS.SW_HIDE); menuBar = menu; if (menuBar != null) OS.ShowWindow (menuBar.hwndCB, OS.SW_SHOW); if (resize) _setMaximized (true); } if (OS.IsSP) { if (menuBar != null) OS.ShowWindow (menuBar.hwndCB, OS.SW_HIDE); menuBar = menu; if (menuBar != null) OS.ShowWindow (menuBar.hwndCB, OS.SW_SHOW); } } } else { if (menu != null) display.removeBar (menu); menuBar = menu; int /*long*/ hMenu = menuBar != null ? menuBar.handle: 0; OS.SetMenu (handle, hMenu); } destroyAccelerators (); } /** * Sets the minimized stated of the receiver. * If the argument is <code>true</code> causes the receiver * to switch to the minimized state, and if the argument is * <code>false</code> and the receiver was previously minimized, * causes the receiver to switch back to either the maximized * or normal states. * <p> * Note: The result of intermixing calls to <code>setMaximized(true)</code> * and <code>setMinimized(true)</code> will vary by platform. Typically, * the behavior will match the platform user's expectations, but not * always. This should be avoided if possible. * </p> * * @param minimized the new maximized state * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> * * @see #setMaximized */ public void setMinimized (boolean minimized) { checkWidget (); Display.lpStartupInfo = null; _setMinimized (minimized); } public void setOrientation (int orientation) { super.setOrientation (orientation); if (menus != null) { for (int i=0; i<menus.length; i++) { Menu menu = menus [i]; if (menu != null && !menu.isDisposed () && (menu.getStyle () & SWT.POP_UP) != 0) { menu._setOrientation (menu.getOrientation ()); } } } } void setParent () { /* * In order for an MDI child window to support * a menu bar, setParent () is needed to reset * the parent. Otherwise, the MDI child window * will appear as a separate shell. This is an * undocumented and possibly dangerous Windows * feature. */ int /*long*/ hwndParent = parent.handle; display.lockActiveWindow = true; OS.SetParent (handle, hwndParent); if (!OS.IsWindowVisible (hwndParent)) { OS.ShowWindow (handle, OS.SW_SHOWNA); } int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); bits &= ~OS.WS_CHILD; OS.SetWindowLong (handle, OS.GWL_STYLE, bits | OS.WS_POPUP); OS.SetWindowLongPtr (handle, OS.GWLP_ID, 0); int flags = OS.SWP_NOSIZE | OS.SWP_NOMOVE | OS.SWP_NOACTIVATE; SetWindowPos (handle, OS.HWND_BOTTOM, 0, 0, 0, 0, flags); display.lockActiveWindow = false; } void setPlacement (int x, int y, int width, int height, int flags) { WINDOWPLACEMENT lpwndpl = new WINDOWPLACEMENT (); lpwndpl.length = WINDOWPLACEMENT.sizeof; OS.GetWindowPlacement (handle, lpwndpl); lpwndpl.showCmd = OS.SW_SHOWNA; if (OS.IsIconic (handle)) { lpwndpl.showCmd = OS.SW_SHOWMINNOACTIVE; } else { if (OS.IsZoomed (handle)) { lpwndpl.showCmd = OS.SW_SHOWMAXIMIZED; } } boolean sameOrigin = true; if ((flags & OS.SWP_NOMOVE) == 0) { sameOrigin = lpwndpl.left != x || lpwndpl.top != y; lpwndpl.right = x + (lpwndpl.right - lpwndpl.left); lpwndpl.bottom = y + (lpwndpl.bottom - lpwndpl.top); lpwndpl.left = x; lpwndpl.top = y; } boolean sameExtent = true; if ((flags & OS.SWP_NOSIZE) == 0) { sameExtent = lpwndpl.right - lpwndpl.left != width || lpwndpl.bottom - lpwndpl.top != height; lpwndpl.right = lpwndpl.left + width; lpwndpl.bottom = lpwndpl.top + height; } OS.SetWindowPlacement (handle, lpwndpl); if (OS.IsIconic (handle)) { if (sameOrigin) { moved = true; Point location = getLocation (); oldX = location.x; oldY = location.y; sendEvent (SWT.Move); if (isDisposed ()) return; } if (sameExtent) { resized = true; Rectangle rect = getClientArea (); oldWidth = rect.width; oldHeight = rect.height; sendEvent (SWT.Resize); if (isDisposed ()) return; if (layout != null) { markLayout (false, false); updateLayout (true, false); } } } } void setSavedFocus (Control control) { savedFocus = control; } void setSystemMenu () { if (OS.IsWinCE) return; int /*long*/ hMenu = OS.GetSystemMenu (handle, false); if (hMenu == 0) return; int oldCount = OS.GetMenuItemCount (hMenu); if ((style & SWT.RESIZE) == 0) { OS.DeleteMenu (hMenu, OS.SC_SIZE, OS.MF_BYCOMMAND); } if ((style & SWT.MIN) == 0) { OS.DeleteMenu (hMenu, OS.SC_MINIMIZE, OS.MF_BYCOMMAND); } if ((style & SWT.MAX) == 0) { OS.DeleteMenu (hMenu, OS.SC_MAXIMIZE, OS.MF_BYCOMMAND); } if ((style & (SWT.MIN | SWT.MAX)) == 0) { OS.DeleteMenu (hMenu, OS.SC_RESTORE, OS.MF_BYCOMMAND); } int newCount = OS.GetMenuItemCount (hMenu); if ((style & SWT.CLOSE) == 0 || newCount != oldCount) { OS.DeleteMenu (hMenu, OS.SC_TASKLIST, OS.MF_BYCOMMAND); MENUITEMINFO info = new MENUITEMINFO (); info.cbSize = MENUITEMINFO.sizeof; info.fMask = OS.MIIM_ID; int index = 0; while (index < newCount) { if (OS.GetMenuItemInfo (hMenu, index, true, info)) { if (info.wID == OS.SC_CLOSE) break; } index++; } if (index != newCount) { OS.DeleteMenu (hMenu, index - 1, OS.MF_BYPOSITION); if ((style & SWT.CLOSE) == 0) { OS.DeleteMenu (hMenu, OS.SC_CLOSE, OS.MF_BYCOMMAND); } } } } /** * Sets the receiver's text, which is the string that the * window manager will typically display as the receiver's * <em>title</em>, to the argument, which must not be null. * * @param string the new text * * @exception IllegalArgumentException <ul> * <li>ERROR_NULL_ARGUMENT - if the text is null</li> * </ul> * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li> * </ul> */ public void setText (String string) { checkWidget (); if (string == null) error (SWT.ERROR_NULL_ARGUMENT); /* Use the character encoding for the default locale */ TCHAR buffer = new TCHAR (0, string, true); /* Ensure that the title appears in the task bar.*/ if ((state & FOREIGN_HANDLE) != 0) { int /*long*/ hHeap = OS.GetProcessHeap (); int byteCount = buffer.length () * TCHAR.sizeof; int /*long*/ pszText = OS.HeapAlloc (hHeap, OS.HEAP_ZERO_MEMORY, byteCount); OS.MoveMemory (pszText, buffer, byteCount); OS.DefWindowProc (handle, OS.WM_SETTEXT, 0, pszText); if (pszText != 0) OS.HeapFree (hHeap, 0, pszText); } else { OS.SetWindowText (handle, buffer); } } public void setVisible (boolean visible) { checkWidget (); if (!getDrawing()) { if (((state & HIDDEN) == 0) == visible) return; } else { if (visible == OS.IsWindowVisible (handle)) return; } if (visible) { /* * It is possible (but unlikely), that application * code could have disposed the widget in the show * event. If this happens, just return. */ sendEvent (SWT.Show); if (isDisposed ()) return; if (OS.IsHPC) { if (menuBar != null) { int /*long*/ hwndCB = menuBar.hwndCB; OS.CommandBar_DrawMenuBar (hwndCB, 0); } } if (!getDrawing()) { state &= ~HIDDEN; } else { if (OS.IsWinCE) { OS.ShowWindow (handle, OS.SW_SHOW); } else { if (menuBar != null) { display.removeBar (menuBar); OS.DrawMenuBar (handle); } STARTUPINFO lpStartUpInfo = Display.lpStartupInfo; if (lpStartUpInfo != null && (lpStartUpInfo.dwFlags & OS.STARTF_USESHOWWINDOW) != 0) { OS.ShowWindow (handle, lpStartUpInfo.wShowWindow); } else { OS.ShowWindow (handle, swFlags); } } if (isDisposed ()) return; opened = true; if (!moved) { moved = true; Point location = getLocation (); oldX = location.x; oldY = location.y; } if (!resized) { resized = true; Rectangle rect = getClientArea (); oldWidth = rect.width; oldHeight = rect.height; } /* * Bug in Windows. On Vista using the Classic theme, * when the window is hung and UpdateWindow() is called, * nothing is drawn, and outstanding WM_PAINTs are cleared. * This causes pixel corruption. The fix is to avoid calling * update on hung windows. */ boolean update = true; if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION (6, 0) && !OS.IsAppThemed ()) { update = !OS.IsHungAppWindow (handle); } if (update) OS.UpdateWindow (handle); } } else { if (!OS.IsWinCE) { if (OS.IsIconic (handle)) { swFlags = OS.SW_SHOWMINNOACTIVE; } else { if (OS.IsZoomed (handle)) { swFlags = OS.SW_SHOWMAXIMIZED; } else { swFlags = OS.SW_SHOWNOACTIVATE; } } } if (!getDrawing()) { state |= HIDDEN; } else { OS.ShowWindow (handle, OS.SW_HIDE); } if (isDisposed ()) return; sendEvent (SWT.Hide); } } void sort (Image [] images, ImageData [] datas, int width, int height, int depth) { /* Shell Sort from K&R, pg 108 */ int length = images.length; if (length <= 1) return; for (int gap=length/2; gap>0; gap/=2) { for (int i=gap; i<length; i++) { for (int j=i-gap; j>=0; j-=gap) { if (compare (datas [j], datas [j + gap], width, height, depth) >= 0) { Image swap = images [j]; images [j] = images [j + gap]; images [j + gap] = swap; ImageData swapData = datas [j]; datas [j] = datas [j + gap]; datas [j + gap] = swapData; } } } } } boolean translateAccelerator (MSG msg) { if (!isEnabled () || !isActive ()) return false; if (menuBar != null && !menuBar.isEnabled ()) return false; if (translateMDIAccelerator (msg) || translateMenuAccelerator (msg)) return true; Decorations decorations = parent.menuShell (); return decorations.translateAccelerator (msg); } boolean translateMenuAccelerator (MSG msg) { if (hAccel == -1) createAccelerators (); return hAccel != 0 && OS.TranslateAccelerator (handle, hAccel, msg) != 0; } boolean translateMDIAccelerator (MSG msg) { if (!(this instanceof Shell)) { Shell shell = getShell (); int /*long*/ hwndMDIClient = shell.hwndMDIClient; if (hwndMDIClient != 0 && OS.TranslateMDISysAccel (hwndMDIClient, msg)) { return true; } if (msg.message == OS.WM_KEYDOWN) { if (OS.GetKeyState (OS.VK_CONTROL) >= 0) return false; switch ((int)/*64*/(msg.wParam)) { case OS.VK_F4: OS.PostMessage (handle, OS.WM_CLOSE, 0, 0); return true; case OS.VK_F6: if (traverseDecorations (true)) return true; } return false; } if (msg.message == OS.WM_SYSKEYDOWN) { switch ((int)/*64*/(msg.wParam)) { case OS.VK_F4: OS.PostMessage (shell.handle, OS.WM_CLOSE, 0, 0); return true; } return false; } } return false; } boolean traverseDecorations (boolean next) { Control [] children = parent._getChildren (); int length = children.length; int index = 0; while (index < length) { if (children [index] == this) break; index++; } /* * It is possible (but unlikely), that application * code could have disposed the widget in focus in * or out events. Ensure that a disposed widget is * not accessed. */ int start = index, offset = (next) ? 1 : -1; while ((index = (index + offset + length) % length) != start) { Control child = children [index]; if (!child.isDisposed () && child instanceof Decorations) { if (child.setFocus ()) return true; } } return false; } boolean traverseItem (boolean next) { return false; } boolean traverseReturn () { if (defaultButton == null || defaultButton.isDisposed ()) return false; if (!defaultButton.isVisible () || !defaultButton.isEnabled ()) return false; defaultButton.click (); return true; } CREATESTRUCT widgetCreateStruct () { return new CREATESTRUCT (); } int widgetExtStyle () { int bits = super.widgetExtStyle () | OS.WS_EX_MDICHILD; bits &= ~OS.WS_EX_CLIENTEDGE; if ((style & SWT.NO_TRIM) != 0) return bits; if (OS.IsPPC) { if ((style & SWT.CLOSE) != 0) bits |= OS.WS_EX_CAPTIONOKBTN; } if ((style & SWT.RESIZE) != 0) return bits; if ((style & SWT.BORDER) != 0) bits |= OS.WS_EX_DLGMODALFRAME; return bits; } int /*long*/ widgetParent () { Shell shell = getShell (); return shell.hwndMDIClient (); } int widgetStyle () { /* * Clear WS_VISIBLE and WS_TABSTOP. NOTE: In Windows, WS_TABSTOP * has the same value as WS_MAXIMIZEBOX so these bits cannot be * used to control tabbing. */ int bits = super.widgetStyle () & ~(OS.WS_TABSTOP | OS.WS_VISIBLE); /* Set the title bits and no-trim bits */ bits &= ~OS.WS_BORDER; if ((style & SWT.NO_TRIM) != 0) { if (parent == null) { bits |= OS.WS_SYSMENU | OS.WS_MINIMIZEBOX; } return bits; } if ((style & SWT.TITLE) != 0) bits |= OS.WS_CAPTION; /* Set the min and max button bits */ if ((style & SWT.MIN) != 0) bits |= OS.WS_MINIMIZEBOX; if ((style & SWT.MAX) != 0) bits |= OS.WS_MAXIMIZEBOX; /* Set the resize, dialog border or border bits */ if ((style & SWT.RESIZE) != 0) { /* * Note on WinCE PPC. SWT.RESIZE is used to resize * the Shell according to the state of the IME. * It does not set the WS_THICKFRAME style. */ if (!OS.IsPPC) bits |= OS.WS_THICKFRAME; } else { if ((style & SWT.BORDER) == 0) bits |= OS.WS_BORDER; } /* Set the system menu and close box bits */ if (!OS.IsPPC && !OS.IsSP) { if ((style & SWT.CLOSE) != 0) bits |= OS.WS_SYSMENU; } return bits; } int /*long*/ windowProc (int /*long*/ hwnd, int msg, int /*long*/ wParam, int /*long*/ lParam) { switch (msg) { case Display.SWT_GETACCEL: case Display.SWT_GETACCELCOUNT: if (hAccel == -1) createAccelerators (); return msg == Display.SWT_GETACCELCOUNT ? nAccel : hAccel; } return super.windowProc (hwnd, msg, wParam, lParam); } LRESULT WM_ACTIVATE (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_ACTIVATE (wParam, lParam); if (result != null) return result; /* * Feature in AWT. When an AWT Window is activated, * for some reason, it seems to forward the WM_ACTIVATE * message to the parent. Normally, the parent is an * AWT Frame. When AWT is embedded in SWT, the SWT * shell gets the WM_ACTIVATE and assumes that it came * from Windows. When an SWT shell is activated it * restores focus to the last control that had focus. * If this control is an embedded composite, it takes * focus from the AWT Window. The fix is to ignore * WM_ACTIVATE messages that come from AWT Windows. */ if (OS.GetParent (lParam) == handle) { TCHAR buffer = new TCHAR (0, 128); OS.GetClassName (lParam, buffer, buffer.length ()); String className = buffer.toString (0, buffer.strlen ()); if (className.equals (Display.AWT_WINDOW_CLASS)) { return LRESULT.ZERO; } } if (OS.LOWORD (wParam) != 0) { /* * When the high word of wParam is non-zero, the activation * state of the window is being changed while the window is * minimized. If this is the case, do not report activation * events or restore the focus. */ if (OS.HIWORD (wParam) != 0) return result; Control control = display.findControl (lParam); if (control == null || control instanceof Shell) { if (this instanceof Shell) { sendEvent (SWT.Activate); if (isDisposed ()) return LRESULT.ZERO; } } if (restoreFocus ()) return LRESULT.ZERO; } else { Display display = this.display; boolean lockWindow = display.isXMouseActive (); if (lockWindow) display.lockActiveWindow = true; Control control = display.findControl (lParam); if (control == null || control instanceof Shell) { if (this instanceof Shell) { sendEvent (SWT.Deactivate); if (!isDisposed ()) { Shell shell = getShell (); shell.setActiveControl (null); // widget could be disposed at this point } } } if (lockWindow) display.lockActiveWindow = false; if (isDisposed ()) return LRESULT.ZERO; saveFocus (); } return result; } LRESULT WM_CLOSE (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_CLOSE (wParam, lParam); if (result != null) return result; if (isEnabled () && isActive ()) closeWidget (); return LRESULT.ZERO; } LRESULT WM_HOTKEY (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_HOTKEY (wParam, lParam); if (result != null) return result; if (OS.IsSP) { /* * Feature on WinCE SP. The Back key is either used to close * the foreground Dialog or used as a regular Back key in an EDIT * control. The article 'Back Key' in MSDN for Smartphone * describes how an application should handle it. The * workaround is to override the Back key when creating * the menubar and handle it based on the style of the Shell. * If the Shell has the SWT.CLOSE style, close the Shell. * Otherwise, send the Back key to the window with focus. */ if (OS.HIWORD (lParam) == OS.VK_ESCAPE) { if ((style & SWT.CLOSE) != 0) { OS.PostMessage (handle, OS.WM_CLOSE, 0, 0); } else { OS.SHSendBackToFocusWindow (OS.WM_HOTKEY, wParam, lParam); } return LRESULT.ZERO; } } return result; } LRESULT WM_KILLFOCUS (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_KILLFOCUS (wParam, lParam); saveFocus (); return result; } LRESULT WM_MOVE (int /*long*/ wParam, int /*long*/ lParam) { if (moved) { Point location = getLocation (); if (location.x == oldX && location.y == oldY) { return null; } oldX = location.x; oldY = location.y; } return super.WM_MOVE (wParam, lParam); } LRESULT WM_NCACTIVATE (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_NCACTIVATE (wParam, lParam); if (result != null) return result; if (wParam == 0) { if (display.lockActiveWindow) return LRESULT.ZERO; Control control = display.findControl (lParam); if (control != null) { Shell shell = getShell (); Decorations decorations = control.menuShell (); if (decorations.getShell () == shell) { if (this instanceof Shell) return LRESULT.ONE; if (display.ignoreRestoreFocus) { if (display.lastHittest != OS.HTCLIENT) { result = LRESULT.ONE; } } } } } if (!(this instanceof Shell)) { int /*long*/ hwndShell = getShell().handle; OS.SendMessage (hwndShell, OS.WM_NCACTIVATE, wParam, lParam); } return result; } LRESULT WM_QUERYOPEN (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_QUERYOPEN (wParam, lParam); if (result != null) return result; sendEvent (SWT.Deiconify); // widget could be disposed at this point return result; } LRESULT WM_SETFOCUS (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_SETFOCUS (wParam, lParam); if (isDisposed ()) return result; if (savedFocus != this) restoreFocus (); return result; } LRESULT WM_SIZE (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = null; boolean changed = true; if (resized) { int newWidth = 0, newHeight = 0; switch ((int)/*64*/wParam) { case OS.SIZE_MAXIMIZED: OS.GetWindowRect (handle, maxRect); case OS.SIZE_RESTORED: newWidth = OS.LOWORD (lParam); newHeight = OS.HIWORD (lParam); break; case OS.SIZE_MINIMIZED: Rectangle rect = getClientArea (); newWidth = rect.width; newHeight = rect.height; break; } changed = newWidth != oldWidth || newHeight != oldHeight; if (changed) { oldWidth = newWidth; oldHeight = newHeight; } } if (changed) { result = super.WM_SIZE (wParam, lParam); if (isDisposed ()) return result; } if (wParam == OS.SIZE_MINIMIZED) { sendEvent (SWT.Iconify); // widget could be disposed at this point } return result; } LRESULT WM_SYSCOMMAND (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_SYSCOMMAND (wParam, lParam); if (result != null) return result; if (!(this instanceof Shell)) { int cmd = (int)/*64*/wParam & 0xFFF0; switch (cmd) { case OS.SC_CLOSE: { OS.PostMessage (handle, OS.WM_CLOSE, 0, 0); return LRESULT.ZERO; } case OS.SC_NEXTWINDOW: { traverseDecorations (true); return LRESULT.ZERO; } } } return result; } LRESULT WM_WINDOWPOSCHANGING (int /*long*/ wParam, int /*long*/ lParam) { LRESULT result = super.WM_WINDOWPOSCHANGING (wParam, lParam); if (result != null) return result; if (display.lockActiveWindow) { WINDOWPOS lpwp = new WINDOWPOS (); OS.MoveMemory (lpwp, lParam, WINDOWPOS.sizeof); lpwp.flags |= OS.SWP_NOZORDER; OS.MoveMemory (lParam, lpwp, WINDOWPOS.sizeof); } return result; } }
elkafoury/tux
src/org/eclipse/swt/widgets/Decorations.java
Java
lgpl-2.1
56,884
#include "t3_5.h" #include <iostream> int B::a(float* b) { std::cout << "t3_5: B::a(float* b)" << std::endl; std::cout << "b: " << *b << std::endl; return (int)*b; } int* B::b(float c) { std::cout << "t3_5: B::b(float c)" << std::endl; std::cout << "c: " << c << std::endl; e = (int) c; return &e; } int* B::c(float* d) { std::cout << "t3_5: B::c(float* d)" << std::endl; std::cout << "d: " << *d << std::endl; e = (int) *d; return &e; }
rhajamor/xbig
tests/t3_5/src/lib/t3_5.cpp
C++
lgpl-2.1
454
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * SPIOutput.cpp * An RDM-controllable SPI device. Takes up to one universe of DMX. * Copyright (C) 2013 Simon Newton * * The LPD8806 code was based on * https://github.com/adafruit/LPD8806/blob/master/LPD8806.cpp */ #if HAVE_CONFIG_H #include <config.h> #endif #include <string.h> #include <algorithm> #include <memory> #include <sstream> #include <string> #include <vector> #include "ola/base/Array.h" #include "ola/Constants.h" #include "ola/Logging.h" #include "ola/file/Util.h" #include "ola/network/NetworkUtils.h" #include "ola/rdm/OpenLightingEnums.h" #include "ola/rdm/RDMCommand.h" #include "ola/rdm/RDMEnums.h" #include "ola/rdm/ResponderHelper.h" #include "ola/rdm/ResponderLoadSensor.h" #include "ola/rdm/ResponderSensor.h" #include "ola/rdm/UID.h" #include "ola/rdm/UIDSet.h" #include "ola/stl/STLUtils.h" #include "plugins/spi/SPIBackend.h" #include "plugins/spi/SPIOutput.h" namespace ola { namespace plugin { namespace spi { using ola::file::FilenameFromPathOrPath; using ola::network::HostToNetwork; using ola::network::NetworkToHost; using ola::rdm::LoadSensor; using ola::rdm::NR_DATA_OUT_OF_RANGE; using ola::rdm::NR_FORMAT_ERROR; using ola::rdm::Personality; using ola::rdm::PersonalityCollection; using ola::rdm::PersonalityManager; using ola::rdm::RDMCallback; using ola::rdm::RDMCommand; using ola::rdm::RDMRequest; using ola::rdm::RDMResponse; using ola::rdm::ResponderHelper; using ola::rdm::UID; using ola::rdm::UIDSet; using std::auto_ptr; using std::min; using std::string; using std::vector; const uint16_t SPIOutput::SPI_DELAY = 0; const uint8_t SPIOutput::SPI_BITS_PER_WORD = 8; const uint8_t SPIOutput::SPI_MODE = 0; /** * These constants are used to determine the number of DMX Slots per pixel * The p9813 uses another byte preceding each of the three bytes as a kind * of header. */ const uint16_t SPIOutput::WS2801_SLOTS_PER_PIXEL = 3; const uint16_t SPIOutput::LPD8806_SLOTS_PER_PIXEL = 3; const uint16_t SPIOutput::P9813_SLOTS_PER_PIXEL = 3; // Number of bytes that each P9813 pixel uses on the spi wires const uint16_t SPIOutput::P9813_SPI_BYTES_PER_PIXEL = 4; SPIOutput::RDMOps *SPIOutput::RDMOps::instance = NULL; const ola::rdm::ResponderOps<SPIOutput>::ParamHandler SPIOutput::PARAM_HANDLERS[] = { { ola::rdm::PID_DEVICE_INFO, &SPIOutput::GetDeviceInfo, NULL}, { ola::rdm::PID_PRODUCT_DETAIL_ID_LIST, &SPIOutput::GetProductDetailList, NULL}, { ola::rdm::PID_DEVICE_MODEL_DESCRIPTION, &SPIOutput::GetDeviceModelDescription, NULL}, { ola::rdm::PID_MANUFACTURER_LABEL, &SPIOutput::GetManufacturerLabel, NULL}, { ola::rdm::PID_DEVICE_LABEL, &SPIOutput::GetDeviceLabel, &SPIOutput::SetDeviceLabel}, { ola::rdm::PID_SOFTWARE_VERSION_LABEL, &SPIOutput::GetSoftwareVersionLabel, NULL}, { ola::rdm::PID_DMX_PERSONALITY, &SPIOutput::GetDmxPersonality, &SPIOutput::SetDmxPersonality}, { ola::rdm::PID_DMX_PERSONALITY_DESCRIPTION, &SPIOutput::GetPersonalityDescription, NULL}, { ola::rdm::PID_DMX_START_ADDRESS, &SPIOutput::GetDmxStartAddress, &SPIOutput::SetDmxStartAddress}, { ola::rdm::PID_IDENTIFY_DEVICE, &SPIOutput::GetIdentify, &SPIOutput::SetIdentify}, #ifdef HAVE_GETLOADAVG { ola::rdm::PID_SENSOR_DEFINITION, &SPIOutput::GetSensorDefinition, NULL}, { ola::rdm::PID_SENSOR_VALUE, &SPIOutput::GetSensorValue, &SPIOutput::SetSensorValue}, { ola::rdm::PID_RECORD_SENSORS, NULL, &SPIOutput::RecordSensor}, #endif { ola::rdm::PID_LIST_INTERFACES, &SPIOutput::GetListInterfaces, NULL}, { ola::rdm::PID_INTERFACE_LABEL, &SPIOutput::GetInterfaceLabel, NULL}, { ola::rdm::PID_INTERFACE_HARDWARE_ADDRESS_TYPE1, &SPIOutput::GetInterfaceHardwareAddressType1, NULL}, { ola::rdm::PID_IPV4_CURRENT_ADDRESS, &SPIOutput::GetIPV4CurrentAddress, NULL}, { ola::rdm::PID_IPV4_DEFAULT_ROUTE, &SPIOutput::GetIPV4DefaultRoute, NULL}, { ola::rdm::PID_DNS_HOSTNAME, &SPIOutput::GetDNSHostname, NULL}, { ola::rdm::PID_DNS_DOMAIN_NAME, &SPIOutput::GetDNSDomainName, NULL}, { ola::rdm::PID_DNS_NAME_SERVER, &SPIOutput::GetDNSNameServer, NULL}, { 0, NULL, NULL}, }; SPIOutput::SPIOutput(const UID &uid, SPIBackendInterface *backend, const Options &options) : m_backend(backend), m_output_number(options.output_number), m_uid(uid), m_pixel_count(options.pixel_count), m_device_label(options.device_label), m_start_address(1), m_identify_mode(false) { m_spi_device_name = FilenameFromPathOrPath(m_backend->DevicePath()); PersonalityCollection::PersonalityList personalities; personalities.push_back(Personality(m_pixel_count * WS2801_SLOTS_PER_PIXEL, "WS2801 Individual Control")); personalities.push_back(Personality(WS2801_SLOTS_PER_PIXEL, "WS2801 Combined Control")); personalities.push_back(Personality(m_pixel_count * LPD8806_SLOTS_PER_PIXEL, "LPD8806 Individual Control")); personalities.push_back(Personality(LPD8806_SLOTS_PER_PIXEL, "LPD8806 Combined Control")); personalities.push_back(Personality(m_pixel_count * P9813_SLOTS_PER_PIXEL, "P9813 Individual Control")); personalities.push_back(Personality(P9813_SLOTS_PER_PIXEL, "P9813 Combined Control")); m_personality_collection.reset(new PersonalityCollection(personalities)); m_personality_manager.reset(new PersonalityManager( m_personality_collection.get())); m_personality_manager->SetActivePersonality(1); #ifdef HAVE_GETLOADAVG m_sensors.push_back(new LoadSensor(ola::system::LOAD_AVERAGE_1_MIN, "Load Average 1 minute")); m_sensors.push_back(new LoadSensor(ola::system::LOAD_AVERAGE_5_MINS, "Load Average 5 minutes")); m_sensors.push_back(new LoadSensor(ola::system::LOAD_AVERAGE_15_MINS, "Load Average 15 minutes")); #endif m_network_manager.reset(new ola::rdm::NetworkManager()); } SPIOutput::~SPIOutput() { STLDeleteElements(&m_sensors); } string SPIOutput::GetDeviceLabel() const { return m_device_label; } bool SPIOutput::SetDeviceLabel(const string &device_label) { m_device_label = device_label; return true; } uint8_t SPIOutput::GetPersonality() const { return m_personality_manager->ActivePersonalityNumber(); } bool SPIOutput::SetPersonality(uint16_t personality) { return m_personality_manager->SetActivePersonality(personality); } uint16_t SPIOutput::GetStartAddress() const { return m_start_address; } bool SPIOutput::SetStartAddress(uint16_t address) { uint16_t footprint = m_personality_manager->ActivePersonalityFootprint(); uint16_t end_address = DMX_UNIVERSE_SIZE - footprint + 1; if (address == 0 || address > end_address || footprint == 0) { return false; } m_start_address = address; return true; } string SPIOutput::Description() const { std::ostringstream str; str << m_spi_device_name << ", output " << static_cast<int>(m_output_number) << ", " << m_personality_manager->ActivePersonalityDescription() << ", " << m_personality_manager->ActivePersonalityFootprint() << " slots @ " << m_start_address << ". (" << m_uid << ")"; return str.str(); } /* * Send DMX data over SPI. */ bool SPIOutput::WriteDMX(const DmxBuffer &buffer) { if (m_identify_mode) return true; return InternalWriteDMX(buffer); } void SPIOutput::RunFullDiscovery(ola::rdm::RDMDiscoveryCallback *callback) { UIDSet uids; uids.AddUID(m_uid); callback->Run(uids); } void SPIOutput::RunIncrementalDiscovery( ola::rdm::RDMDiscoveryCallback *callback) { UIDSet uids; uids.AddUID(m_uid); callback->Run(uids); } void SPIOutput::SendRDMRequest(RDMRequest *request, RDMCallback *callback) { RDMOps::Instance()->HandleRDMRequest(this, m_uid, ola::rdm::ROOT_RDM_DEVICE, request, callback); } bool SPIOutput::InternalWriteDMX(const DmxBuffer &buffer) { switch (m_personality_manager->ActivePersonalityNumber()) { case 1: IndividualWS2801Control(buffer); break; case 2: CombinedWS2801Control(buffer); break; case 3: IndividualLPD8806Control(buffer); break; case 4: CombinedLPD8806Control(buffer); break; case 5: IndividualP9813Control(buffer); break; case 6: CombinedP9813Control(buffer); break; default: break; } return true; } void SPIOutput::IndividualWS2801Control(const DmxBuffer &buffer) { // We always check out the entire string length, even if we only have data // for part of it const unsigned int output_length = m_pixel_count * LPD8806_SLOTS_PER_PIXEL; uint8_t *output = m_backend->Checkout(m_output_number, output_length); if (!output) return; unsigned int new_length = output_length; buffer.GetRange(m_start_address - 1, output, &new_length); m_backend->Commit(m_output_number); } void SPIOutput::CombinedWS2801Control(const DmxBuffer &buffer) { unsigned int pixel_data_length = WS2801_SLOTS_PER_PIXEL; uint8_t pixel_data[WS2801_SLOTS_PER_PIXEL]; buffer.GetRange(m_start_address - 1, pixel_data, &pixel_data_length); if (pixel_data_length != WS2801_SLOTS_PER_PIXEL) { OLA_INFO << "Insufficient DMX data, required " << WS2801_SLOTS_PER_PIXEL << ", got " << pixel_data_length; return; } const unsigned int length = m_pixel_count * WS2801_SLOTS_PER_PIXEL; uint8_t *output = m_backend->Checkout(m_output_number, length); if (!output) return; for (unsigned int i = 0; i < m_pixel_count; i++) { memcpy(output + (i * WS2801_SLOTS_PER_PIXEL), pixel_data, pixel_data_length); } m_backend->Commit(m_output_number); } void SPIOutput::IndividualLPD8806Control(const DmxBuffer &buffer) { const uint8_t latch_bytes = (m_pixel_count + 31) / 32; const unsigned int first_slot = m_start_address - 1; // 0 offset if (buffer.Size() - first_slot < LPD8806_SLOTS_PER_PIXEL) { // not even 3 bytes of data, don't bother updating return; } // We always check out the entire string length, even if we only have data // for part of it const unsigned int output_length = m_pixel_count * LPD8806_SLOTS_PER_PIXEL; uint8_t *output = m_backend->Checkout(m_output_number, output_length, latch_bytes); if (!output) return; const unsigned int length = std::min(m_pixel_count * LPD8806_SLOTS_PER_PIXEL, buffer.Size() - first_slot); for (unsigned int i = 0; i < length / LPD8806_SLOTS_PER_PIXEL; i++) { // Convert RGB to GRB unsigned int offset = first_slot + i * LPD8806_SLOTS_PER_PIXEL; uint8_t r = buffer.Get(offset); uint8_t g = buffer.Get(offset + 1); uint8_t b = buffer.Get(offset + 2); output[i * LPD8806_SLOTS_PER_PIXEL] = 0x80 | (g >> 1); output[i * LPD8806_SLOTS_PER_PIXEL + 1] = 0x80 | (r >> 1); output[i * LPD8806_SLOTS_PER_PIXEL + 2] = 0x80 | (b >> 1); } m_backend->Commit(m_output_number); } void SPIOutput::CombinedLPD8806Control(const DmxBuffer &buffer) { const uint8_t latch_bytes = (m_pixel_count + 31) / 32; unsigned int pixel_data_length = LPD8806_SLOTS_PER_PIXEL; uint8_t pixel_data[LPD8806_SLOTS_PER_PIXEL]; buffer.GetRange(m_start_address - 1, pixel_data, &pixel_data_length); if (pixel_data_length != LPD8806_SLOTS_PER_PIXEL) { OLA_INFO << "Insufficient DMX data, required " << LPD8806_SLOTS_PER_PIXEL << ", got " << pixel_data_length; return; } // The leds are GRB format so convert here uint8_t temp = pixel_data[1]; pixel_data[1] = pixel_data[0]; pixel_data[0] = temp; const unsigned int length = m_pixel_count * LPD8806_SLOTS_PER_PIXEL; uint8_t *output = m_backend->Checkout(m_output_number, length, latch_bytes); if (!output) return; for (unsigned int i = 0; i < m_pixel_count; i++) { for (unsigned int j = 0; j < LPD8806_SLOTS_PER_PIXEL; j++) { output[i * LPD8806_SLOTS_PER_PIXEL + j] = 0x80 | (pixel_data[j] >> 1); } } m_backend->Commit(m_output_number); } void SPIOutput::IndividualP9813Control(const DmxBuffer &buffer) { // We need 4 bytes of zeros in the beginning and 8 bytes at // the end const uint8_t latch_bytes = 3 * P9813_SPI_BYTES_PER_PIXEL; const unsigned int first_slot = m_start_address - 1; // 0 offset if (buffer.Size() - first_slot < P9813_SLOTS_PER_PIXEL) { // not even 3 bytes of data, don't bother updating return; } // We always check out the entire string length, even if we only have data // for part of it const unsigned int output_length = m_pixel_count * P9813_SPI_BYTES_PER_PIXEL; uint8_t *output = m_backend->Checkout(m_output_number, output_length, latch_bytes); if (!output) return; for (unsigned int i = 0; i < m_pixel_count; i++) { // Convert RGB to P9813 Pixel unsigned int offset = first_slot + i * P9813_SLOTS_PER_PIXEL; // We need to avoid the first 4 bytes of the buffer since that acts as a // start of frame delimiter unsigned int spi_offset = (i + 1) * P9813_SPI_BYTES_PER_PIXEL; uint8_t r = 0; uint8_t b = 0; uint8_t g = 0; if (buffer.Size() - offset >= P9813_SLOTS_PER_PIXEL) { r = buffer.Get(offset); g = buffer.Get(offset + 1); b = buffer.Get(offset + 2); } output[spi_offset] = P9813CreateFlag(r, g, b); output[spi_offset + 1] = b; output[spi_offset + 2] = g; output[spi_offset + 3] = r; } m_backend->Commit(m_output_number); } void SPIOutput::CombinedP9813Control(const DmxBuffer &buffer) { const uint8_t latch_bytes = 3 * P9813_SPI_BYTES_PER_PIXEL; const unsigned int first_slot = m_start_address - 1; // 0 offset if (buffer.Size() - first_slot < P9813_SLOTS_PER_PIXEL) { OLA_INFO << "Insufficient DMX data, required " << P9813_SLOTS_PER_PIXEL << ", got " << buffer.Size() - first_slot; return; } uint8_t pixel_data[P9813_SPI_BYTES_PER_PIXEL]; pixel_data[3] = buffer.Get(first_slot); // Get Red pixel_data[2] = buffer.Get(first_slot + 1); // Get Green pixel_data[1] = buffer.Get(first_slot + 2); // Get Blue pixel_data[0] = P9813CreateFlag(pixel_data[3], pixel_data[2], pixel_data[1]); const unsigned int length = m_pixel_count * P9813_SPI_BYTES_PER_PIXEL; uint8_t *output = m_backend->Checkout(m_output_number, length, latch_bytes); if (!output) return; for (unsigned int i = 0; i < m_pixel_count; i++) { memcpy(&output[(i + 1) * P9813_SPI_BYTES_PER_PIXEL], pixel_data, P9813_SPI_BYTES_PER_PIXEL); } m_backend->Commit(m_output_number); } /** * For more information please visit: * https://github.com/CoolNeon/elinux-tcl/blob/master/README.txt */ uint8_t SPIOutput::P9813CreateFlag(uint8_t red, uint8_t green, uint8_t blue) { uint8_t flag = 0; flag = (red & 0xc0) >> 6; flag |= (green & 0xc0) >> 4; flag |= (blue & 0xc0) >> 2; return ~flag; } RDMResponse *SPIOutput::GetDeviceInfo(const RDMRequest *request) { return ResponderHelper::GetDeviceInfo( request, ola::rdm::OLA_SPI_DEVICE_MODEL, ola::rdm::PRODUCT_CATEGORY_FIXTURE, 4, m_personality_manager.get(), m_start_address, 0, m_sensors.size()); } RDMResponse *SPIOutput::GetProductDetailList(const RDMRequest *request) { // Shortcut for only one item in the vector return ResponderHelper::GetProductDetailList(request, vector<ola::rdm::rdm_product_detail> (1, ola::rdm::PRODUCT_DETAIL_LED)); } RDMResponse *SPIOutput::GetDeviceModelDescription(const RDMRequest *request) { return ResponderHelper::GetString(request, "OLA SPI Device"); } RDMResponse *SPIOutput::GetManufacturerLabel(const RDMRequest *request) { return ResponderHelper::GetString( request, ola::rdm::OLA_MANUFACTURER_LABEL); } RDMResponse *SPIOutput::GetDeviceLabel(const RDMRequest *request) { return ResponderHelper::GetString(request, m_device_label); } RDMResponse *SPIOutput::SetDeviceLabel(const RDMRequest *request) { return ResponderHelper::SetString(request, &m_device_label); } RDMResponse *SPIOutput::GetSoftwareVersionLabel(const RDMRequest *request) { return ResponderHelper::GetString(request, string("OLA Version ") + VERSION); } RDMResponse *SPIOutput::GetDmxPersonality(const RDMRequest *request) { return ResponderHelper::GetPersonality(request, m_personality_manager.get()); } RDMResponse *SPIOutput::SetDmxPersonality(const RDMRequest *request) { return ResponderHelper::SetPersonality(request, m_personality_manager.get(), m_start_address); } RDMResponse *SPIOutput::GetPersonalityDescription(const RDMRequest *request) { return ResponderHelper::GetPersonalityDescription( request, m_personality_manager.get()); } RDMResponse *SPIOutput::GetDmxStartAddress(const RDMRequest *request) { return ResponderHelper::GetDmxAddress(request, m_personality_manager.get(), m_start_address); } RDMResponse *SPIOutput::SetDmxStartAddress(const RDMRequest *request) { return ResponderHelper::SetDmxAddress(request, m_personality_manager.get(), &m_start_address); } RDMResponse *SPIOutput::GetIdentify(const RDMRequest *request) { return ResponderHelper::GetBoolValue(request, m_identify_mode); } RDMResponse *SPIOutput::SetIdentify(const RDMRequest *request) { bool old_value = m_identify_mode; RDMResponse *response = ResponderHelper::SetBoolValue( request, &m_identify_mode); if (m_identify_mode != old_value) { OLA_INFO << "SPI " << m_spi_device_name << " identify mode " << ( m_identify_mode ? "on" : "off"); DmxBuffer identify_buffer; if (m_identify_mode) { identify_buffer.SetRangeToValue(0, DMX_MAX_SLOT_VALUE, DMX_UNIVERSE_SIZE); } else { identify_buffer.Blackout(); } InternalWriteDMX(identify_buffer); } return response; } /** * PID_SENSOR_DEFINITION */ RDMResponse *SPIOutput::GetSensorDefinition(const RDMRequest *request) { return ResponderHelper::GetSensorDefinition(request, m_sensors); } /** * PID_SENSOR_VALUE */ RDMResponse *SPIOutput::GetSensorValue(const RDMRequest *request) { return ResponderHelper::GetSensorValue(request, m_sensors); } RDMResponse *SPIOutput::SetSensorValue(const RDMRequest *request) { return ResponderHelper::SetSensorValue(request, m_sensors); } /** * PID_RECORD_SENSORS */ RDMResponse *SPIOutput::RecordSensor(const RDMRequest *request) { return ResponderHelper::RecordSensor(request, m_sensors); } /** * E1.37-2 PIDs */ RDMResponse *SPIOutput::GetListInterfaces(const RDMRequest *request) { return ResponderHelper::GetListInterfaces(request, m_network_manager.get()); } RDMResponse *SPIOutput::GetInterfaceLabel(const RDMRequest *request) { return ResponderHelper::GetInterfaceLabel(request, m_network_manager.get()); } RDMResponse *SPIOutput::GetInterfaceHardwareAddressType1( const RDMRequest *request) { return ResponderHelper::GetInterfaceHardwareAddressType1( request, m_network_manager.get()); } RDMResponse *SPIOutput::GetIPV4CurrentAddress(const RDMRequest *request) { return ResponderHelper::GetIPV4CurrentAddress(request, m_network_manager.get()); } RDMResponse *SPIOutput::GetIPV4DefaultRoute(const RDMRequest *request) { return ResponderHelper::GetIPV4DefaultRoute(request, m_network_manager.get()); } RDMResponse *SPIOutput::GetDNSHostname(const RDMRequest *request) { return ResponderHelper::GetDNSHostname(request, m_network_manager.get()); } RDMResponse *SPIOutput::GetDNSDomainName(const RDMRequest *request) { return ResponderHelper::GetDNSDomainName(request, m_network_manager.get()); } RDMResponse *SPIOutput::GetDNSNameServer(const RDMRequest *request) { return ResponderHelper::GetDNSNameServer(request, m_network_manager.get()); } } // namespace spi } // namespace plugin } // namespace ola
nightrune/ola
plugins/spi/SPIOutput.cpp
C++
lgpl-2.1
21,386
/* */ package thaumcraft.api.research; /* */ /* */ import java.util.HashMap; /* */ import java.util.Map; /* */ import net.minecraft.util.ResourceLocation; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class ResearchCategoryList /* */ { /* */ public int minDisplayColumn; /* */ public int minDisplayRow; /* */ public int maxDisplayColumn; /* */ public int maxDisplayRow; /* */ public ResourceLocation icon; /* */ public ResourceLocation background; /* */ public ResourceLocation background2; /* */ public String researchKey; /* */ /* */ public ResearchCategoryList(String researchKey, ResourceLocation icon, ResourceLocation background) /* */ { /* 30 */ this.researchKey = researchKey; /* 31 */ this.icon = icon; /* 32 */ this.background = background; /* 33 */ this.background2 = null; /* */ } /* */ /* */ public ResearchCategoryList(String researchKey, ResourceLocation icon, ResourceLocation background, ResourceLocation background2) { /* 37 */ this.researchKey = researchKey; /* 38 */ this.icon = icon; /* 39 */ this.background = background; /* 40 */ this.background2 = background2; /* */ } /* */ /* */ /* 44 */ public Map<String, ResearchItem> research = new HashMap(); /* */ } /* Location: C:\Users\Alex\Desktop\Thaumcraft-1.8.9-5.2.4-deobf.jar!\thaumcraft\api\research\ResearchCategoryList.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
darkeports/tc5-port
src/main/java/thaumcraft/api/research/ResearchCategoryList.java
Java
lgpl-2.1
1,609
#include "mmBvhParser.h" #include "BvhParser.h" using namespace std; namespace MoMa { bool BvhParser::load( string fileName, Track *track, bool hasRotation, bool globalCoordinate ) { vector<string> rawJoint; vector<int> axisIndex; std::shared_ptr<NodeList> nodeList; nodeList = std::make_shared<NodeList>(); #ifdef WIN32 // Added to manage special characters (accents for example) in file path (extended ASCII table) string tmp = fileName; int j=0; bool accented=false; for(int i=0;i<tmp.size();++i){ /*if(tmp[i]<127&&tmp[i]>0){// Basic ASCII table (not safe) fileName[j]=tmp[i]; ++j; }*/ if(tmp[i]!=-61){// Basic ASCII table (safer) fileName[j]=tmp[i]; ++j; } else{ // Manage buggy special characters // the special character is divided in two characters : -61 and X (between -1 and -127); to get a valid character the conversion is c=X+64 accented=true; ++i; //tmp[i] was -61 fileName[j]=tmp[i]+64; ++j; } } if(accented){ fileName[j]='\0'; } #endif //cout << "--- Attempt: " << fileName << " ---" << endl; bvhParser parser; if (!(parser.bvhRead(fileName))) return false; //track->clear(); unsigned int nFrames = parser.mFrames; unsigned int nNodes = parser.getNofJoints(); track->setFrameRate(parser.mFrameRate); //vector<vector<float> > jointOffsetRotation; //jointOffsetRotation=parser.getJointOffsetRotation(); arma::cube positionData(3, nNodes, nFrames); for (int i = 0; i < nFrames; i++) { if (i % 100 == 0) std::cout << i << std::endl; vector<vector<float> > bvhFrame; if (globalCoordinate) { bvhFrame = parser.bvh2xyz(i); } else{ bvhFrame = parser.bvh2LocalXyz(i); } //MoMa::Frame lFrame; //lFrame.setRotationFlag(hasRotation); //lFrame.setSynoList(track->synoList); for (int j = 0; j < bvhFrame.size(); j++) { //MoMa::Node lNode(bvhFrame[j][0]*10,bvhFrame[j][1]*10,bvhFrame[j][2]*10); positionData(0, j, i) = bvhFrame[j][0] * 10; positionData(1, j, i) = bvhFrame[j][1] * 10; positionData(2, j, i) = bvhFrame[j][2] * 10; } //track->push(lFrame); track->position.setData(parser.mFrameRate, positionData); track->setFrameRate(parser.mFrameRate); } if (hasRotation) { arma::cube rotationData(4, parser.getNofBones(), nFrames); for (int i = 0; i < nFrames; i++) { if (i % 100 == 0) std::cout << i << std::endl; vector<vector<float> > bvhFrame; vector<vector<float> > bvhRotationFrame; if (globalCoordinate) { bvhRotationFrame = parser.bvh2quat(i); } else { bvhRotationFrame = parser.bvh2LocalQuat(i); } for (int j = 0; j < bvhRotationFrame.size(); j++) { rotationData(0, j, i) = bvhRotationFrame[j][0]; rotationData(1, j, i) = bvhRotationFrame[j][1]; rotationData(2, j, i) = bvhRotationFrame[j][2]; rotationData(3, j, i) = bvhRotationFrame[j][3]; } track->rotation.setData(parser.mFrameRate, rotationData); track->setFrameRate(parser.mFrameRate); } } track->hasRotation = hasRotation; track->hasGlobalCoordinate = globalCoordinate; track->nodeList = std::make_shared<NodeList>(); track->hasNodeList = true; for (unsigned int i = 0; i < nNodes; i++) { // track->nodeList->push_back(parser.getNodeName(i)); track->nodeList->insert(make_pair(parser.getNodeName(i), i)); } if (track->boneList){ //delete track->boneList; track->boneList = NULL; } track->boneList = std::make_shared<BoneList>(); std::vector<std::pair<int, std::vector<int> > > lBones = parser.getBonesIndices(); track->hasBoneList = true; unsigned int nBones = lBones.size(); for (unsigned int i = 0; i < nBones; i++) { track->boneList->emplace(parser.getNodeName(lBones[i].first), BoneData(i, lBones[i].first, lBones[i].second));//By convention for BVH, bone name is the name of the origin node } // track->hasSynoList=false; // track->hasOrigNodeRot_as_boneRot=true; return true; } }
numediart/MotionMachine
src/parsers/mmBvhParser.cpp
C++
lgpl-2.1
4,418
/** * <copyright> * </copyright> * * $Id$ */ package net.opengis.fes20.impl; import java.util.Collection; import net.opengis.fes20.Fes20Package; import net.opengis.fes20.SpatialOperatorType; import net.opengis.fes20.SpatialOperatorsType; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; import org.opengis.filter.capability.SpatialOperator; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Spatial Operators Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link net.opengis.fes20.impl.SpatialOperatorsTypeImpl#getSpatialOperator <em>Spatial Operator</em>}</li> * </ul> * </p> * * @generated */ public class SpatialOperatorsTypeImpl extends EObjectImpl implements SpatialOperatorsType { /** * The cached value of the '{@link #getSpatialOperator() <em>Spatial Operator</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSpatialOperator() * @generated * @ordered */ protected EList<SpatialOperator> spatialOperator; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SpatialOperatorsTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Fes20Package.Literals.SPATIAL_OPERATORS_TYPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EList<SpatialOperator> getOperators() { if (spatialOperator == null) { spatialOperator = new EObjectContainmentEList<>(SpatialOperatorType.class, this, Fes20Package.SPATIAL_OPERATORS_TYPE__SPATIAL_OPERATOR); } return spatialOperator; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Fes20Package.SPATIAL_OPERATORS_TYPE__SPATIAL_OPERATOR: return ((InternalEList<?>)getOperators()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Fes20Package.SPATIAL_OPERATORS_TYPE__SPATIAL_OPERATOR: return getOperators(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Fes20Package.SPATIAL_OPERATORS_TYPE__SPATIAL_OPERATOR: getOperators().clear(); getOperators().addAll((Collection<? extends SpatialOperatorType>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Fes20Package.SPATIAL_OPERATORS_TYPE__SPATIAL_OPERATOR: getOperators().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Fes20Package.SPATIAL_OPERATORS_TYPE__SPATIAL_OPERATOR: return spatialOperator != null && !spatialOperator.isEmpty(); } return super.eIsSet(featureID); } @Override public SpatialOperator getOperator(String name) { for (SpatialOperator op : getOperators()){ if (op.getName().equals(name)){ return op; } } return null; } } //SpatialOperatorsTypeImpl
geotools/geotools
modules/ogc/net.opengis.fes/src/net/opengis/fes20/impl/SpatialOperatorsTypeImpl.java
Java
lgpl-2.1
4,589
// // SearchAndReplaceTests.cs // // Author: // Mike Krüger <mkrueger@xamarin.com> // // Copyright (c) 2013 Xamarin Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using NUnit.Framework; using Gtk; namespace Mono.TextEditor.Tests { [TestFixture] class SearchAndReplaceTests : TextEditorTestBase { /// <summary> /// Bug 14716 - Search and replace All doesn't /// </summary> [Test()] public void TestBug14716 () { var data = new TextEditorData (); data.Document.Text = "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n"; data.SearchEngine = new RegexSearchEngine (); data.SearchEngine.SearchRequest.SearchPattern = "u.i.g"; data.SearchReplaceAll ("bar"); Assert.AreEqual ("bar System;\nbar System.Linq;\nbar System.Collections.Generic;\n", data.Document.Text ); } } }
mono/linux-packaging-monodevelop
src/core/MonoDevelop.TextEditor.Tests/Mono.TextEditor.Tests/SearchAndReplaceTests.cs
C#
lgpl-2.1
1,898
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2022, by David Gilbert and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------------- * StandardXYBarPainterTest.java * ----------------------------- * (C) Copyright 2008-2022, by David Gilbert and Contributors. * * Original Author: David Gilbert; * Contributor(s): -; * */ package org.jfree.chart.renderer.xy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; import org.jfree.chart.TestUtils; import org.jfree.chart.api.PublicCloneable; import org.junit.jupiter.api.Test; /** * Tests for the {@link StandardXYBarPainter} class. */ public class StandardXYBarPainterTest { /** * Check that the equals() method distinguishes all fields. */ @Test public void testEquals() { StandardXYBarPainter p1 = new StandardXYBarPainter(); StandardXYBarPainter p2 = new StandardXYBarPainter(); assertEquals(p1, p2); } /** * Two objects that are equal are required to return the same hashCode. */ @Test public void testHashcode() { StandardXYBarPainter p1 = new StandardXYBarPainter(); StandardXYBarPainter p2 = new StandardXYBarPainter(); assertEquals(p1, p2); int h1 = p1.hashCode(); int h2 = p2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning isn't implemented (it isn't required, because * instances of the class are immutable). */ @Test public void testCloning() { StandardXYBarPainter p1 = new StandardXYBarPainter(); assertFalse(p1 instanceof Cloneable); assertFalse(p1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { StandardXYBarPainter p1 = new StandardXYBarPainter(); StandardXYBarPainter p2 = TestUtils.serialised(p1); assertEquals(p1, p2); } }
jfree/jfreechart
src/test/java/org/jfree/chart/renderer/xy/StandardXYBarPainterTest.java
Java
lgpl-2.1
3,288
#include "Moose.h" #include "JoojakApp.h" #include "JoojakRevision.h" #include "AppFactory.h" #include "ActionFactory.h" #include "Syntax.h" /// Action #include "CLawAuxVariablesAction.h" #include "CLawICAction.h" #include "CommonPostProcessorAction.h" #include "AddMultiVariableAction.h" #include "AddMultiAuxVariableAction.h" /// 单元积分 #include "CLawCellKernel.h" #include "EmptyTimeDerivative.h" #include "ElasticityKernel.h" /// 面积分 #include "CLawFaceKernel.h" /// 初始条件 #include "CLawIC.h" #include "CFDPassFlowIC.h" /// 边界条件 #include "CLawBoundaryCondition.h" /// 函数 #include "CouetteFlowExact.h" /// 辅助kernel #include "CFDAuxVariable.h" #include "ArtificialViscosityAuxKernel.h" #include "EmptyTimeDerivative.h" /// 材料属性 #include "CLawFaceMaterial.h" #include "CLawCellMaterial.h" #include "CLawBoundaryMaterial.h" #include "LinearElasticityMaterial.h" /// 时间步长增加策略 #include "RatioTimeStepper.h" /// PostProcessor #include "CFDResidual.h" #include "ElementExtremeTimeDerivative.h" #include "NumTimeStep.h" #include "VariableResidual.h" #include "IsoVortexElementL2Error.h" #include "CouetteFlowElementL2Error.h" /// UserObject #include "CFDForceUserObject.h" /// VectorPostProcessor /// Executioner //#include "SteadyTransientExecutioner.h" /// mesh modifier #include "BuildSideSetFromBlock.h" /// problem #include "CLawProblem.h" #include "NavierStokesProblem.h" #include "EulerProblem.h" #include "SAProblem.h" #include "IsoVortexProblem.h" #include "CouetteFlowProblem.h" #include "SodProblem.h" #include "BlastWaveProblem.h" #include "Riemann1DProblem.h" #include "Riemann2DProblem.h" /// problem #include "FluxJumpIndicator.h" #include "TestJumpIndicator.h" template<> InputParameters validParams<JoojakApp>() { InputParameters params = validParams<MooseApp>(); params.set<bool>("use_legacy_uo_initialization") = false; params.set<bool>("use_legacy_uo_aux_computation") = false; return params; } JoojakApp::JoojakApp(const std::string & name, InputParameters parameters) : MooseApp(name, parameters) { srand(processor_id()); Moose::registerObjects(_factory); JoojakApp::registerObjects(_factory); Moose::associateSyntax(_syntax, _action_factory); JoojakApp::associateSyntax(_syntax, _action_factory); } JoojakApp::~JoojakApp() { } void JoojakApp::printHeader() { std::string line("*********************************\n\n"); Moose::out << COLOR_CYAN << line << COLOR_DEFAULT; Moose::out << "计算流体力学间断有限元计算器 JOOJAK \n\n"; Moose::out << "Joojak version: " << COLOR_MAGENTA << JOOJAK_REVISION << COLOR_DEFAULT << std::endl << std::endl; Moose::out << COLOR_CYAN << line << COLOR_DEFAULT; // // std::string joojak = // std::string(" _ _ _\n")+ // std::string(" | | ___ ___ (_) __ _| | __\n")+ // std::string(" _ | |/ _ \ / _ \| |/ _` | |/ /\n")+ // std::string(" | |_| | (_) | (_) | | (_| | <\n")+ // std::string(" \___/ \___/ \___// |\__,_|_|\_\\n")+ // std::string(" |__/\n"); // //Moose::out << joojak << std::endl; } void JoojakApp::run() { printHeader(); setupOptions(); runInputFile(); executeExecutioner(); } void JoojakApp::registerApps() { registerApp(JoojakApp); } void JoojakApp::registerObjects(Factory & factory) { /// 注册初始条件 registerInitialCondition(CFDPassFlowIC); registerInitialCondition(CLawIC); /// 注册边界条件 registerBoundaryCondition(CLawBoundaryCondition); /// 注册Kernel registerKernel(CLawCellKernel); registerKernel(EmptyTimeDerivative); registerKernel(ElasticityKernel); /// 注册DGKernel registerDGKernel(CLawFaceKernel); /// 注册材料属性 registerMaterial(LinearElasticityMaterial); registerMaterial(CLawFaceMaterial); registerMaterial(CLawCellMaterial); registerMaterial(CLawBoundaryMaterial); /// 注册函数 registerFunction(CouetteFlowExact); ///注册辅助kernel registerAux(CFDAuxVariable); registerAux(ArtificialViscosityAuxKernel); /// 注册时间步长 registerTimeStepper(RatioTimeStepper); /// 注册后处理 registerPostprocessor(CFDResidual); registerPostprocessor(ElementExtremeTimeDerivative); registerPostprocessor(NumTimeStep); registerPostprocessor(VariableResidual); registerPostprocessor(IsoVortexElementL2Error); registerPostprocessor(CouetteFlowElementL2Error); /// 注册UserObject registerPostprocessor(CFDForceUserObject); // registerExecutioner(SteadyTransientExecutioner); registerMeshModifier(BuildSideSetFromBlock); /// 注册Problem // registerProblem(CLawProblem); registerProblem(NavierStokesProblem); registerProblem(EulerProblem); registerProblem(SAProblem); registerProblem(IsoVortexProblem); registerProblem(CouetteFlowProblem); registerProblem(SodProblem); registerProblem(BlastWaveProblem); registerProblem(Riemann1DProblem); registerProblem(Riemann2DProblem); registerIndicator(FluxJumpIndicator); registerIndicator(TestJumpIndicator); } void JoojakApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory) { /// 注册Action syntax.registerActionSyntax("CLawICAction", "ICs", "add_ic"); registerAction(CLawICAction, "add_ic"); syntax.registerActionSyntax("CLawAuxVariablesAction", "AuxVariables"); registerAction(CLawAuxVariablesAction, "add_aux_variable"); registerAction(CLawAuxVariablesAction, "add_aux_kernel"); syntax.registerActionSyntax("CommonPostProcessorAction", "Postprocessors", "add_postprocessor"); registerAction(CommonPostProcessorAction, "add_postprocessor"); syntax.registerActionSyntax("AddMultiVariableAction", "Problem/Variables"); registerAction(AddMultiVariableAction, "add_variable"); registerAction(AddMultiVariableAction, "add_kernel"); registerAction(AddMultiVariableAction, "add_dg_kernel"); registerAction(AddMultiVariableAction, "add_bc"); syntax.registerActionSyntax("AddMultiAuxVariableAction", "Problem/AuxVariables/*"); registerAction(AddMultiAuxVariableAction, "add_aux_variable"); registerAction(AddMultiAuxVariableAction, "add_aux_kernel"); }
zbhui/Joojak
src/base/JoojakApp.C
C++
lgpl-2.1
6,113
<?php /*"****************************************************************************************************** * (c) 2004-2006 by MulchProductions, www.mulchprod.de * * (c) 2007-2015 by Kajona, www.kajona.de * * Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt * ********************************************************************************************************/ /** * db-driver for oracle using the ovi8-interface * * @package module_system * @author sidler@mulchprod.de * @since 3.4.1 */ class class_db_oci8 extends class_db_base { private $linkDB; //DB-Link private $strHost = ""; private $strUsername = ""; private $strPass = ""; private $strDbName = ""; private $intPort = ""; private $strDumpBin = "exp"; // Binary to dump db (if not in path, add the path here) // /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin/ private $strRestoreBin = "imp"; //Binary to restore db (if not in path, add the path here) private $bitTxOpen = false; /** * This method makes sure to connect to the database properly * * @param string $strHost * @param string $strUsername * @param string $strPass * @param string $strDbName * @param int $intPort * * @return bool * @throws class_exception */ public function dbconnect($strHost, $strUsername, $strPass, $strDbName, $intPort) { if($intPort == "") $intPort = "1521"; //save connection-details $this->strHost = $strHost; $this->strUsername = $strUsername; $this->strPass = $strPass; $this->strDbName = $strDbName; $this->intPort = $intPort; //try to set the NLS_LANG env attribute putenv("NLS_LANG=American_America.UTF8"); $this->linkDB = @oci_connect($strUsername, $strPass, $strHost.":".$intPort."/".$strDbName, "AL32UTF8"); if($this->linkDB !== false) { @oci_set_client_info($this->linkDB, "Kajona CMS"); return true; } else { throw new class_exception("Error connecting to database", class_exception::$level_FATALERROR); } } /** * Closes the connection to the database * @return void */ public function dbclose() { @oci_close($this->linkDB); } /** * Creates a single query in order to insert multiple rows at one time. * For most databases, this will create s.th. like * INSERT INTO $strTable ($arrColumns) VALUES (?, ?), (?, ?)... * * Please note that this method is used to create the query itself, based on the Kajona-internal syntax. * The query is fired to the database by class_db * * @param string $strTable * @param string[] $arrColumns * @param array $arrValueSets * @param class_db $objDb * * @return bool */ public function triggerMultiInsert($strTable, $arrColumns, $arrValueSets, class_db $objDb) { $bitReturn = true; $arrPlaceholder = array(); $arrSafeColumns = array(); foreach($arrColumns as $strOneColumn) { $arrSafeColumns[] = $this->encloseColumnName($strOneColumn); $arrPlaceholder[] = "?"; } $strPlaceholder = " (".implode(",", $arrPlaceholder).") "; $strColumnNames = " (".implode(",", $arrSafeColumns).") "; $arrParams = array(); $strQuery = "INSERT ALL "; foreach($arrValueSets as $arrOneSet) { $arrParams = array_merge($arrParams, $arrOneSet); $strQuery .= " INTO ".$this->encloseTableName($strTable)." ".$strColumnNames." VALUES ".$strPlaceholder." "; } $strQuery .= " SELECT * FROM dual"; $bitReturn = $objDb->_pQuery($strQuery, $arrParams) && $bitReturn; return $bitReturn; } /** * Sends a prepared statement to the database. All params must be represented by the ? char. * The params themself are stored using the second params using the matching order. * * @param string $strQuery * @param array $arrParams * * @return bool * @since 3.4 */ public function _pQuery($strQuery, $arrParams) { $strQuery = $this->processQuery($strQuery); $objStatement = $this->getParsedStatement($strQuery); if($objStatement === false) return false; foreach($arrParams as $intPos => $strValue) oci_bind_by_name($objStatement, ":".($intPos + 1), $arrParams[$intPos]); $bitAddon = OCI_COMMIT_ON_SUCCESS; if($this->bitTxOpen) $bitAddon = OCI_NO_AUTO_COMMIT; $bitResult = oci_execute($objStatement, $bitAddon); @oci_free_statement($objStatement); return $bitResult; } /** * This method is used to retrieve an array of resultsets from the database using * a prepared statement * * @param string $strQuery * @param array $arrParams * * @since 3.4 * @return array */ public function getPArray($strQuery, $arrParams) { $arrReturn = array(); $intCounter = 0; $strQuery = $this->processQuery($strQuery); $objStatement = $this->getParsedStatement($strQuery); if($objStatement === false) return false; foreach($arrParams as $intPos => $strValue) oci_bind_by_name($objStatement, ":".($intPos + 1), $arrParams[$intPos]); $bitAddon = OCI_COMMIT_ON_SUCCESS; if($this->bitTxOpen) $bitAddon = OCI_NO_AUTO_COMMIT; $resultSet = oci_execute($objStatement, $bitAddon); if(!$resultSet) return false; while($arrRow = oci_fetch_array($objStatement, OCI_BOTH + OCI_RETURN_NULLS)) { $arrRow = $this->parseResultRow($arrRow); $arrReturn[$intCounter++] = $arrRow; } @oci_free_statement($objStatement); return $arrReturn; } /** * Returns just a part of a recordset, defined by the start- and the end-rows, * defined by the params. Makes use of prepared statements. * <b>Note:</b> Use array-like counters, so the first row is startRow 0 whereas * the n-th row is the (n-1)th key!!! * * @param string $strQuery * @param array $arrParams * @param int $intStart * @param int $intEnd * * @return array * @since 3.4 */ public function getPArraySection($strQuery, $arrParams, $intStart, $intEnd) { //calculate the end-value: //array-counters to real-counters $intStart++; $intEnd++; //modify the query $strQuery = "SELECT * FROM ( SELECT a.*, ROWNUM rnum FROM ( ".$strQuery.") a WHERE ROWNUM <= ".$intEnd." ) WHERE rnum >= ".$intStart; //and load the array return $this->getPArray($strQuery, $arrParams); } /** * Returns the last error reported by the database. * Is being called after unsuccessful queries * * @return string */ public function getError() { $strError = oci_error($this->linkDB); return $strError; } /** * Returns ALL tables in the database currently connected to * * @return mixed */ public function getTables() { $arrTemp = $this->getPArray("SELECT table_name AS name FROM ALL_TABLES", array()); foreach($arrTemp as $intKey => $strValue) $arrTemp[$intKey]["name"] = uniStrtolower($strValue["name"]); return $arrTemp; } /** * Looks up the columns of the given table. * Should return an array for each row consting of: * array ("columnName", "columnType") * * @param string $strTableName * * @return array */ public function getColumnsOfTable($strTableName) { $arrReturn = array(); $arrTemp = $this->getPArray("select column_name, data_type from user_tab_columns where table_name=?", array(strtoupper($strTableName))); if(empty($arrTemp)) { return array(); } foreach($arrTemp as $arrOneColumn) { $arrReturn[] = array( "columnName" => strtolower($arrOneColumn["column_name"]), "columnType" => ($arrOneColumn["data_type"] == "integer" ? "int" : strtolower($arrOneColumn["data_type"])), ); } return $arrReturn; } /** * Returns the db-specific datatype for the kajona internal datatype. * Currently, this are * int * long * double * char10 * char20 * char100 * char254 * char500 * text * longtext * * @param string $strType * * @return string */ public function getDatatype($strType) { $strReturn = ""; if($strType == class_db_datatypes::STR_TYPE_INT) $strReturn .= " NUMBER(19,0) "; elseif($strType == class_db_datatypes::STR_TYPE_LONG) $strReturn .= " NUMBER(19, 0) "; elseif($strType == class_db_datatypes::STR_TYPE_DOUBLE) $strReturn .= " FLOAT (24) "; elseif($strType == class_db_datatypes::STR_TYPE_CHAR10) $strReturn .= " VARCHAR2( 10 ) "; elseif($strType == class_db_datatypes::STR_TYPE_CHAR20) $strReturn .= " VARCHAR2( 20 ) "; elseif($strType == class_db_datatypes::STR_TYPE_CHAR100) $strReturn .= " VARCHAR2( 100 ) "; elseif($strType == class_db_datatypes::STR_TYPE_CHAR254) $strReturn .= " VARCHAR2( 280 ) "; elseif($strType == class_db_datatypes::STR_TYPE_CHAR500) $strReturn .= " VARCHAR2( 500 ) "; elseif($strType == class_db_datatypes::STR_TYPE_TEXT) $strReturn .= " VARCHAR2( 4000 ) "; elseif($strType == class_db_datatypes::STR_TYPE_LONGTEXT) $strReturn .= " CLOB "; else $strReturn .= " VARCHAR( 254 ) "; return $strReturn; } /** * Renames a single column of the table * * @param $strTable * @param $strOldColumnName * @param $strNewColumnName * @param $strNewDatatype * * @return bool * @since 4.6 */ public function changeColumn($strTable, $strOldColumnName, $strNewColumnName, $strNewDatatype) { $bitReturn = $this->_pQuery("ALTER TABLE ".($this->encloseTableName($strTable))." RENAME COLUMN ".($this->encloseColumnName($strOldColumnName)." TO ".$this->encloseColumnName($strNewColumnName)), array()); return $bitReturn && $this->_pQuery("ALTER TABLE ".$this->encloseTableName($strTable)." MODIFY ( ".$this->encloseColumnName($strNewColumnName)." ".$this->getDatatype($strNewDatatype)." )", array()); } /** * Used to send a create table statement to the database * By passing the query through this method, the driver can * add db-specific commands. * The array of fields should have the following structure * $array[string columnName] = array(string datatype, boolean isNull [, default (only if not null)]) * whereas datatype is one of the following: * int * long * double * char10 * char20 * char100 * char254 * char500 * text * longtext * * @param string $strName * @param array $arrFields array of fields / columns * @param array $arrKeys array of primary keys * @param array $arrIndices array of additional indices * @param bool $bitTxSafe Should the table support transactions? * * @return bool */ public function createTable($strName, $arrFields, $arrKeys, $arrIndices = array(), $bitTxSafe = true) { $strQuery = ""; //loop over existing tables to check, if the table already exists $arrTables = $this->getTables(); foreach($arrTables as $arrOneTable) { if($arrOneTable["name"] == $strName) return true; } //build the oracle code $strQuery .= "CREATE TABLE ".$strName." ( \n"; //loop the fields foreach($arrFields as $strFieldName => $arrColumnSettings) { $strQuery .= " ".$strFieldName." "; $strQuery .= $this->getDatatype($arrColumnSettings[0]); //any default? if(isset($arrColumnSettings[2])) $strQuery .= "DEFAULT ".$arrColumnSettings[2]." "; //nullable? if($arrColumnSettings[1] === true) { $strQuery .= " NULL "; } else { $strQuery .= " NOT NULL "; } $strQuery .= " , \n"; } //primary keys $strQuery .= " CONSTRAINT pk_".generateSystemid()." primary key ( ".implode(" , ", $arrKeys)." ) \n"; $strQuery .= ") "; $bitCreate = $this->_pQuery($strQuery, array()); if($bitCreate && count($arrIndices) > 0) { $strQuery = "CREATE INDEX ix_".generateSystemid()." ON ".$strName." ( ".implode(", ", $arrIndices).") "; $bitCreate = $bitCreate && $this->_pQuery($strQuery, array()); } return $bitCreate; } /** * Starts a transaction * * @return void */ public function transactionBegin() { $this->bitTxOpen = true; } /** * Ends a successful operation by committing the transaction * @return void */ public function transactionCommit() { oci_commit($this->linkDB); $this->bitTxOpen = false; } /** * Ends a non-successful transaction by using a rollback * @return void */ public function transactionRollback() { oci_rollback($this->linkDB); $this->bitTxOpen = false; } /** * @return array|mixed */ public function getDbInfo() { $arrReturn = array(); $arrReturn["dbdriver"] = "oci8-oracle-extension"; $arrReturn["dbserver"] = oci_server_version($this->linkDB); $arrReturn["dbclient"] = function_exists("oci_client_version") ? oci_client_version($this->linkDB) : ""; return $arrReturn; } //--- DUMP & RESTORE ------------------------------------------------------------------------------------ /** * Dumps the current db * * @param string $strFilename * @param array $arrTables * * @return bool */ public function dbExport($strFilename, $arrTables) { $strFilename = _realpath_.$strFilename; $strTables = implode(",", $arrTables); /* if ($this->strPass != "") { $strParamPass = " -p".$this->strPass; } */ $strCommand = $this->strDumpBin." ".$this->strUsername."/".$this->strPass." CONSISTENT=n TABLES=".$strTables." FILE='".$strFilename."'"; class_logger::getInstance(class_logger::DBLOG)->addLogRow("dump command: ".$strCommand, class_logger::$levelInfo); //Now do a systemfork $intTemp = ""; system($strCommand, $intTemp); class_logger::getInstance(class_logger::DBLOG)->addLogRow($this->strDumpBin." exited with code ".$intTemp, class_logger::$levelInfo); return $intTemp == 0; } /** * Imports the given db-dump to the database * * @param string $strFilename * * @return bool */ public function dbImport($strFilename) { $strFilename = _realpath_.$strFilename; $strCommand = $this->strRestoreBin." ".$this->strUsername."/".$this->strPass." FILE='".$strFilename."'"; $intTemp = ""; system($strCommand, $intTemp); class_logger::getInstance(class_logger::DBLOG)->addLogRow($this->strRestoreBin." exited with code ".$intTemp, class_logger::$levelInfo); return $intTemp == 0; } /** * Transforms the prepared statement into a valid oracle syntax. * This is done by replying the ?-chars by :x entries. * * @param string $strQuery * * @return string */ private function processQuery($strQuery) { $intCount = 1; while(uniStrpos($strQuery, "?") !== false) { $intPos = uniStrpos($strQuery, "?"); $strQuery = substr($strQuery, 0, $intPos).":".$intCount++.substr($strQuery, $intPos + 1); } return $strQuery; } /** * Does as cache-lookup for prepared statements. * Reduces the number of recompiles at the db-side. * * @param string $strQuery * * @return resource * @since 3.4 */ private function getParsedStatement($strQuery) { if(uniStripos($strQuery, "select") !== false) { $strQuery = uniStrReplace(array(" as ", " AS "), array(" ", " "), $strQuery); } $objStatement = oci_parse($this->linkDB, $strQuery); return $objStatement; } /** * converts a result-row. changes all keys to lower-case keys again * * @param array $arrRow * * @return array */ private function parseResultRow(array $arrRow) { $arrRow = array_change_key_case($arrRow, CASE_LOWER); if(isset($arrRow["count(*)"])) $arrRow["COUNT(*)"] = $arrRow["count(*)"]; foreach($arrRow as $intKey => $mixedValue) { if(is_object($mixedValue)) { $arrRow[$intKey] = $mixedValue->load(); $mixedValue->free(); } } return $arrRow; } /** * A method triggered in special cases in order to * have even the caches stored at the db-driver being flushed. * This could get important in case of schema updates since pre-compiled queries may get invalid due * to updated table definitions. * * @return void */ public function flushQueryCache() { } }
jinshana/kajonacms
module_system/system/db/class_db_oci8.php
PHP
lgpl-2.1
18,100
"""""" from __future__ import annotations from typing import Any, Dict, List from flask import g from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.orm import relationship from sqlalchemy.schema import Column, ForeignKey from whoosh.fields import STORED from .base import AUDITABLE, EDITABLE, SEARCHABLE, SYSTEM from .subjects import User class OwnedMixin: __index_to__ = ( ("creator", ("creator",)), ("creator_name", (("creator_name", STORED),)), ("owner", ("owner",)), ("owner_name", (("owner_name", STORED),)), ) def __init__(self, *args: list, **kwargs: dict[str, Any]): try: user = g.user if not self.creator and not g.user.is_anonymous: self.creator = user if not self.owner and not g.user.is_anonymous: self.owner = user except (RuntimeError, AttributeError): pass @declared_attr def creator_id(cls): return Column(ForeignKey(User.id), info=SYSTEM) @declared_attr def creator(cls): primary_join = f"User.id == {cls.__name__}.creator_id" return relationship( User, primaryjoin=primary_join, lazy="joined", uselist=False, info=SYSTEM | SEARCHABLE, ) @property def creator_name(self) -> str: return str(self.creator) if self.creator else "" @declared_attr def owner_id(cls): return Column(ForeignKey(User.id), info=EDITABLE | AUDITABLE) @declared_attr def owner(cls): primary_join = f"User.id == {cls.__name__}.owner_id" return relationship( User, primaryjoin=primary_join, lazy="joined", uselist=False, info=EDITABLE | AUDITABLE | SEARCHABLE, ) @property def owner_name(self) -> str: return str(self.owner) if self.owner else ""
abilian/abilian-core
src/abilian/core/models/owned.py
Python
lgpl-2.1
1,952
/* * Omadac - The Open Map Database Compiler * http://omadac.org * * (C) 2010, Harald Wellmann and Contributors * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.omadac.loader; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; public class LoaderFileWriter { private PrintWriter writer; private boolean firstColumn = true; private long numRows; public LoaderFileWriter(File file) throws FileNotFoundException, UnsupportedEncodingException { writer = new PrintWriter(file, "UTF-8"); } public void writeColumn(Object obj) { if (firstColumn) { firstColumn = false; } else { writer.print('\t'); } writer.print(obj); } public void terminateRow() { writer.println(); numRows++; firstColumn = true; } public void close() { writer.close(); } public long getNumRows() { return numRows; } }
hwellmann/omadac
appl/plugins/loader/src/org/omadac/loader/LoaderFileWriter.java
Java
lgpl-2.1
1,577
<?php /* * @author: Javier Reyes Gomez (jreyes@escire.com) * @date: 27/01/2006 * @copyright (C) 2006 Javier Reyes Gomez (eScire.com) * @license http://www.gnu.org/copyleft/lgpl.html GNU/LGPL */ /** * Show a help text */ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__)) !== false) { header("location: index.php"); exit; } function smarty_block_ws_help($params, $content, &$smarty) { global $prefs; extract($params); if (!isset($content)) return "error"; $smarty->assign('param1', "param"); $smarty->assign_by_ref('help_content', $content); return $smarty->fetch('tiki-workspaces_help.tpl'); } ?>
4thAce/evilhow
lib/smarty_tiki/block.ws_help.php
PHP
lgpl-2.1
699
/* --------------------------------------------------------------------------- commonc++ - A C++ Common Class Library Copyright (C) 2005-2012 Mark A Lindner This file is part of commonc++. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. --------------------------------------------------------------------------- */ #ifndef __ccxx_JavaContext_hxx #define __ccxx_JavaContext_hxx #include <commonc++/Common.h++> #include <commonc++/Exception.h++> #include <commonc++/String.h++> #include <commonc++/JavaException.h++> #include <jni.h> #include <cstdarg> namespace ccxx { class JavaVirtualMachine; // fwd decl /** A structure representing a Java native method. * * @author Mark Lindner */ struct JavaNativeMethod { /** The signature of the native method. */ String signature; /** A pointer to the C function that implements the native method. */ void *function; }; /** * * When the <i>Invocation Interface</i> is being used (that is, when * a C++ program calls into Java code), the * <code>getContext()</code> method of the JavaVirtualMachine class * is used to obtain an appropriate JavaContext object. In C++ code * that implements a Java native method, on the other hand, a * JavaContext instance must be explicitly constructed from the * <code>JNIEnv</code> pointer that was passed into the native * function. * * This is a lightweight object that should typically be stack-allocated, * and may be passed and copied by value. * * @author Mark Lindner */ class COMMONCPPJVM_API JavaContext { friend class JavaVirtualMachine; public: /** Construct a new JavaContext for the given JNI environment pointer. * * @param env The JNI environment pointer. */ JavaContext(JNIEnv *env); /** Destructor. */ ~JavaContext(); /** Encode a datatype into a JNI datatype descriptor. For example, * <tt>"String[]"</tt> is encoded as <tt>"[Ljava/lang/String;"</tt>. * * @param type The datatype. * @return The encoding of the datatype. */ static String encodeType(const String &type); /** Parse a method signature into a method name, a JNI method descriptor, * and a static flag. For example, <tt>"static int foo(int, char[])"</tt> * results in a method name of <tt>"foo"</tt>, a JNI method descriptor * of <tt>"(I[C)I"</tt>, and a static flag of <b>true</b>. * * @param signature The signature to parse. * @param method The string in which to place the method name. * @param descriptor The string in which to place the JNI method * descriptor. * @param isStatic The flag in which to store the static flag * (<b>true</b> if a <tt>"static"</tt> qualifier is present, <b>false</b> * otherwise). * @return <b>true</b> if the signature was parsed successfully, * <b>false</b> otherwise. */ static bool parseSignature(const String &signature, String& method, String& descriptor, bool &isStatic); /** Look up a class by name. The class name must be fully qualified (for * example, <tt>"java.util.Vector"</tt>), with the following classes as * the only exceptions: <tt>String</tt>, <tt>Object</tt>, <tt>Class</tt>. * * @param name The name of the class. * @return A reference to the Java class. * @throw JavaException If the class was not found. */ jclass findClass(const String &name) throw(JavaException); /** Look up a method or constructor by signature. The signature * must be specified in Java source code form, without parameter * names, for example <tt>"int foo(int, byte[])"</tt> or * <tt>"static boolean bar(java.lang.Vector, int, String)"</tt>, or * <tt>"(int, String, String)"</tt> (a constructor). * * @param clazz The Java class. * @param signature The signature of the method. * @return A reference to the method. * @throw JavaException If the method was not found. */ jmethodID findMethod(jclass clazz, const String &signature) throw(JavaException); /** Instantiate a new Java object. * * @param clazz The class. * @param constructor The constructor to invoke. * @throw JavaException If the constructor throws an exception, or if * an invocation error occurs. */ jobject createObject(jclass clazz, jmethodID constructor, ...) throw(JavaException); /** Instantiate a new Java object. * * @param clazz The class. * @param constructor The constructor to invoke. * @param args The arguments to pass to the constructor. * @throw JavaException If the constructor throws an exception, or if * an invocation error occurs. */ jobject createObjectVA(jclass clazz, jmethodID constructor, va_list args) throw(JavaException); /** Call a Java method that returns void. * * @param object The object instance. * @param method The method to call. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ void callVoidMethod(jobject object, jmethodID method, ...) throw(JavaException); /** Call a Java method that returns a Java Object. * * @param object The object instance. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ jobject callObjectMethod(jobject object, jmethodID method, ...) throw(JavaException); /** Call a Java method that returns a java.lang.String. * * @param object The object instance. * @param method The method to call. * @return The method's return value, encoded as a String. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ String callStringMethod(jobject object, jmethodID method, ...) throw(JavaException); /** Call a Java method that returns a java.lang.String. * * @param object The object instance. * @param method The method to call. * @return The method's return value, encoded as a WString. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ WString callWStringMethod(jobject object, jmethodID method, ...) throw(JavaException); /** Call a Java method that returns a boolean. * * @param object The object instance. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ bool callBooleanMethod(jobject object, jmethodID method, ...) throw(JavaException); /** Call a Java method that returns a byte. * * @param object The object instance. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ byte_t callByteMethod(jobject object, jmethodID method, ...) throw(JavaException); /** Call a Java method that returns a char. * * @param object The object instance. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ char16_t callCharMethod(jobject object, jmethodID method, ...) throw(JavaException); /** Call a Java method that returns a short. * * @param object The object instance. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ int16_t callShortMethod(jobject object, jmethodID method, ...) throw(JavaException); /** Call a Java method that returns an int. * * @param object The object instance. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ int32_t callIntMethod(jobject object, jmethodID method, ...) throw(JavaException); /** Call a Java method that returns a long. * * @param object The object instance. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ int64_t callLongMethod(jobject object, jmethodID method, ...) throw(JavaException); /** Call a Java method that returns a float. * * @param object The object instance. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ float callFloatMethod(jobject object, jmethodID method, ...) throw(JavaException); /** Call a Java method that returns a double. * * @param object The object instance. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ double callDoubleMethod(jobject object, jmethodID method, ...) throw(JavaException); /** Call a non-virtual Java method that returns void. * * @param object The object instance. * @param clazz The method's defining class. * @param method The method to call. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ void callNonvirtualVoidMethod(jobject object, jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a non-virtual Java method that returns a Java object. * * @param object The object instance. * @param clazz The method's defining class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ jobject callNonvirtualObjectMethod(jobject object, jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a non-virtual Java method that returns a boolean. * * @param object The object instance. * @param clazz The method's defining class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ bool callNonvirtualBooleanMethod(jobject object, jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a non-virtual Java method that returns a byte. * * @param object The object instance. * @param clazz The method's defining class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ byte_t callNonvirtualByteMethod(jobject object, jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a non-virtual Java method that returns a char. * * @param object The object instance. * @param clazz The method's defining class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ char16_t callNonvirtualCharMethod(jobject object, jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a non-virtual Java method that returns a short. * * @param object The object instance. * @param clazz The method's defining class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ int16_t callNonvirtualShortMethod(jobject object, jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a non-virtual Java method that returns an int. * * @param object The object instance. * @param clazz The method's defining class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ int32_t callNonvirtualIntMethod(jobject object, jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a non-virtual Java method that returns a long. * * @param object The object instance. * @param clazz The method's defining class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ int64_t callNonvirtualLongMethod(jobject object, jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a non-virtual Java method that returns a float. * * @param object The object instance. * @param clazz The method's defining class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ float callNonvirtualFloatMethod(jobject object, jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a non-virtual Java method that returns a double. * * @param object The object instance. * @param clazz The method's defining class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ double callNonvirtualDoubleMethod(jobject object, jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a static Java method that returns void. * * @param clazz The Java class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ void callStaticVoidMethod(jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a static Java method that returns a Java Object. * * @param clazz The Java class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ jobject callStaticObjectMethod(jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a static Java method that returns a java.lang.String * * @param clazz The Java class. * @param method The method to call. * @return The method's return value, as a String. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ String callStaticStringMethod(jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a static Java method that returns a java.lang.String * * @param clazz The Java class. * @param method The method to call. * @return The method's return value, as a WString. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ WString callStaticWStringMethod(jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a static Java method that returns a boolean. * * @param clazz The Java class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ bool callStaticBooleanMethod(jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a static Java method that returns a byte. * * @param clazz The Java class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ byte_t callStaticByteMethod(jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a static Java method that returns a char. * * @param clazz The Java class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ char16_t callStaticCharMethod(jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a static Java method that returns a short. * * @param clazz The Java class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ int16_t callStaticShortMethod(jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a static Java method that returns an int. * * @param clazz The Java class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ int32_t callStaticIntMethod(jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a static Java method that returns a long. * * @param clazz The Java class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ int64_t callStaticLongMethod(jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a static Java method that returns a float. * * @param clazz The Java class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ float callStaticFloatMethod(jclass clazz, jmethodID method, ...) throw(JavaException); /** Call a static Java method that returns a double. * * @param clazz The Java class. * @param method The method to call. * @return The method's return value. * @throw JavaException If the called method throws an exception, or if * an invocation error occurs. */ double callStaticDoubleMethod(jclass clazz, jmethodID method, ...) throw(JavaException); /** Determine if a Java exception has been thrown in the current thread. * * @param verbose If <b>true</b>, print the exception stack trace * to standard error. * @return <b>true</b> if an exception has been thrown, <b>false</b> * otherwise. */ bool checkException(bool verbose = false); /** Clear any pending Java exception that is currently being thrown * in the current thread. */ void clearException() throw(); /** Get the pending Java exception, if one is currently being thrown * in the current thread. * * @return The exception object, or <b>NULL</b> if none. */ jthrowable getException() throw(); /** Throw a Java exception. * * @param exception The class of the exception. * @param message The exception message. * @return <b>true</b> on success, <b>false</b> otherwise. */ bool throwException(jclass exception, const String &message); /** Look up a field by signature. The signature must be specified in * Java source code form, for example <tt>"String name"</tt> or * <tt>"static int foo"</tt>. * * @param clazz The Java class. * @param signature The signature of the field. * @return A reference to the field. * @throw JavaException If the field was not found. */ jfieldID findField(jclass clazz, const String &signature) throw(JavaException); /** Get the value of an Object field in an Object. * * @param object The object. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ jobject getObjectField(jobject object, jfieldID field) throw(JavaException); /** Get the value of an boolean field in an Object. * * @param object The object. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ bool getBooleanField(jobject object, jfieldID field) throw(JavaException); /** Get the value of a byte field in an Object. * * @param object The object. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ byte_t getByteField(jobject object, jfieldID field) throw(JavaException); /** Get the value of a char field in an Object. * * @param object The object. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ char16_t getCharField(jobject object, jfieldID field) throw(JavaException); /** Get the value of a short field in an Object. * * @param object The object. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ int16_t getShortField(jobject object, jfieldID field) throw(JavaException); /** Get the value of an int field in an Object. * * @param object The object. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ int32_t getIntField(jobject object, jfieldID field) throw(JavaException); /** Get the value of a long field in an Object. * * @param object The object. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ int64_t getLongField(jobject object, jfieldID field) throw(JavaException); /** Get the value of a float field in an Object. * * @param object The object. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ float getFloatField(jobject object, jfieldID field) throw(JavaException); /** Get the value of a double field in an Object. * * @param object The object. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ double getDoubleField(jobject object, jfieldID field) throw(JavaException); /** Get the value of a java.lang.String field in an Object. * * @param object The object. * @param field The field ID. * @return The value of the field, encoded as a String. * @throw JavaException If an error occurs. */ String getStringField(jobject object, jfieldID field) throw(JavaException); /** Get the value of a java.lang.String field in an Object. * * @param object The object. * @param field The field ID. * @return The value of the field, encoded as a WString. * @throw JavaException If an error occurs. */ WString getWStringField(jobject object, jfieldID field) throw(JavaException); /** Get the value of a static Object field in a class. * * @param clazz The class. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ jobject getStaticObjectField(jclass clazz, jfieldID field) throw(JavaException); /** Get the value of a static boolean field in a class. * * @param clazz The class. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ bool getStaticBooleanField(jclass clazz, jfieldID field) throw(JavaException); /** Get the value of a static byte field in a class. * * @param clazz The class. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ byte_t getStaticByteField(jclass clazz, jfieldID field) throw(JavaException); /** Get the value of a static char field in a class. * * @param clazz The class. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ char16_t getStaticCharField(jclass clazz, jfieldID field) throw(JavaException); /** Get the value of a static short field in a class. * * @param clazz The class. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ int16_t getStaticShortField(jclass clazz, jfieldID field) throw(JavaException); /** Get the value of a static int field in a class. * * @param clazz The class. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ int32_t getStaticIntField(jclass clazz, jfieldID field) throw(JavaException); /** Get the value of a static long field in a class. * * @param clazz The class. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ int64_t getStaticLongField(jclass clazz, jfieldID field) throw(JavaException); /** Get the value of a static float field in a class. * * @param clazz The class. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ float getStaticFloatField(jclass clazz, jfieldID field) throw(JavaException); /** Get the value of a static double field in a class. * * @param clazz The class. * @param field The field ID. * @return The value of the field. * @throw JavaException If an error occurs. */ double getStaticDoubleField(jclass clazz, jfieldID field) throw(JavaException); /** Get the value of a static String field in a class. * * @param clazz The class. * @param field The field ID. * @return The value of the field as a String. * @throw JavaException If an error occurs. */ String getStaticStringField(jclass clazz, jfieldID field) throw(JavaException); /** Get the value of a static String field in a class. * * @param clazz The class. * @param field The field ID. * @return The value of the field as a WString. * @throw JavaException If an error occurs. */ WString getStaticWStringField(jclass clazz, jfieldID field) throw(JavaException); /** Set the value of an Object field in an object. * * @param object The object. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setObjectField(jobject object, jfieldID field, jobject value) throw(JavaException); /** Set the value of a boolean field in an object. * * @param object The object. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setBooleanField(jobject object, jfieldID field, bool value) throw(JavaException); /** Set the value of a byte field in an object. * * @param object The object. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setByteField(jobject object, jfieldID field, byte_t value) throw(JavaException); /** Set the value of a char field in an object. * * @param object The object. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setCharField(jobject object, jfieldID field, char16_t value) throw(JavaException); /** Set the value of a short field in an object. * * @param object The object. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setShortField(jobject object, jfieldID field, int16_t value) throw(JavaException); /** Set the value of an int field in an object. * * @param object The object. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setIntField(jobject object, jfieldID field, int32_t value) throw(JavaException); /** Set the value of a long field in an object. * * @param object The object. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setLongField(jobject object, jfieldID field, int64_t value) throw(JavaException); /** Set the value of a float field in an object. * * @param object The object. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setFloatField(jobject object, jfieldID field, float value) throw(JavaException); /** Set the value of a double field in an object. * * @param object The object. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setDoubleField(jobject object, jfieldID field, double value) throw(JavaException); /** Set the value of a java.lang.String field in an object. * * @param object The object. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setStringField(jobject object, jfieldID field, const String &value) throw(JavaException); /** Set the value of a java.lang.String field in an object. * * @param object The object. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setWStringField(jobject object, jfieldID field, const WString &value) throw(JavaException); /** Set the value of a static Object field in a class. * * @param clazz The class. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setStaticObjectField(jclass clazz, jfieldID field, jobject value) throw(JavaException); /** Set the value of a static boolean field in a class. * * @param clazz The class. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setStaticBooleanField(jclass clazz, jfieldID field, bool value) throw(JavaException); /** Set the value of a static byte field in a class. * * @param clazz The class. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setStaticByteField(jclass clazz, jfieldID field, byte_t value) throw(JavaException); /** Set the value of a static char field in a class. * * @param clazz The class. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setStaticCharField(jclass clazz, jfieldID field, char16_t value) throw(JavaException); /** Set the value of a static short field in a class. * * @param clazz The class. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setStaticShortField(jclass clazz, jfieldID field, int16_t value) throw(JavaException); /** Set the value of a static int field in a class. * * @param clazz The class. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setStaticIntField(jclass clazz, jfieldID field, int32_t value) throw(JavaException); /** Set the value of a static long field in a class. * * @param clazz The class. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setStaticLongField(jclass clazz, jfieldID field, int64_t value) throw(JavaException); /** Set the value of a static float field in a class. * * @param clazz The class. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setStaticFloatField(jclass clazz, jfieldID field, float value) throw(JavaException); /** Set the value of a static double field in a class. * * @param clazz The class. * @param field The field ID. * @param value The new value for the field. * @throw JavaException If an error occurs. */ void setStaticDoubleField(jclass clazz, jfieldID field, double value) throw(JavaException); /** Create a Java byte array. * * @param length The length of the array. * @return The array. * @throw JavaException If an error occurs. */ jbyteArray createByteArray(uint_t length) throw(JavaException); /** Set an element of a Java object array. * * @param array The array. * @param index The index of the element. * @param value The new value for the element. * @throw JavaException If an error occurs. */ void setObjectArrayElement(jobjectArray array, uint_t index, jobject value) throw(JavaException); /** Get an element of a Java object array. * * @param array The array. * @param index The index of the element. * @return The value of the element. * @throw JavaException If an error occurs. */ jobject getObjectArrayElement(jobjectArray array, uint_t index) throw(JavaException); /** Get the length of a Java array. * * @param array The array. * @return The number of elements in the array. * @throw JavaException If an error occurs. */ uint_t getArrayLength(jarray array) throw(JavaException); /** Create a new Java DirectByteBuffer. * * @param buf A pointer to the natively-allocated memory block for the * buffer. * @param size The size of the memory block, in bytes. * @return The newly created DirectByteBuffer object. * @throw JavaException If an error occurs. */ jobject createDirectByteBuffer(byte_t *buf, size_t size) throw(JavaException); /** Get a pointer to and the size of the memory region occupied by * a Java DirectBuffer. * * @param buf The DirectBuffer object. * @param size The variable in which to store the size of the memory * region. * @return A pointer to the beginning of the memory region, or <b>NULL</b> * on failure. */ void *getDirectBufferRegion(jobject buf, uint64_t &size); /** Create a local reference to a Java object. * * @param object The object. * @return The new local reference. * @throw JavaException If an error occurs. */ jobject createLocalRef(jobject object) throw(JavaException); /** Delete a local reference. * * @param ref The reference. */ void deleteLocalRef(jobject ref); /** Reserve space for local references. * * @param capacity The number of local references to reserve capacity for. * @throw JavaException If an error occurs. */ void ensureLocalCapacity(uint_t capacity) throw(JavaException); /** Create a global reference to a Java object. * * @param object The object. * @return The new global reference. * @throw JavaException If an error occurs. */ jobject createGlobalRef(jobject object) throw(JavaException); /** Delete a local reference. * * @param ref The reference. */ void deleteGlobalRef(jobject ref); /** Decode a java.lang.String into a String. * * @param str The Java string. * @return The decoded String. * @throw JavaException If an error occurs. */ String decodeString(jstring str) throw(JavaException); /** Decode a java.lang.String into a WString. * * @param str The Java string. * @return The decoded WString. * @throw JavaException If an error occurs. */ WString decodeWString(jstring str) throw(JavaException); /** Encode a String into a java.lang.String. * * @param str The String. * @return The encoded Java string. * @throw JavaException If an error occurs. */ jstring encodeString(const String &str) throw(JavaException); /** Encode a WString into a java.lang.String. * * @param str The String. * @return The encoded Java string. * @throw JavaException If an error occurs. */ jstring encodeWString(const WString &str) throw(JavaException); /** Get the length of a Java string. * * @param str The string. * @return The length of the string. */ uint_t getStringLength(jstring str); /** Obtain a pointer to the body of a primitive Java array. This * data may be used and modified safely (without any intervening * JNI calls) until a matching call to <b>releaseArrayData()</b>. * * @param array The primitive array. * @param length A parameter in which to store the length of the buffer * containing the array data. * @param isCopy If not NULL, a pointer in which to store a flag * indicating whether the returned buffer is a copy of the array * data. * @return A pointer to a buffer containing the array data. * @throw JavaException If an error occurs. */ void *getArrayData(jarray array, uint_t &length, bool *isCopy = NULL) throw(JavaException); /** Release the buffer returned by <b>getArrayData()</b>. The data will * be copied back into the original array, if necessary. * * @param array The primitive array. * @param data The buffer containing the array data. */ void releaseArrayData(jarray array, void *data); /** Create a Java byte array. * * @param data The data to copy into the array. * @param length The length of the array. * @return The newly created array. * @throw JavaException If an error occurs. */ jbyteArray createByteArray(const byte_t *data, size_t length) throw(JavaException); /** Create a Java object array. * * @param type The array type. * @param length The length of the array. * @param initialValue An optional initial value to store into every * element in the new array. * @return The newly created array. * @throw JavaException If an error occurs. */ jarray createObjectArray(jclass type, uint_t length, jobject initialValue = NULL) throw(JavaException); /** Test two Java object references for equality. * * @param object1 The first object reference. * @param object2 The second object reference. * @return <b>true</b> if the references both refer to the same object, * <b>false</b> otherwise. */ bool isSameObject(jobject object1, jobject object2); /** Test if a Java object is an instance of an interface or another * class. * * @param object The object. * @param clazz The class or interface. * @return <b>true</b> if the object is an instance of the other class or * interface, <b>false</b> otherwise. */ bool isInstanceOf(jobject object, jclass clazz); /** Test if an object of a class or interface can be safely cast to * a class or interface of another class. * * @param clazz1 The class of the object to be cast. * @param clazz2 The class of the cast. * @return <b>true</b> if the cast is valid, <b>false</b> otherwise. */ bool isAssignableFrom(jclass clazz1, jclass clazz2); /** Get the class for a Java object. * * @param object The object. * @return The class. */ jclass getClassForObject(jobject object); /** Get the superclass for a Java class. * * @param clazz The class. * @return The superclass, or NULL if the class is an interface or * if it is <code>java.lang.Object</code>. */ jclass getSuperclass(jclass clazz); /** Enter the monitor associated with a Java object. The method blocks * if another thread is currently in the monitor. * * @param object The object. * @throw JavaException If an error occurs. */ void enterMonitor(jobject object) throw(JavaException); /** Exit the monitor associated with a Java object. * * @param object The object. * @throw JavaException If an error occurs. */ void exitMonitor(jobject object) throw(JavaException); /** Register native methods for a Java class. * * @param clazz The class. * @param methods An array of native methods to register. The last element * in the array must have the <b>function</b> field set to <b>NULL</b>. * @throw JavaException If an error occurs. */ void registerNativeMethods(jclass clazz, const JavaNativeMethod methods[]) throw(JavaException); /** Unregister all native methods for a Java class. * * @param clazz The class. */ void unregisterNativeMethods(jclass clazz); /** Create a new local reference frame. * * @param capacity The minimal local reference capacity of the new frame. * @throw JavaException If an error occurs. */ void pushLocalFrame(uint_t capacity = 8) throw(JavaException); /** Destroy the topmost local reference frame. All local references * created in the frame will be freed. */ void popLocalFrame(); /** Determine if verbose mode is enabled for this context. */ inline bool isVerbose() const throw() { return(_verbose); } private: void attach(JavaVirtualMachine *jvm, JNIEnv* env, bool verbose) throw(); void detach() throw(); inline bool isAttached() const throw() { return(_env != NULL); } inline JNIEnv *getEnv() const throw() { return(_env); } JavaVirtualMachine *_jvm; JNIEnv *_env; bool _verbose; }; }; // namespace ccxx #endif // __ccxx_JavaContext_hxx /* end of header file */
PhoenixClub/libcommoncpp
lib/commonc++/JavaContext.h++
C++
lgpl-2.1
42,571
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "searchresultwidget.h" #include "searchresulttreeview.h" #include "searchresulttreemodel.h" #include "searchresulttreeitems.h" #include "searchresulttreeitemroles.h" #include "findplugin.h" #include "itemviewfind.h" #include <aggregation/aggregate.h> #include <coreplugin/coreplugin.h> #include <QDir> #include <QFrame> #include <QLabel> #include <QLineEdit> #include <QToolButton> #include <QCheckBox> #include <QVBoxLayout> #include <QHBoxLayout> static const int SEARCHRESULT_WARNING_LIMIT = 200000; static const char SIZE_WARNING_ID[] = "sizeWarningLabel"; namespace Core { namespace Internal { class WideEnoughLineEdit : public QLineEdit { Q_OBJECT public: WideEnoughLineEdit(QWidget *parent):QLineEdit(parent){ connect(this, SIGNAL(textChanged(QString)), this, SLOT(updateGeometry())); } ~WideEnoughLineEdit(){} QSize sizeHint() const { QSize sh = QLineEdit::minimumSizeHint(); sh.rwidth() += qMax(25 * fontMetrics().width(QLatin1Char('x')), fontMetrics().width(text())); return sh; } public slots: void updateGeometry() { QLineEdit::updateGeometry(); } }; } // namespace Internal } // namespace Core using namespace Core; using namespace Core::Internal; SearchResultWidget::SearchResultWidget(QWidget *parent) : QWidget(parent), m_count(0), m_preserveCaseSupported(true), m_isShowingReplaceUI(false), m_searchAgainSupported(false) { QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(0); layout->setSpacing(0); setLayout(layout); QFrame *topWidget = new QFrame; QPalette pal; pal.setColor(QPalette::Window, QColor(255, 255, 225)); pal.setColor(QPalette::WindowText, Qt::black); topWidget->setPalette(pal); topWidget->setFrameStyle(QFrame::Panel | QFrame::Raised); topWidget->setLineWidth(1); topWidget->setAutoFillBackground(true); QHBoxLayout *topLayout = new QHBoxLayout(topWidget); topLayout->setMargin(2); topWidget->setLayout(topLayout); layout->addWidget(topWidget); m_messageWidget = new QFrame; pal.setColor(QPalette::WindowText, Qt::red); m_messageWidget->setPalette(pal); m_messageWidget->setFrameStyle(QFrame::Panel | QFrame::Raised); m_messageWidget->setLineWidth(1); m_messageWidget->setAutoFillBackground(true); QHBoxLayout *messageLayout = new QHBoxLayout(m_messageWidget); messageLayout->setMargin(2); m_messageWidget->setLayout(messageLayout); QLabel *messageLabel = new QLabel(tr("Search was canceled.")); messageLabel->setPalette(pal); messageLayout->addWidget(messageLabel); layout->addWidget(m_messageWidget); m_messageWidget->setVisible(false); m_searchResultTreeView = new Internal::SearchResultTreeView(this); m_searchResultTreeView->setFrameStyle(QFrame::NoFrame); m_searchResultTreeView->setAttribute(Qt::WA_MacShowFocusRect, false); Aggregation::Aggregate * agg = new Aggregation::Aggregate; agg->add(m_searchResultTreeView); agg->add(new ItemViewFind(m_searchResultTreeView, ItemDataRoles::ResultLineRole)); layout->addWidget(m_searchResultTreeView); m_infoBarDisplay.setTarget(layout, 2); m_infoBarDisplay.setInfoBar(&m_infoBar); m_descriptionContainer = new QWidget(topWidget); QHBoxLayout *descriptionLayout = new QHBoxLayout(m_descriptionContainer); m_descriptionContainer->setLayout(descriptionLayout); descriptionLayout->setMargin(0); m_descriptionContainer->setMinimumWidth(200); m_descriptionContainer->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); m_label = new QLabel(m_descriptionContainer); m_label->setVisible(false); m_searchTerm = new QLabel(m_descriptionContainer); m_searchTerm->setVisible(false); descriptionLayout->addWidget(m_label); descriptionLayout->addWidget(m_searchTerm); m_cancelButton = new QToolButton(topWidget); m_cancelButton->setText(tr("Cancel")); m_cancelButton->setToolButtonStyle(Qt::ToolButtonTextOnly); connect(m_cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); m_searchAgainButton = new QToolButton(topWidget); m_searchAgainButton->setToolTip(tr("Repeat the search with same parameters.")); m_searchAgainButton->setText(tr("Search again")); m_searchAgainButton->setToolButtonStyle(Qt::ToolButtonTextOnly); m_searchAgainButton->setVisible(false); connect(m_searchAgainButton, SIGNAL(clicked()), this, SLOT(searchAgain())); m_replaceLabel = new QLabel(tr("Replace with:"), topWidget); m_replaceTextEdit = new WideEnoughLineEdit(topWidget); m_replaceTextEdit->setMinimumWidth(120); m_replaceTextEdit->setEnabled(false); m_replaceTextEdit->setTabOrder(m_replaceTextEdit, m_searchResultTreeView); m_replaceButton = new QToolButton(topWidget); m_replaceButton->setToolTip(tr("Replace all occurrences.")); m_replaceButton->setText(tr("Replace")); m_replaceButton->setToolButtonStyle(Qt::ToolButtonTextOnly); m_replaceButton->setEnabled(false); m_preserveCaseCheck = new QCheckBox(topWidget); m_preserveCaseCheck->setText(tr("Preserve case")); m_preserveCaseCheck->setEnabled(false); if (FindPlugin * plugin = FindPlugin::instance()) { m_preserveCaseCheck->setChecked(plugin->hasFindFlag(FindPreserveCase)); connect(m_preserveCaseCheck, SIGNAL(clicked(bool)), plugin, SLOT(setPreserveCase(bool))); } m_matchesFoundLabel = new QLabel(topWidget); updateMatchesFoundLabel(); topLayout->addWidget(m_descriptionContainer); topLayout->addWidget(m_cancelButton); topLayout->addWidget(m_searchAgainButton); topLayout->addWidget(m_replaceLabel); topLayout->addWidget(m_replaceTextEdit); topLayout->addWidget(m_replaceButton); topLayout->addWidget(m_preserveCaseCheck); topLayout->addStretch(2); topLayout->addWidget(m_matchesFoundLabel); topWidget->setMinimumHeight(m_cancelButton->sizeHint().height() + topLayout->contentsMargins().top() + topLayout->contentsMargins().bottom() + topWidget->lineWidth()); setShowReplaceUI(false); connect(m_searchResultTreeView, SIGNAL(jumpToSearchResult(SearchResultItem)), this, SLOT(handleJumpToSearchResult(SearchResultItem))); connect(m_replaceTextEdit, SIGNAL(returnPressed()), this, SLOT(handleReplaceButton())); connect(m_replaceButton, SIGNAL(clicked()), this, SLOT(handleReplaceButton())); } SearchResultWidget::~SearchResultWidget() { if (m_infoBar.containsInfo(Core::Id(SIZE_WARNING_ID))) cancelAfterSizeWarning(); } void SearchResultWidget::setInfo(const QString &label, const QString &toolTip, const QString &term) { m_label->setText(label); m_label->setVisible(!label.isEmpty()); m_descriptionContainer->setToolTip(toolTip); m_searchTerm->setText(term); m_searchTerm->setVisible(!term.isEmpty()); } void SearchResultWidget::addResult(const QString &fileName, int lineNumber, const QString &rowText, int searchTermStart, int searchTermLength, const QVariant &userData) { SearchResultItem item; item.path = QStringList() << QDir::toNativeSeparators(fileName); item.lineNumber = lineNumber; item.text = rowText; item.textMarkPos = searchTermStart; item.textMarkLength = searchTermLength; item.useTextEditorFont = true; item.userData = userData; addResults(QList<SearchResultItem>() << item, SearchResult::AddOrdered); } void SearchResultWidget::addResults(const QList<SearchResultItem> &items, SearchResult::AddMode mode) { bool firstItems = (m_count == 0); m_count += items.size(); m_searchResultTreeView->addResults(items, mode); updateMatchesFoundLabel(); if (firstItems) { if (!m_dontAskAgainGroup.isEmpty()) { Core::Id undoWarningId = Core::Id("warninglabel/").withSuffix(m_dontAskAgainGroup); if (m_infoBar.canInfoBeAdded(undoWarningId)) { Core::InfoBarEntry info(undoWarningId, tr("This change cannot be undone."), Core::InfoBarEntry::GlobalSuppressionEnabled); m_infoBar.addInfo(info); } } m_replaceTextEdit->setEnabled(true); // We didn't have an item before, set the focus to the search widget or replace text edit if (m_isShowingReplaceUI) { m_replaceTextEdit->setFocus(); m_replaceTextEdit->selectAll(); } else { m_searchResultTreeView->setFocus(); } m_searchResultTreeView->selectionModel()->select(m_searchResultTreeView->model()->index(0, 0, QModelIndex()), QItemSelectionModel::Select); emit navigateStateChanged(); } else if (m_count <= SEARCHRESULT_WARNING_LIMIT) { return; } else { Core::Id sizeWarningId(SIZE_WARNING_ID); if (!m_infoBar.canInfoBeAdded(sizeWarningId)) return; emit paused(true); Core::InfoBarEntry info(sizeWarningId, tr("The search resulted in more than %n items, do you still want to continue?", 0, SEARCHRESULT_WARNING_LIMIT)); info.setCancelButtonInfo(tr("Cancel"), [this]() { cancelAfterSizeWarning(); }); info.setCustomButtonInfo(tr("Continue"), [this]() { continueAfterSizeWarning(); }); m_infoBar.addInfo(info); emit requestPopup(false/*no focus*/); } } int SearchResultWidget::count() const { return m_count; } QString SearchResultWidget::dontAskAgainGroup() const { return m_dontAskAgainGroup; } void SearchResultWidget::setDontAskAgainGroup(const QString &group) { m_dontAskAgainGroup = group; } void SearchResultWidget::setTextToReplace(const QString &textToReplace) { m_replaceTextEdit->setText(textToReplace); } QString SearchResultWidget::textToReplace() const { return m_replaceTextEdit->text(); } void SearchResultWidget::setSupportPreserveCase(bool enabled) { m_preserveCaseSupported = enabled; } void SearchResultWidget::setShowReplaceUI(bool visible) { m_searchResultTreeView->model()->setShowReplaceUI(visible); m_replaceLabel->setVisible(visible); m_replaceTextEdit->setVisible(visible); m_replaceButton->setVisible(visible); m_preserveCaseCheck->setVisible(visible && m_preserveCaseSupported); m_isShowingReplaceUI = visible; } bool SearchResultWidget::hasFocusInternally() const { return m_searchResultTreeView->hasFocus() || (m_isShowingReplaceUI && m_replaceTextEdit->hasFocus()); } void SearchResultWidget::setFocusInternally() { if (m_count > 0) { if (m_isShowingReplaceUI) { if (!focusWidget() || focusWidget() == m_replaceTextEdit) { m_replaceTextEdit->setFocus(); m_replaceTextEdit->selectAll(); } else { m_searchResultTreeView->setFocus(); } } else { m_searchResultTreeView->setFocus(); } } } bool SearchResultWidget::canFocusInternally() const { return m_count > 0; } void SearchResultWidget::notifyVisibilityChanged(bool visible) { emit visibilityChanged(visible); } void SearchResultWidget::setTextEditorFont(const QFont &font, const SearchResultColor &color) { m_searchResultTreeView->setTextEditorFont(font, color); } void SearchResultWidget::setAutoExpandResults(bool expand) { m_searchResultTreeView->setAutoExpandResults(expand); } void SearchResultWidget::expandAll() { m_searchResultTreeView->expandAll(); } void SearchResultWidget::collapseAll() { m_searchResultTreeView->collapseAll(); } void SearchResultWidget::goToNext() { if (m_count == 0) return; QModelIndex idx = m_searchResultTreeView->model()->next(m_searchResultTreeView->currentIndex()); if (idx.isValid()) { m_searchResultTreeView->setCurrentIndex(idx); m_searchResultTreeView->emitJumpToSearchResult(idx); } } void SearchResultWidget::goToPrevious() { if (!m_searchResultTreeView->model()->rowCount()) return; QModelIndex idx = m_searchResultTreeView->model()->prev(m_searchResultTreeView->currentIndex()); if (idx.isValid()) { m_searchResultTreeView->setCurrentIndex(idx); m_searchResultTreeView->emitJumpToSearchResult(idx); } } void SearchResultWidget::restart() { m_replaceTextEdit->setEnabled(false); m_replaceButton->setEnabled(false); m_searchResultTreeView->clear(); m_count = 0; Core::Id sizeWarningId(SIZE_WARNING_ID); m_infoBar.removeInfo(sizeWarningId); m_infoBar.enableInfo(sizeWarningId); m_cancelButton->setVisible(true); m_searchAgainButton->setVisible(false); m_messageWidget->setVisible(false); updateMatchesFoundLabel(); emit restarted(); } void SearchResultWidget::setSearchAgainSupported(bool supported) { m_searchAgainSupported = supported; m_searchAgainButton->setVisible(supported && !m_cancelButton->isVisible()); } void SearchResultWidget::setSearchAgainEnabled(bool enabled) { m_searchAgainButton->setEnabled(enabled); } void SearchResultWidget::finishSearch(bool canceled) { Core::Id sizeWarningId(SIZE_WARNING_ID); m_infoBar.removeInfo(sizeWarningId); m_infoBar.enableInfo(sizeWarningId); m_replaceTextEdit->setEnabled(m_count > 0); m_replaceButton->setEnabled(m_count > 0); m_preserveCaseCheck->setEnabled(m_count > 0); m_cancelButton->setVisible(false); m_messageWidget->setVisible(canceled); m_searchAgainButton->setVisible(m_searchAgainSupported); } void SearchResultWidget::sendRequestPopup() { emit requestPopup(true/*focus*/); } void SearchResultWidget::continueAfterSizeWarning() { m_infoBar.suppressInfo(Core::Id(SIZE_WARNING_ID)); emit paused(false); } void SearchResultWidget::cancelAfterSizeWarning() { m_infoBar.suppressInfo(Core::Id(SIZE_WARNING_ID)); emit cancelled(); emit paused(false); } void SearchResultWidget::handleJumpToSearchResult(const SearchResultItem &item) { emit activated(item); } void SearchResultWidget::handleReplaceButton() { // check if button is actually enabled, because this is also triggered // by pressing return in replace line edit if (m_replaceButton->isEnabled()) { m_infoBar.clear(); emit replaceButtonClicked(m_replaceTextEdit->text(), checkedItems(), m_preserveCaseSupported && m_preserveCaseCheck->isChecked()); } } void SearchResultWidget::cancel() { m_cancelButton->setVisible(false); if (m_infoBar.containsInfo(Core::Id(SIZE_WARNING_ID))) cancelAfterSizeWarning(); else emit cancelled(); } void SearchResultWidget::searchAgain() { emit searchAgainRequested(); } QList<SearchResultItem> SearchResultWidget::checkedItems() const { QList<SearchResultItem> result; Internal::SearchResultTreeModel *model = m_searchResultTreeView->model(); const int fileCount = model->rowCount(QModelIndex()); for (int i = 0; i < fileCount; ++i) { QModelIndex fileIndex = model->index(i, 0, QModelIndex()); Internal::SearchResultTreeItem *fileItem = static_cast<Internal::SearchResultTreeItem *>(fileIndex.internalPointer()); Q_ASSERT(fileItem != 0); for (int rowIndex = 0; rowIndex < fileItem->childrenCount(); ++rowIndex) { QModelIndex textIndex = model->index(rowIndex, 0, fileIndex); Internal::SearchResultTreeItem *rowItem = static_cast<Internal::SearchResultTreeItem *>(textIndex.internalPointer()); if (rowItem->checkState()) result << rowItem->item; } } return result; } void SearchResultWidget::updateMatchesFoundLabel() { if (m_count == 0) m_matchesFoundLabel->setText(tr("No matches found.")); else m_matchesFoundLabel->setText(tr("%n matches found.", 0, m_count)); } #include "searchresultwidget.moc"
maui-packages/qt-creator
src/plugins/coreplugin/find/searchresultwidget.cpp
C++
lgpl-2.1
17,509
/* * This file is part of Wireless Display Software for Linux OS * * Copyright (C) 2014 Intel Corporation. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef MIRAC_BROKER_HPP #define MIRAC_BROKER_HPP #include <glib.h> #include <memory> #include <map> #include <vector> #include "libwds/public/peer.h" #include "mirac-network.hpp" class MiracBroker : public wds::Peer::Delegate { public: MiracBroker (const std::string& listen_port); MiracBroker(const std::string& peer_address, const std::string& peer_port, uint timeout = 3000); virtual ~MiracBroker (); unsigned short get_host_port() const; std::string get_peer_address() const; virtual wds::Peer* Peer() const = 0; void OnTimeout(uint timer_id); protected: enum ConnectionFailure { CONNECTION_TIMEOUT, CONNECTION_LOST, }; // wds::Peer::Delegate void SendRTSPData(const std::string& data) override; std::string GetLocalIPAddress() const override; uint CreateTimer(int seconds) override; void ReleaseTimer(uint timer_id) override; virtual void got_message(const std::string& data) {} virtual void on_connected() {}; virtual void on_connection_failure(ConnectionFailure failure) {}; private: static gboolean send_cb (gint fd, GIOCondition condition, gpointer data_ptr); static gboolean receive_cb (gint fd, GIOCondition condition, gpointer data_ptr); static gboolean listen_cb (gint fd, GIOCondition condition, gpointer data_ptr); static gboolean connect_cb (gint fd, GIOCondition condition, gpointer data_ptr); static gboolean try_connect(gpointer data_ptr); static void on_timeout_remove(gpointer user_data); gboolean send_cb (gint fd, GIOCondition condition); gboolean receive_cb (gint fd, GIOCondition condition); gboolean listen_cb (gint fd, GIOCondition condition); gboolean connect_cb (gint fd, GIOCondition condition); void try_connect(); void handle_body(const std::string msg); void handle_header(const std::string msg); void network(MiracNetwork* connection); std::unique_ptr<MiracNetwork> network_; MiracBroker *network_source_ptr_; void connection(MiracNetwork* connection); std::unique_ptr<MiracNetwork> connection_; MiracBroker *connection_source_ptr_; std::vector<uint> timers_; std::string peer_address_; std::string peer_port_; GTimer *connect_timer_; uint connect_wait_id_; uint connect_timeout_; static const uint connect_wait_ = 200; }; #endif /* MIRAC_BROKER_HPP */
275288698/wds
mirac_network/mirac-broker.hpp
C++
lgpl-2.1
3,442
package edu.umd.cs.findbugs.detect; import static org.apache.bcel.Constants.DCMPG; import static org.apache.bcel.Constants.DCMPL; import static org.apache.bcel.Constants.FCMPG; import static org.apache.bcel.Constants.FCMPL; import static org.apache.bcel.Constants.IAND; import static org.apache.bcel.Constants.IF_ACMPEQ; import static org.apache.bcel.Constants.IF_ACMPNE; import static org.apache.bcel.Constants.IF_ICMPEQ; import static org.apache.bcel.Constants.IF_ICMPGE; import static org.apache.bcel.Constants.IF_ICMPGT; import static org.apache.bcel.Constants.IF_ICMPLE; import static org.apache.bcel.Constants.IF_ICMPLT; import static org.apache.bcel.Constants.IF_ICMPNE; import static org.apache.bcel.Constants.INVOKEINTERFACE; import static org.apache.bcel.Constants.INVOKEVIRTUAL; import static org.apache.bcel.Constants.IOR; import static org.apache.bcel.Constants.ISUB; import static org.apache.bcel.Constants.IXOR; import static org.apache.bcel.Constants.LAND; import static org.apache.bcel.Constants.LCMP; import static org.apache.bcel.Constants.LOR; import static org.apache.bcel.Constants.LSUB; import static org.apache.bcel.Constants.LXOR; import static org.apache.bcel.Constants.POP; import java.util.BitSet; import java.util.Iterator; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.MethodGen; import edu.umd.cs.findbugs.BugAnnotation; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.FieldAnnotation; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.ba.CFG; import edu.umd.cs.findbugs.ba.CFGBuilderException; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.DataflowAnalysisException; import edu.umd.cs.findbugs.ba.Location; import edu.umd.cs.findbugs.ba.MethodUnprofitableException; import edu.umd.cs.findbugs.ba.SignatureParser; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.vna.ValueNumber; import edu.umd.cs.findbugs.ba.vna.ValueNumberDataflow; import edu.umd.cs.findbugs.ba.vna.ValueNumberFrame; import edu.umd.cs.findbugs.ba.vna.ValueNumberSourceInfo; public class FindSelfComparison2 implements Detector { private BugReporter bugReporter; public FindSelfComparison2(BugReporter bugReporter) { this.bugReporter = bugReporter; } public void visitClassContext(ClassContext classContext) { Method[] methodList = classContext.getJavaClass().getMethods(); for (Method method : methodList) { if (method.getCode() == null) continue; try { analyzeMethod(classContext, method); } catch (MethodUnprofitableException mue) { if (SystemProperties.getBoolean("unprofitable.debug")) // otherwise don't report bugReporter.logError("skipping unprofitable method in " + getClass().getName()); } catch (CFGBuilderException e) { bugReporter.logError("Detector " + this.getClass().getName() + " caught exception", e); } catch (DataflowAnalysisException e) { bugReporter.logError("Detector " + this.getClass().getName() + " caught exception", e); } } } private void analyzeMethod(ClassContext classContext, Method method) throws CFGBuilderException, DataflowAnalysisException { CFG cfg = classContext.getCFG(method); ValueNumberDataflow valueNumberDataflow = classContext .getValueNumberDataflow(method); ConstantPoolGen cpg = classContext.getConstantPoolGen(); MethodGen methodGen = classContext.getMethodGen(method); String sourceFile = classContext.getJavaClass().getSourceFileName(); for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) { Location location = i.next(); Instruction ins = location.getHandle().getInstruction(); switch(ins.getOpcode()) { case INVOKEVIRTUAL: case INVOKEINTERFACE: InvokeInstruction iins = (InvokeInstruction) ins; String invoking = iins.getName(cpg); if (invoking.equals("equals") || invoking.equals("compareTo")) { if (methodGen.getName().toLowerCase().indexOf("test") >= 0) break; if (methodGen.getClassName().toLowerCase().indexOf("test") >= 0) break; if (classContext.getJavaClass().getSuperclassName().toLowerCase().indexOf("test") >= 0) break; if (location.getHandle().getNext().getInstruction().getOpcode() == POP) break; String sig = iins.getSignature(cpg); SignatureParser parser = new SignatureParser(sig); if (parser.getNumParameters() == 1 && (invoking.equals("equals") && sig.endsWith(";)Z") || invoking.equals("compareTo") && sig.endsWith(";)I"))) checkForSelfOperation(classContext, location, valueNumberDataflow, "COMPARISON", method, methodGen, sourceFile); } break; case LOR: case LAND: case LXOR: case LSUB: case IOR: case IAND: case IXOR: case ISUB: checkForSelfOperation(classContext, location, valueNumberDataflow, "COMPUTATION", method, methodGen, sourceFile); break; case FCMPG: case DCMPG: case DCMPL: case FCMPL: break; case LCMP: case IF_ACMPEQ: case IF_ACMPNE: case IF_ICMPNE: case IF_ICMPEQ: case IF_ICMPGT: case IF_ICMPLE: case IF_ICMPLT: case IF_ICMPGE: checkForSelfOperation(classContext, location, valueNumberDataflow, "COMPARISON", method, methodGen, sourceFile); } } } /** * @param classContext TODO * @param location * @param method TODO * @param methodGen TODO * @param sourceFile TODO * @param string * @throws DataflowAnalysisException */ private void checkForSelfOperation(ClassContext classContext, Location location, ValueNumberDataflow valueNumberDataflow, String op, Method method, MethodGen methodGen, String sourceFile) throws DataflowAnalysisException { ValueNumberFrame frame = valueNumberDataflow.getFactAtLocation(location); if (!frame.isValid()) return; Instruction ins = location.getHandle().getInstruction(); int opcode = ins.getOpcode(); int offset = 1; if (opcode == LCMP || opcode == LXOR || opcode == LAND || opcode == LOR || opcode == LSUB) offset = 2; ValueNumber v0 = frame.getStackValue(0); ValueNumber v1 = frame.getStackValue(offset); if (!v1.equals(v0)) return; if (v0.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT) || v0.hasFlag(ValueNumber.CONSTANT_VALUE)) return; int priority = HIGH_PRIORITY; if (opcode == ISUB || opcode == LSUB || opcode == INVOKEINTERFACE || opcode == INVOKEVIRTUAL) priority = NORMAL_PRIORITY; XField field = ValueNumberSourceInfo.findXFieldFromValueNumber(method, location, v0, frame); BugAnnotation annotation; String prefix; if (field != null) { if (field.isVolatile()) return; if (true) return; // don't report these; too many false positives annotation = FieldAnnotation.fromXField(field); prefix = "SA_FIELD_SELF_"; } else { annotation = ValueNumberSourceInfo.findLocalAnnotationFromValueNumber(method, location, v0, frame); prefix = "SA_LOCAL_SELF_" ; if (opcode == ISUB) return; // only report this if simple detector reports it } if (annotation == null) return; SourceLineAnnotation sourceLine = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, location.getHandle()); int line = sourceLine.getStartLine(); BitSet occursMultipleTimes = ClassContext.linesMentionedMultipleTimes(method); if (line > 0 && occursMultipleTimes.get(line)) return; BugInstance bug = new BugInstance(this, prefix + op, priority).addClassAndMethod(methodGen, sourceFile) .add(annotation).addSourceLine(classContext, methodGen, sourceFile, location.getHandle()); bugReporter.reportBug(bug); } public void report() { } }
optivo-org/fingbugs-1.3.9-optivo
src/java/edu/umd/cs/findbugs/detect/FindSelfComparison2.java
Java
lgpl-2.1
7,896
package plasma.jna.clutter; import plasma.fx.scene.layout.ClutterFlowLayout; import com.sun.jna.Pointer; public interface ClutterFlowLayoutApi { //@formatter:off Pointer clutter_flow_layout_new (int orientation); // ClutterFlowOrientation void clutter_flow_layout_set_orientation (ClutterFlowLayout layout, int orientation); // ClutterFlowOrientation int clutter_flow_layout_get_orientation (ClutterFlowLayout layout); // ClutterFlowOrientation void clutter_flow_layout_set_homogeneous (ClutterFlowLayout layout, boolean homogeneous); boolean clutter_flow_layout_get_homogeneous (ClutterFlowLayout layout); void clutter_flow_layout_set_column_spacing (ClutterFlowLayout layout, float spacing); float clutter_flow_layout_get_column_spacing (ClutterFlowLayout layout); void clutter_flow_layout_set_row_spacing (ClutterFlowLayout layout, float spacing); float clutter_flow_layout_get_row_spacing (ClutterFlowLayout layout); void clutter_flow_layout_set_column_width (ClutterFlowLayout layout, float min_width, float max_width); void clutter_flow_layout_get_column_width (ClutterFlowLayout layout, float[] min_width, float[] max_width); void clutter_flow_layout_set_row_height (ClutterFlowLayout layout, float min_height, float max_height); void clutter_flow_layout_get_row_height (ClutterFlowLayout layout, float[] min_height, float[] max_height); // CLUTTER_AVAILABLE_IN_1_16 void clutter_flow_layout_set_snap_to_grid (ClutterFlowLayout layout, boolean snap_to_grid); // CLUTTER_AVAILABLE_IN_1_16 boolean clutter_flow_layout_get_snap_to_grid (ClutterFlowLayout layout); //@formatter:on }
ggeorg/plasma-fx
src/plasma/jna/clutter/ClutterFlowLayoutApi.java
Java
lgpl-2.1
3,116
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <mapnik/config.hpp> #include "boost_std_shared_shim.hpp" #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/python.hpp> #pragma GCC diagnostic pop // mapnik #include <mapnik/coord.hpp> #include <mapnik/box2d.hpp> #include <mapnik/projection.hpp> using mapnik::projection; struct projection_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(const projection& p) { using namespace boost::python; return boost::python::make_tuple(p.params()); } }; namespace { mapnik::coord2d forward_pt(mapnik::coord2d const& pt, mapnik::projection const& prj) { double x = pt.x; double y = pt.y; prj.forward(x,y); return mapnik::coord2d(x,y); } mapnik::coord2d inverse_pt(mapnik::coord2d const& pt, mapnik::projection const& prj) { double x = pt.x; double y = pt.y; prj.inverse(x,y); return mapnik::coord2d(x,y); } mapnik::box2d<double> forward_env(mapnik::box2d<double> const & box, mapnik::projection const& prj) { double minx = box.minx(); double miny = box.miny(); double maxx = box.maxx(); double maxy = box.maxy(); prj.forward(minx,miny); prj.forward(maxx,maxy); return mapnik::box2d<double>(minx,miny,maxx,maxy); } mapnik::box2d<double> inverse_env(mapnik::box2d<double> const & box, mapnik::projection const& prj) { double minx = box.minx(); double miny = box.miny(); double maxx = box.maxx(); double maxy = box.maxy(); prj.inverse(minx,miny); prj.inverse(maxx,maxy); return mapnik::box2d<double>(minx,miny,maxx,maxy); } } void export_projection () { using namespace boost::python; class_<projection>("Projection", "Represents a map projection.",init<std::string const&>( (arg("proj4_string")), "Constructs a new projection from its PROJ.4 string representation.\n" "\n" "The constructor will throw a RuntimeError in case the projection\n" "cannot be initialized.\n" ) ) .def_pickle(projection_pickle_suite()) .def ("params", make_function(&projection::params, return_value_policy<copy_const_reference>()), "Returns the PROJ.4 string for this projection.\n") .def ("expanded",&projection::expanded, "normalize PROJ.4 definition by expanding +init= syntax\n") .add_property ("geographic", &projection::is_geographic, "This property is True if the projection is a geographic projection\n" "(i.e. it uses lon/lat coordinates)\n") ; def("forward_",&forward_pt); def("inverse_",&inverse_pt); def("forward_",&forward_env); def("inverse_",&inverse_env); }
mapycz/python-mapnik
src/mapnik_projection.cpp
C++
lgpl-2.1
4,034
<?php require_once '../page_request.php'; ?><html> <head><title>Simple test target file in folder</title></head> <body> A target for the SimpleTest test suite. <h1>Request</h1> <dl> <dt>Protocol version</dt><dd><?php echo $_SERVER['SERVER_PROTOCOL']; ?></dd> <dt>Request method</dt><dd><?php echo $_SERVER['REQUEST_METHOD']; ?></dd> <dt>Accept header</dt><dd><?php echo $_SERVER['HTTP_ACCEPT'] ?? ''; ?></dd> </dl> <h1>Cookies</h1> <?php if (count($_COOKIE) > 0) { foreach ($_COOKIE as $key => $value) { echo $key.'=['.$value."]<br />\n"; } } ?> <h1>Raw GET data</h1> <?php if (!empty($_SERVER['QUERY_STRING'])) { echo '['.$_SERVER['QUERY_STRING'].']'; } ?> <h1>GET data</h1> <?php $get = PageRequest::get(); if (count($get) > 0) { foreach ($get as $key => $value) { if (is_array($value)) { $value = implode(', ', $value); } echo $key.'=['.$value."]<br />\n"; } } ?> <h1>Raw POST data</h1> <?php echo '['.file_get_contents('php://input').']'; ?> <pre><?php print_r(PageRequest::post()); ?></pre> <h1>POST data</h1> <?php if (count($_POST) > 0) { foreach ($_POST as $key => $value) { echo $key.'=['; if (is_array($value)) { echo implode(', ', $value); } else { echo $value; } echo "]<br />\n"; } } ?> </body> </html>
simpletest/simpletest
test/site/path/network_confirm.php
PHP
lgpl-2.1
1,912
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.engine.internal; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.VersionType; import org.jboss.logging.Logger; /** * Utilities for dealing with optimistic locking values. * * @author Gavin King */ public final class Versioning { private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, Versioning.class.getName() ); /** * Private constructor disallowing instantiation. */ private Versioning() { } /** * Create an initial optimistic locking value according the {@link VersionType} * contract for the version property. * * @param versionType The version type. * @param session The originating session * @return The initial optimistic locking value */ private static Object seed(VersionType versionType, SessionImplementor session) { final Object seed = versionType.seed( session ); LOG.tracef( "Seeding: %s", seed ); return seed; } /** * Create an initial optimistic locking value according the {@link VersionType} * contract for the version property <b>if required</b> and inject it into * the snapshot state. * * @param fields The current snapshot state * @param versionProperty The index of the version property * @param versionType The version type * @param session The originating session * @return True if we injected a new version value into the fields array; false * otherwise. */ public static boolean seedVersion( Object[] fields, int versionProperty, VersionType versionType, SessionImplementor session) { final Object initialVersion = fields[versionProperty]; if ( initialVersion==null || // This next bit is to allow for both unsaved-value="negative" // and for "older" behavior where version number did not get // seeded if it was already set in the object // TODO: shift it into unsaved-value strategy ( (initialVersion instanceof Number) && ( (Number) initialVersion ).longValue()<0 ) ) { fields[versionProperty] = seed( versionType, session ); return true; } LOG.tracev( "Using initial version: {0}", initialVersion ); return false; } /** * Generate the next increment in the optimistic locking value according * the {@link VersionType} contract for the version property. * * @param version The current version * @param versionType The version type * @param session The originating session * @return The incremented optimistic locking value. */ @SuppressWarnings("unchecked") public static Object increment(Object version, VersionType versionType, SessionImplementor session) { final Object next = versionType.next( version, session ); if ( LOG.isTraceEnabled() ) { LOG.tracef( "Incrementing: %s to %s", versionType.toLoggableString( version, session.getFactory() ), versionType.toLoggableString( next, session.getFactory() ) ); } return next; } /** * Inject the optimistic locking value into the entity state snapshot. * * @param fields The state snapshot * @param version The optimistic locking value * @param persister The entity persister */ public static void setVersion(Object[] fields, Object version, EntityPersister persister) { if ( !persister.isVersioned() ) { return; } fields[ persister.getVersionProperty() ] = version; } /** * Extract the optimistic locking value out of the entity state snapshot. * * @param fields The state snapshot * @param persister The entity persister * @return The extracted optimistic locking value */ public static Object getVersion(Object[] fields, EntityPersister persister) { if ( !persister.isVersioned() ) { return null; } return fields[ persister.getVersionProperty() ]; } /** * Do we need to increment the version number, given the dirty properties? * * @param dirtyProperties The array of property indexes which were deemed dirty * @param hasDirtyCollections Were any collections found to be dirty (structurally changed) * @param propertyVersionability An array indicating versionability of each property. * @return True if a version increment is required; false otherwise. */ public static boolean isVersionIncrementRequired( final int[] dirtyProperties, final boolean hasDirtyCollections, final boolean[] propertyVersionability) { if ( hasDirtyCollections ) { return true; } for ( int dirtyProperty : dirtyProperties ) { if ( propertyVersionability[dirtyProperty] ) { return true; } } return false; } }
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java
Java
lgpl-2.1
4,872
/* PSerial - class for serial port goodness Part of the Processing project - http://processing.org Copyright (c) 2004 Ben Fry & Casey Reas This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app; import jssc.SerialPort; import jssc.SerialPortEvent; import jssc.SerialPortEventListener; import jssc.SerialPortException; import java.io.IOException; import java.util.Arrays; import java.util.List; import static processing.app.I18n.tr; import static processing.app.I18n.format; public class Serial implements SerialPortEventListener { //PApplet parent; // properties can be passed in for default values // otherwise defaults to 9600 N81 // these could be made static, which might be a solution // for the classloading problem.. because if code ran again, // the static class would have an object that could be closed private SerialPort port; public Serial() throws SerialException { this(PreferencesData.get("serial.port"), PreferencesData.getInteger("serial.debug_rate", 9600), PreferencesData.getNonEmpty("serial.parity", "N").charAt(0), PreferencesData.getInteger("serial.databits", 8), PreferencesData.getFloat("serial.stopbits", 1)); } public Serial(int irate) throws SerialException { this(PreferencesData.get("serial.port"), irate, PreferencesData.getNonEmpty("serial.parity", "N").charAt(0), PreferencesData.getInteger("serial.databits", 8), PreferencesData.getFloat("serial.stopbits", 1)); } public Serial(String iname, int irate) throws SerialException { this(iname, irate, PreferencesData.getNonEmpty("serial.parity", "N").charAt(0), PreferencesData.getInteger("serial.databits", 8), PreferencesData.getFloat("serial.stopbits", 1)); } public Serial(String iname) throws SerialException { this(iname, PreferencesData.getInteger("serial.debug_rate", 9600), PreferencesData.getNonEmpty("serial.parity", "N").charAt(0), PreferencesData.getInteger("serial.databits", 8), PreferencesData.getFloat("serial.stopbits", 1)); } public static boolean touchForCDCReset(String iname) throws SerialException { SerialPort serialPort = new SerialPort(iname); try { serialPort.openPort(); serialPort.setParams(1200, 8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.setDTR(false); serialPort.closePort(); return true; } catch (SerialPortException e) { throw new SerialException(format(tr("Error touching serial port ''{0}''."), iname), e); } finally { if (serialPort.isOpened()) { try { serialPort.closePort(); } catch (SerialPortException e) { // noop } } } } private Serial(String iname, int irate, char iparity, int idatabits, float istopbits) throws SerialException { //if (port != null) port.close(); //this.parent = parent; //parent.attach(this); int parity = SerialPort.PARITY_NONE; if (iparity == 'E') parity = SerialPort.PARITY_EVEN; if (iparity == 'O') parity = SerialPort.PARITY_ODD; int stopbits = SerialPort.STOPBITS_1; if (istopbits == 1.5f) stopbits = SerialPort.STOPBITS_1_5; if (istopbits == 2) stopbits = SerialPort.STOPBITS_2; if (iname == "fake serial") return; try { port = new SerialPort(iname); port.openPort(); boolean res = port.setParams(irate, idatabits, stopbits, parity, true, true); if (!res) { System.err.println(format(tr("Error while setting serial port parameters: {0} {1} {2} {3}"), irate, iparity, idatabits, istopbits)); } port.addEventListener(this); } catch (SerialPortException e) { if (e.getPortName().startsWith("/dev") && SerialPortException.TYPE_PERMISSION_DENIED.equals(e.getExceptionType())) { throw new SerialException(format(tr("Error opening serial port ''{0}''. Try consulting the documentation at http://playground.arduino.cc/Linux/All#Permission"), iname)); } throw new SerialException(format(tr("Error opening serial port ''{0}''."), iname), e); } if (port == null) { throw new SerialNotFoundException(format(tr("Serial port ''{0}'' not found. Did you select the right one from the Tools > Serial Port menu?"), iname)); } } public void setup() { //parent.registerCall(this, DISPOSE); } public void dispose() throws IOException { if (port != null) { try { if (port.isOpened()) { port.closePort(); // close the port } } catch (SerialPortException e) { throw new IOException(e); } finally { port = null; } } } public synchronized void serialEvent(SerialPortEvent serialEvent) { if (serialEvent.isRXCHAR()) { try { byte[] buf = port.readBytes(serialEvent.getEventValue()); if (buf.length > 0) { String msg = new String(buf); char[] chars = msg.toCharArray(); message(chars, chars.length); } } catch (SerialPortException e) { errorMessage("serialEvent", e); } } } /** * This method is intented to be extended to receive messages * coming from serial port. */ protected void message(char[] chars, int length) { // Empty } /** * This will handle both ints, bytes and chars transparently. */ public void write(int what) { // will also cover char try { port.writeInt(what & 0xff); } catch (SerialPortException e) { errorMessage("write", e); } } private void write(byte bytes[]) { try { port.writeBytes(bytes); } catch (SerialPortException e) { errorMessage("write", e); } } /** * Write a String to the output. Note that this doesn't account * for Unicode (two bytes per char), nor will it send UTF8 * characters.. It assumes that you mean to send a byte buffer * (most often the case for networking and serial i/o) and * will only use the bottom 8 bits of each char in the string. * (Meaning that internally it uses String.getBytes) * <p> * If you want to move Unicode data, you can first convert the * String to a byte stream in the representation of your choice * (i.e. UTF8 or two-byte Unicode data), and send it as a byte array. */ public void write(String what) { write(what.getBytes()); } public void setDTR(boolean state) { try { port.setDTR(state); } catch (SerialPortException e) { errorMessage("setDTR", e); } } public void setRTS(boolean state) { try { port.setRTS(state); } catch (SerialPortException e) { errorMessage("setRTS", e); } } public void setBaud(int rate) { if (port == null) return; try { port.setParams(rate, 8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (SerialPortException e) { } } public boolean isOnline() { if (port == null) return false; if (!(port.isOpened())) return false; boolean online; try { online = port.setDTR(true); } catch (Exception e) { online = false; } //System.out.println("set dtr, result = " + online); return online; } static public List<String> list() { return Arrays.asList(SerialPortList.getPortNames()); } /** * General error reporting, all corraled here just in case * I think of something slightly more intelligent to do. */ private static void errorMessage(String where, Throwable e) { System.err.println(format(tr("Error inside Serial.{0}()"), where)); e.printStackTrace(); } }
PaulStoffregen/Arduino-1.6.6-Teensyduino
arduino-core/src/processing/app/Serial.java
Java
lgpl-2.1
8,308
""" Load and save a set of chosen implementations. @since: 0.27 """ # Copyright (C) 2009, Thomas Leonard # See the README file for details, or visit http://0install.net. import os from zeroinstall import _ from zeroinstall.injector import model from zeroinstall.injector.policy import Policy, get_deprecated_singleton_config from zeroinstall.injector.model import process_binding, process_depends, binding_names, Command from zeroinstall.injector.namespaces import XMLNS_IFACE from zeroinstall.injector.qdom import Element, Prefixes from zeroinstall.support import tasks class Selection(object): """A single selected implementation in a L{Selections} set. @ivar dependencies: list of dependencies @type dependencies: [L{model.Dependency}] @ivar attrs: XML attributes map (name is in the format "{namespace} {localName}") @type attrs: {str: str} @ivar version: the implementation's version number @type version: str""" interface = property(lambda self: self.attrs['interface']) id = property(lambda self: self.attrs['id']) version = property(lambda self: self.attrs['version']) feed = property(lambda self: self.attrs.get('from-feed', self.interface)) main = property(lambda self: self.attrs.get('main', None)) @property def local_path(self): local_path = self.attrs.get('local-path', None) if local_path: return local_path if self.id.startswith('/'): return self.id return None def __repr__(self): return self.id def is_available(self, stores): """Is this implementation available locally? (a local implementation or a cached ZeroInstallImplementation) @rtype: bool @since: 0.53""" path = self.local_path if path is not None: return os.path.exists(path) path = stores.lookup_maybe(self.digests) return path is not None class ImplSelection(Selection): """A Selection created from an Implementation""" __slots__ = ['impl', 'dependencies', 'attrs'] def __init__(self, iface_uri, impl, dependencies): assert impl self.impl = impl self.dependencies = dependencies attrs = impl.metadata.copy() attrs['id'] = impl.id attrs['version'] = impl.get_version() attrs['interface'] = iface_uri attrs['from-feed'] = impl.feed.url if impl.local_path: attrs['local-path'] = impl.local_path self.attrs = attrs @property def bindings(self): return self.impl.bindings @property def digests(self): return self.impl.digests class XMLSelection(Selection): """A Selection created by reading an XML selections document. @ivar digests: a list of manifest digests @type digests: [str] """ __slots__ = ['bindings', 'dependencies', 'attrs', 'digests'] def __init__(self, dependencies, bindings = None, attrs = None, digests = None): if bindings is None: bindings = [] if digests is None: digests = [] self.dependencies = dependencies self.bindings = bindings self.attrs = attrs self.digests = digests assert self.interface assert self.id assert self.version assert self.feed class Selections(object): """ A selected set of components which will make up a complete program. @ivar interface: the interface of the program @type interface: str @ivar commands: how to run this selection (will contain more than one item if runners are used) @type commands: [{L{Command}}] @ivar selections: the selected implementations @type selections: {str: L{Selection}} """ __slots__ = ['interface', 'selections', 'commands'] def __init__(self, source): """Constructor. @param source: a map of implementations, policy or selections document @type source: {str: L{Selection}} | L{Policy} | L{Element} """ self.selections = {} if source is None: self.commands = [] # (Solver will fill everything in) elif isinstance(source, Policy): self._init_from_policy(source) elif isinstance(source, Element): self._init_from_qdom(source) else: raise Exception(_("Source not a Policy or qdom.Element!")) def _init_from_policy(self, policy): """Set the selections from a policy. @deprecated: use Solver.selections instead @param policy: the policy giving the selected implementations.""" self.interface = policy.root self.selections = policy.solver.selections.selections self.commands = policy.solver.selections.commands def _init_from_qdom(self, root): """Parse and load a selections document. @param root: a saved set of selections.""" self.interface = root.getAttribute('interface') assert self.interface self.commands = [] for selection in root.childNodes: if selection.uri != XMLNS_IFACE: continue if selection.name != 'selection': if selection.name == 'command': self.commands.append(Command(selection, None)) continue requires = [] bindings = [] digests = [] for dep_elem in selection.childNodes: if dep_elem.uri != XMLNS_IFACE: continue if dep_elem.name in binding_names: bindings.append(process_binding(dep_elem)) elif dep_elem.name == 'requires': dep = process_depends(dep_elem, None) requires.append(dep) elif dep_elem.name == 'manifest-digest': for aname, avalue in dep_elem.attrs.iteritems(): digests.append('%s=%s' % (aname, avalue)) # For backwards compatibility, allow getting the digest from the ID sel_id = selection.attrs['id'] local_path = selection.attrs.get("local-path", None) if (not digests and not local_path) and '=' in sel_id: alg = sel_id.split('=', 1)[0] if alg in ('sha1', 'sha1new', 'sha256'): digests.append(sel_id) iface_uri = selection.attrs['interface'] s = XMLSelection(requires, bindings, selection.attrs, digests) self.selections[iface_uri] = s if not self.commands: # Old-style selections document; use the main attribute if iface_uri == self.interface: root_sel = self.selections[self.interface] main = root_sel.attrs.get('main', None) if main is not None: self.commands = [Command(Element(XMLNS_IFACE, 'command', {'path': main}), None)] def toDOM(self): """Create a DOM document for the selected implementations. The document gives the URI of the root, plus each selected implementation. For each selected implementation, we record the ID, the version, the URI and (if different) the feed URL. We also record all the bindings needed. @return: a new DOM Document""" from xml.dom import minidom, XMLNS_NAMESPACE assert self.interface impl = minidom.getDOMImplementation() doc = impl.createDocument(XMLNS_IFACE, "selections", None) root = doc.documentElement root.setAttributeNS(XMLNS_NAMESPACE, 'xmlns', XMLNS_IFACE) root.setAttributeNS(None, 'interface', self.interface) prefixes = Prefixes(XMLNS_IFACE) for iface, selection in sorted(self.selections.items()): selection_elem = doc.createElementNS(XMLNS_IFACE, 'selection') selection_elem.setAttributeNS(None, 'interface', selection.interface) root.appendChild(selection_elem) for name, value in selection.attrs.iteritems(): if ' ' in name: ns, localName = name.split(' ', 1) prefixes.setAttributeNS(selection_elem, ns, localName, value) elif name == 'stability': pass elif name == 'from-feed': # Don't bother writing from-feed attr if it's the same as the interface if value != selection.attrs['interface']: selection_elem.setAttributeNS(None, name, value) elif name not in ('main', 'self-test'): # (replaced by <command>) selection_elem.setAttributeNS(None, name, value) if selection.digests: manifest_digest = doc.createElementNS(XMLNS_IFACE, 'manifest-digest') for digest in selection.digests: aname, avalue = digest.split('=', 1) assert ':' not in aname manifest_digest.setAttribute(aname, avalue) selection_elem.appendChild(manifest_digest) for b in selection.bindings: selection_elem.appendChild(b._toxml(doc)) for dep in selection.dependencies: dep_elem = doc.createElementNS(XMLNS_IFACE, 'requires') dep_elem.setAttributeNS(None, 'interface', dep.interface) selection_elem.appendChild(dep_elem) for m in dep.metadata: parts = m.split(' ', 1) if len(parts) == 1: ns = None localName = parts[0] dep_elem.setAttributeNS(None, localName, dep.metadata[m]) else: ns, localName = parts prefixes.setAttributeNS(dep_elem, ns, localName, dep.metadata[m]) for b in dep.bindings: dep_elem.appendChild(b._toxml(doc)) for command in self.commands: root.appendChild(command._toxml(doc, prefixes)) for ns, prefix in prefixes.prefixes.items(): root.setAttributeNS(XMLNS_NAMESPACE, 'xmlns:' + prefix, ns) return doc def __repr__(self): return "Selections for " + self.interface def download_missing(self, config, _old = None, include_packages = False): """Check all selected implementations are available. Download any that are not present. Note: package implementations (distribution packages) are ignored unless include_packages is True. @param config: used to get iface_cache, stores and fetcher @param include_packages: also install native distribution packages @return: a L{tasks.Blocker} or None""" from zeroinstall.zerostore import NotStored if _old: config = get_deprecated_singleton_config() iface_cache = config.iface_cache stores = config.stores # Check that every required selection is cached def needs_download(sel): if sel.id.startswith('package:'): return include_packages elif not sel.local_path: try: stores.lookup_any(sel.digests) except NotStored: return True return False needed_downloads = list(filter(needs_download, self.selections.values())) if not needed_downloads: return if config.network_use == model.network_offline: from zeroinstall import NeedDownload raise NeedDownload(', '.join([str(x) for x in needed_downloads])) @tasks.async def download(): # We're missing some. For each one, get the feed it came from # and find the corresponding <implementation> in that. This will # tell us where to get it from. # Note: we look for an implementation with the same ID. Maybe we # should check it has the same digest(s) too? needed_impls = [] for sel in needed_downloads: feed_url = sel.attrs.get('from-feed', None) or sel.attrs['interface'] feed = iface_cache.get_feed(feed_url) if feed is None or sel.id not in feed.implementations: fetch_feed = config.fetcher.download_and_import_feed(feed_url, iface_cache) yield fetch_feed tasks.check(fetch_feed) feed = iface_cache.get_feed(feed_url) assert feed, "Failed to get feed for %s" % feed_url impl = feed.implementations[sel.id] needed_impls.append(impl) fetch_impls = config.fetcher.download_impls(needed_impls, stores) yield fetch_impls tasks.check(fetch_impls) return download() # These (deprecated) methods are to make a Selections object look like the old Policy.implementation map... def __getitem__(self, key): # Deprecated if isinstance(key, basestring): return self.selections[key] sel = self.selections[key.uri] return sel and sel.impl def iteritems(self): # Deprecated iface_cache = get_deprecated_singleton_config().iface_cache for (uri, sel) in self.selections.iteritems(): yield (iface_cache.get_interface(uri), sel and sel.impl) def values(self): # Deprecated for (uri, sel) in self.selections.iteritems(): yield sel and sel.impl def __iter__(self): # Deprecated iface_cache = get_deprecated_singleton_config().iface_cache for (uri, sel) in self.selections.iteritems(): yield iface_cache.get_interface(uri) def get(self, iface, if_missing): # Deprecated sel = self.selections.get(iface.uri, None) if sel: return sel.impl return if_missing def copy(self): # Deprecated s = Selections(None) s.interface = self.interface s.selections = self.selections.copy() return s def items(self): # Deprecated return list(self.iteritems())
timdiels/zeroinstall
zeroinstall/injector/selections.py
Python
lgpl-2.1
11,955
package joshua.util.io; import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; /** * Wraps a reader with "line" index information. * * @author wren ng thornton <wren@users.sourceforge.net> * @version $LastChangedDate: 2009-03-26 15:06:57 -0400 (Thu, 26 Mar 2009) $ */ public class IndexedReader<E> implements Reader<E> { /** A name for the type of elements the reader produces. */ private final String elementName; /** The number of elements the reader has delivered so far. */ private int lineNumber; /** The underlying reader. */ private final Reader<E> reader; public IndexedReader(String elementName, Reader<E> reader) { this.elementName = elementName; this.lineNumber = 0; this.reader = reader; } // =============================================================== // Public (non-interface) methods // =============================================================== /** Return the number of elements delivered so far. */ public int index() { return this.lineNumber; } /** * Wrap an IOException's message with the index when it occured. */ public IOException wrapIOException(IOException oldError) { IOException newError = new IOException("At " + this.elementName + " " + this.lineNumber + ": " + oldError.getMessage()); newError.initCause(oldError); return newError; } // =============================================================== // Reader // =============================================================== /** Delegated to the underlying reader. */ public boolean ready() throws IOException { try { return this.reader.ready(); } catch (IOException oldError) { throw wrapIOException(oldError); } } /** * Delegated to the underlying reader. Note that we do not have a <code>finalize()</code> method; * however, when we fall out of scope, the underlying reader will too, so its finalizer may be * called. For correctness, be sure to manually close all readers. */ public void close() throws IOException { try { this.reader.close(); } catch (IOException oldError) { throw wrapIOException(oldError); } } /** Delegated to the underlying reader. */ public E readLine() throws IOException { E line; try { line = this.reader.readLine(); } catch (IOException oldError) { throw wrapIOException(oldError); } ++this.lineNumber; return line; } // =============================================================== // Iterable -- because sometimes Java can be very stupid // =============================================================== /** Return self as an iterator. */ public Iterator<E> iterator() { return this; } // =============================================================== // Iterator // =============================================================== /** Delegated to the underlying reader. */ public boolean hasNext() { return this.reader.hasNext(); } /** Delegated to the underlying reader. */ public E next() throws NoSuchElementException { E line = this.reader.next(); // Let exceptions out, we'll wrap any errors a closing time. ++this.lineNumber; return line; } /** * If the underlying reader supports removal, then so do we. Note that the {@link #index()} method * returns the number of elements delivered to the client, so removing an element from the * underlying collection does not affect that number. */ public void remove() throws UnsupportedOperationException { this.reader.remove(); } }
lukeorland/joshua
src/joshua/util/io/IndexedReader.java
Java
lgpl-2.1
3,670
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain Version 0.10.4 // The SmartSoft Toolchain has been developed by: // // ZAFH Servicerobotic Ulm // Christian Schlegel (schlegel@hs-ulm.de) // University of Applied Sciences // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // smart-robotics.sourceforge.net // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #ifndef _SMARTROBOTCONSOLE_HH #define _SMARTROBOTCONSOLE_HH #include <iostream> #include "smartSoft.hh" #include "../SmartRobotConsoleCore.hh" // include communication objects #include <CommBasicObjects/commBaseParameter.hh> #include <CommForkliftObjects/commForkliftParameter.hh> #include <CommManipulatorObjects/commGripperParam.hh> #include <CommNavigationObjects/commAmclParameter.hh> #include <CommNavigationObjects/commCdlGoalEventParameter.hh> #include <CommNavigationObjects/commCdlGoalEventResult.hh> #include <CommNavigationObjects/commCdlParameter.hh> #include <CommNavigationObjects/commGMappingParameter.hh> #include <CommNavigationObjects/commMapperParameter.hh> #include <CommNavigationObjects/commPlannerEventParameter.hh> #include <CommNavigationObjects/commPlannerEventResult.hh> #include <CommNavigationObjects/commPlannerParameter.hh> #include <CommPTUObjects/commPTUMoveRequest.hh> #include <CommPTUObjects/commPTUMoveResponse.hh> #include <CommPersonDetectionObjects/commPersonDetectionParameter.hh> #include <CommSpeechObjects/commSpeechInputParameter.hh> #include <CommSpeechObjects/commSpeechOutputMessage.hh> #include <CommTrackingObjects/commFollowMeParameter.hh> // include tasks #include "../ConsoleTask.hh" #include "../GoalEventTask.hh" #include "../PlannerNoPathEventTask.hh" // include handler #include "../CompHandler.hh" #define COMP SmartRobotConsole::instance() class SmartRobotConsole: public SmartRobotConsoleCore { private: static SmartRobotConsole _smartRobotConsole; // constructor SmartRobotConsole(); // copy-constructor SmartRobotConsole(const SmartRobotConsole& cc); // destructor ~SmartRobotConsole() { } ; // load parameter from ini file void loadParameter(int argc, char *argv[]); // instantiate handler CompHandler compHandler; // ThreadQueueHandler public: // component CHS::SmartComponent *component; // create mutex CHS::SmartMutex SpeechLock; // create condition mutex // instantiate tasks ConsoleTask consoleTask; GoalEventTask goalEventTask; PlannerNoPathEventTask plannerNoPathEventTask; // ports CHS::SendClient<CommNavigationObjects::CommAmclParameter> *amclParameterClient; CHS::SmartStateClient *amclStateClient; CHS::SendClient<CommBasicObjects::CommBaseParameter> *baseParameterClient; CHS::EventClient<CommNavigationObjects::CommCdlGoalEventParameter, CommNavigationObjects::CommCdlGoalEventResult> *cdlGoalEventClient; CHS::SendClient<CommNavigationObjects::CommCdlParameter> *cdlParameterClient; CHS::SmartStateClient *cdlStateClient; CHS::SendClient<CommTrackingObjects::CommFollowMeParameter> *followMeParameterClient; CHS::SendClient<CommForkliftObjects::CommForkliftParameter> *forkliftParameterClient; CHS::SendClient<CommNavigationObjects::CommGMappingParameter> *gmappingParameterClient; CHS::SendClient<CommNavigationObjects::CommMapperParameter> *mapperParameterClient; CHS::SmartStateClient *mapperStateClient; CHS::SendClient<CommPersonDetectionObjects::CommPersonDetectionParameter> *personDetectionParameterClient; CHS::EventClient<CommNavigationObjects::CommPlannerEventParameter, CommNavigationObjects::CommPlannerEventResult> *plannerEventClient; CHS::SendClient<CommNavigationObjects::CommPlannerParameter> *plannerParameterClient; CHS::SmartStateClient *plannerStateClient; CHS::QueryClient<CommPTUObjects::CommPTUMoveRequest, CommPTUObjects::CommPTUMoveResponse> *ptuQueryClient; CHS::SmartStateClient *ptuStateClient; CHS::SendClient<CommManipulatorObjects::CommGripperParam> *schunkGripperParameterClient; CHS::SendClient<CommSpeechObjects::CommSpeechInputParameter> *speechParameterClient; CHS::SendClient<CommSpeechObjects::CommSpeechOutputMessage> *speechSendClient; CHS::SmartStateClient *speechStateClient; CHS::WiringSlave *wiringSlave; void init(int argc, char *argv[]); void run(); // return singleton instance static SmartRobotConsole* instance() { return (SmartRobotConsole*) &_smartRobotConsole; } // ini parameter struct ini_ini { // component struct struct ini_component { // the name of the component std::string name; } component; struct ini_amclParameterClient { std::string serverName; std::string serviceName; } amclParameterClient; struct ini_amclStateClient { std::string serverName; std::string serviceName; } amclStateClient; struct ini_baseParameterClient { std::string serverName; std::string serviceName; } baseParameterClient; struct ini_cdlGoalEventClient { std::string serverName; std::string serviceName; } cdlGoalEventClient; struct ini_cdlParameterClient { std::string serverName; std::string serviceName; } cdlParameterClient; struct ini_cdlStateClient { std::string serverName; std::string serviceName; } cdlStateClient; struct ini_followMeParameterClient { std::string serverName; std::string serviceName; } followMeParameterClient; struct ini_forkliftParameterClient { std::string serverName; std::string serviceName; } forkliftParameterClient; struct ini_gmappingParameterClient { std::string serverName; std::string serviceName; } gmappingParameterClient; struct ini_mapperParameterClient { std::string serverName; std::string serviceName; } mapperParameterClient; struct ini_mapperStateClient { std::string serverName; std::string serviceName; } mapperStateClient; struct ini_personDetectionParameterClient { std::string serverName; std::string serviceName; } personDetectionParameterClient; struct ini_plannerEventClient { std::string serverName; std::string serviceName; } plannerEventClient; struct ini_plannerParameterClient { std::string serverName; std::string serviceName; } plannerParameterClient; struct ini_plannerStateClient { std::string serverName; std::string serviceName; } plannerStateClient; struct ini_ptuQueryClient { std::string serverName; std::string serviceName; } ptuQueryClient; struct ini_ptuStateClient { std::string serverName; std::string serviceName; } ptuStateClient; struct ini_schunkGripperParameterClient { std::string serverName; std::string serviceName; } schunkGripperParameterClient; struct ini_speechParameterClient { std::string serverName; std::string serviceName; } speechParameterClient; struct ini_speechSendClient { std::string serverName; std::string serviceName; } speechSendClient; struct ini_speechStateClient { std::string serverName; std::string serviceName; } speechStateClient; } ini; }; #endif
carlos22/SmartSoftCorba
src/components/SmartRobotConsole/src/gen/SmartRobotConsole.hh
C++
lgpl-2.1
7,306
// The libMesh Finite Element Library. // Copyright (C) 2002-2021 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local includes #include "libmesh/transient_system.h" #include "libmesh/explicit_system.h" #include "libmesh/linear_implicit_system.h" #include "libmesh/nonlinear_implicit_system.h" #include "libmesh/dof_map.h" #include "libmesh/numeric_vector.h" #include "libmesh/rb_construction.h" #include "libmesh/eigen_system.h" namespace libMesh { // ------------------------------------------------------------ // TransientSystem implementation template <class Base> TransientSystem<Base>::TransientSystem (EquationSystems & es, const std::string & name_in, const unsigned int number_in) : Base(es, name_in, number_in), old_local_solution(nullptr), older_local_solution(nullptr) { this->add_old_vectors(); } template <class Base> TransientSystem<Base>::~TransientSystem () = default; template <class Base> void TransientSystem<Base>::clear () { // clear the parent data Base::clear(); // Restore us to a "basic" state this->add_old_vectors(); } template <class Base> void TransientSystem<Base>::re_update () { // re_update the parent system Base::re_update (); const std::vector<dof_id_type> & send_list = this->get_dof_map().get_send_list (); const dof_id_type first_local_dof = Base::get_dof_map().first_dof(); const dof_id_type end_local_dof = Base::get_dof_map().end_dof(); // Check sizes libmesh_assert_greater_equal (end_local_dof, first_local_dof); libmesh_assert_greater_equal (older_local_solution->size(), send_list.size()); libmesh_assert_greater_equal (old_local_solution->size(), send_list.size()); // Even if we don't have to do anything ourselves, localize() may // use parallel_only tools // if (first_local_dof == end_local_dof) // return; // Update the old & older solutions with the send_list, // which may have changed since their last update. older_local_solution->localize (first_local_dof, end_local_dof-1, send_list); old_local_solution->localize (first_local_dof, end_local_dof-1, send_list); } template <class Base> Number TransientSystem<Base>::old_solution (const dof_id_type global_dof_number) const { // Check the sizes libmesh_assert_less (global_dof_number, this->get_dof_map().n_dofs()); libmesh_assert_less (global_dof_number, old_local_solution->size()); return (*old_local_solution)(global_dof_number); } template <class Base> Number TransientSystem<Base>::older_solution (const dof_id_type global_dof_number) const { // Check the sizes libmesh_assert_less (global_dof_number, this->get_dof_map().n_dofs()); libmesh_assert_less (global_dof_number, older_local_solution->size()); return (*older_local_solution)(global_dof_number); } template <class Base> void TransientSystem<Base>::add_old_vectors() { ParallelType type = #ifdef LIBMESH_ENABLE_GHOSTED GHOSTED; #else SERIAL; #endif old_local_solution = &(this->add_vector("_transient_old_local_solution", true, type)); older_local_solution = &(this->add_vector("_transient_older_local_solution", true, type)); } // ------------------------------------------------------------ // TransientSystem instantiations template class TransientSystem<LinearImplicitSystem>; template class TransientSystem<NonlinearImplicitSystem>; template class TransientSystem<ExplicitSystem>; template class TransientSystem<System>; template class TransientSystem<RBConstruction>; #ifdef LIBMESH_HAVE_SLEPC template class TransientSystem<EigenSystem>; #endif } // namespace libMesh
dschwen/libmesh
src/systems/transient_system.C
C++
lgpl-2.1
4,537
// constant definition const c = 11; shouldBe("c", "11"); // attempt to redefine should have no effect c = 22; shouldBe("c", "11"); const dummy = 0; for (var v = 0;;) { ++v; shouldBe("v", "1"); break; } // local vars & consts function h () { function shouldBe(_a, _b) { if (typeof _a != "string" || typeof _b != "string") debug("WARN: shouldBe() expects string arguments"); var _av, _bv; try { _av = eval(_a); } catch (e) { _av = evalError(_a, e); } try { _bv = eval(_b); } catch (e) { _bv = evalError(_b, e); } if (_av === _bv) testPassed(_a + " is " + _b); else testFailed(_a + " should be " + _bv + ". Was " + _av); } var hvar = 1; const hconst = 1; shouldBe("hvar", "1"); shouldBe("hconst", "1"); hvar = 2; hconst = 2; shouldBe("hvar", "2"); shouldBe("hconst", "1"); ++hvar; ++hconst; shouldBe("hvar", "3"); shouldBe("hconst", "1"); shouldBe("(hvar = 4)", "4"); shouldBe("(hconst = 4)", "4"); shouldBe("hvar", "4"); shouldBe("hconst", "1"); } h(); h(); // ### check for forbidden redeclaration
KDE/kjs
tests/const.js
JavaScript
lgpl-2.1
1,109
package net.sourceforge.pinyin4j; import com.hp.hpl.sparta.Document; import com.hp.hpl.sparta.ParseException; import com.hp.hpl.sparta.Parser; import java.io.FileNotFoundException; import java.io.IOException; class GwoyeuRomatzyhResource { private Document pinyinToGwoyeuMappingDoc; private GwoyeuRomatzyhResource() { initializeResource(); } GwoyeuRomatzyhResource(1 param1) { this(); } static GwoyeuRomatzyhResource getInstance() { return GwoyeuRomatzyhSystemResourceHolder.theInstance; } private void initializeResource() { try { setPinyinToGwoyeuMappingDoc(Parser.parse("", ResourceHelper.getResourceInputStream("/pinyindb/pinyin_gwoyeu_mapping.xml"))); return; } catch (FileNotFoundException localFileNotFoundException) { localFileNotFoundException.printStackTrace(); return; } catch (IOException localIOException) { localIOException.printStackTrace(); return; } catch (ParseException localParseException) { localParseException.printStackTrace(); } } private void setPinyinToGwoyeuMappingDoc(Document paramDocument) { this.pinyinToGwoyeuMappingDoc = paramDocument; } Document getPinyinToGwoyeuMappingDoc() { return this.pinyinToGwoyeuMappingDoc; } private static class GwoyeuRomatzyhSystemResourceHolder { static final GwoyeuRomatzyhResource theInstance = new GwoyeuRomatzyhResource(null); } } /* Location: D:\Documents\Reverse\BDDX\classes-dex2jar.jar * Qualified Name: net.sourceforge.pinyin4j.GwoyeuRomatzyhResource * JD-Core Version: 0.6.2 */
klosejay/android
source/Reverse/BDDX/classes-dex2jar.src/net/sourceforge/pinyin4j/GwoyeuRomatzyhResource.java
Java
lgpl-2.1
1,707
/* * SOMImageTester.java * This sample application uses some code written by Jeff Heaton took by the article * "Programming Neural Networks in Java" at http://www.jeffheaton.com/ai/index.shtml */ package org.joone.samples.editor.som; import java.io.*; /** * * @author Julien Norman */ public class SOMImageTester extends javax.swing.JFrame { private int DrawSizeX = 81; private int DrawSizeY = 81; private int ScaleSizeX = 9; private int ScaleSizeY = 9; private java.util.Vector imageHolder = new java.util.Vector(); private java.awt.Image downsamplePreviewImage = null; private java.awt.image.BufferedImage downSample = new java.awt.image.BufferedImage(getScaleSizeX(),getScaleSizeY(),java.awt.image.BufferedImage.TYPE_INT_RGB); private java.awt.image.BufferedImage drawImage = new java.awt.image.BufferedImage(getDrawSizeX(),getDrawSizeY(),java.awt.image.BufferedImage.TYPE_INT_RGB); private java.util.Vector idHolder = new java.util.Vector(); private int currentImage = 0; private boolean alone; // true if launched from the command prompt /** * Specifies the left boundary of the cropping * rectangle. */ protected int downSampleLeft; /** * Specifies the right boundary of the cropping * rectangle. */ protected int downSampleRight; /** * Specifies the top boundary of the cropping * rectangle. */ protected int downSampleTop; /** * Specifies the bottom boundary of the cropping * rectangle. */ protected int downSampleBottom; /** * The downsample ratio for x. */ protected double ratioX; /** * The downsample ratio for y */ protected double ratioY; /** * The pixel map of what the user has drawn. * Used to downsample it. */ protected int pixelMap[]; /** Creates new form SOMImageTester */ public SOMImageTester() { this(false); } /** Creates new form SOMImageTester */ public SOMImageTester(boolean main) { alone = main; initComponents(); setup(); setSize(300,350); setResizable(false); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ private void initComponents() {//GEN-BEGIN:initComponents ImageHolderPanel = new javax.swing.JPanel(); PainterPanel = new ImagePainter(); DownsamplePanel = new ImageDrawer(); InfoPanel = new javax.swing.JPanel(); ImageIDLabel = new javax.swing.JLabel(); IDInputTextField = new javax.swing.JTextField(); ImageNoLabel = new javax.swing.JLabel(); DownSampleButton = new javax.swing.JButton(); ImageScrollBar = new javax.swing.JScrollBar(); ControlPanel = new javax.swing.JPanel(); HelpButton = new javax.swing.JButton(); NewImageButton = new javax.swing.JButton(); ClearImageButton = new javax.swing.JButton(); SaveImagesButton = new javax.swing.JButton(); QuitButton = new javax.swing.JButton(); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } }); ImageHolderPanel.setLayout(new java.awt.GridLayout(1, 2)); PainterPanel.setToolTipText("You can draw on this image."); ImageHolderPanel.add(PainterPanel); DownsamplePanel.setToolTipText("This contains the down sampled image."); ImageHolderPanel.add(DownsamplePanel); getContentPane().add(ImageHolderPanel, java.awt.BorderLayout.CENTER); InfoPanel.setLayout(new java.awt.GridLayout(2, 2)); ImageIDLabel.setText("Image ID"); InfoPanel.add(ImageIDLabel); IDInputTextField.setText("1"); InfoPanel.add(IDInputTextField); ImageNoLabel.setFont(new java.awt.Font("Dialog", 1, 14)); ImageNoLabel.setText("Image 1 of 1"); ImageNoLabel.setToolTipText("The current image number."); InfoPanel.add(ImageNoLabel); DownSampleButton.setText("Down Sample"); DownSampleButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DownSampleButtonActionPerformed(evt); } }); InfoPanel.add(DownSampleButton); getContentPane().add(InfoPanel, java.awt.BorderLayout.NORTH); ImageScrollBar.setMaximum(1); ImageScrollBar.setMinimum(1); ImageScrollBar.setToolTipText("Use scroll bar to scroll through images."); ImageScrollBar.addAdjustmentListener(new java.awt.event.AdjustmentListener() { public void adjustmentValueChanged(java.awt.event.AdjustmentEvent evt) { OnScrolled(evt); } }); getContentPane().add(ImageScrollBar, java.awt.BorderLayout.EAST); ControlPanel.setLayout(new java.awt.GridLayout(5, 2)); ControlPanel.setBorder(new javax.swing.border.TitledBorder("Controls")); HelpButton.setText("Help"); HelpButton.setToolTipText("Help on this application."); HelpButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { HelpButtonActionPerformed(evt); } }); ControlPanel.add(HelpButton); NewImageButton.setText("New Image"); NewImageButton.setToolTipText("Create a new image."); NewImageButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NewImageButtonActionPerformed(evt); } }); ControlPanel.add(NewImageButton); ClearImageButton.setText("Clear Image"); ClearImageButton.setToolTipText("Clear the drawing from this image."); ClearImageButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ClearImageButtonActionPerformed(evt); } }); ControlPanel.add(ClearImageButton); SaveImagesButton.setText("Save Images"); SaveImagesButton.setToolTipText("Save the images out to Joone format."); SaveImagesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveImagesButtonActionPerformed(evt); } }); ControlPanel.add(SaveImagesButton); QuitButton.setText("Quit"); QuitButton.setToolTipText("Quit this application."); QuitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { QuitButtonActionPerformed(evt); } }); ControlPanel.add(QuitButton); getContentPane().add(ControlPanel, java.awt.BorderLayout.SOUTH); pack(); }//GEN-END:initComponents private void HelpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HelpButtonActionPerformed // Add your handling code here: // Produce a quick help box String help1 = new String("This application allows the user to draw characters or images for recognition by a Joone neural network."); String help2 = new String("It is intended to test a SOM or Kohonen Network by providing an image recognition example."); String help3 = new String("The drawing image grid is 81 X 81 but the images saved in the file are 9x9 down sampled images."); String help4 = new String("The saved file has 81 inputs and an id. The id can be used to identify the character."); String help5 = new String("Read the Editor's help pages to learn how to use this example."); javax.swing.JOptionPane.showMessageDialog(this,help1+"\n"+help2+"\n"+help3+"\n"+help4+"\n"+help5); }//GEN-LAST:event_HelpButtonActionPerformed private void QuitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QuitButtonActionPerformed // Add your handling code here: this.exitTester(); }//GEN-LAST:event_QuitButtonActionPerformed private void SaveImagesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveImagesButtonActionPerformed // Add your handling code here: SaveImagesOut(); }//GEN-LAST:event_SaveImagesButtonActionPerformed private void NewImageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewImageButtonActionPerformed // Add your handling code here: NewImage(); }//GEN-LAST:event_NewImageButtonActionPerformed private void ClearImageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClearImageButtonActionPerformed // Add your handling code here: clearCurrentImage(); }//GEN-LAST:event_ClearImageButtonActionPerformed private void DownSampleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DownSampleButtonActionPerformed // Add your handling code here: downSample(); repaint(); }//GEN-LAST:event_DownSampleButtonActionPerformed private void OnScrolled(java.awt.event.AdjustmentEvent evt) {//GEN-FIRST:event_OnScrolled // Add your handling code here: Integer id = null; if ( evt.getAdjustmentType() == java.awt.event.AdjustmentEvent.TRACK ) { if ( evt.getValue() <= imageHolder.size() ) { try { id = new Integer(IDInputTextField.getText()); } catch(java.lang.NumberFormatException ex) { ImageScrollBar.setValue(ImageScrollBar.getValue()-ImageScrollBar.getUnitIncrement()); javax.swing.JOptionPane.showMessageDialog(this,"ID must be an integer value."); return; } idHolder.set(currentImage-1, id); currentImage = evt.getValue(); IDInputTextField.setText(""+((Integer)idHolder.get(currentImage-1)).intValue()); drawImage = (java.awt.image.BufferedImage)imageHolder.get(currentImage-1); ((ImagePainter)PainterPanel).setImageToEdit(drawImage); downSample(); ImageNoLabel.setText("Image 1 of "+currentImage); repaint(); //PainterPanel.repaint(); //DownsamplePanel.repaint(); } } }//GEN-LAST:event_OnScrolled /** Exit the Application */ private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm this.exitTester(); }//GEN-LAST:event_exitForm private void exitTester() { if (alone) System.exit(0); else this.dispose(); } /** * */ public void setup() { if ( imageHolder != null ) { drawImage.getGraphics().setColor(new java.awt.Color(255,255,255)); drawImage.getGraphics().fillRect(0,0, drawImage.getWidth(),drawImage.getHeight()); imageHolder.add(drawImage); ((ImagePainter)PainterPanel).setImageToEdit(drawImage); if ( downsamplePreviewImage!= null) { downsamplePreviewImage.getGraphics().setColor(java.awt.Color.WHITE); downsamplePreviewImage.getGraphics().fillRect(0,0, downsamplePreviewImage.getWidth(this),downsamplePreviewImage.getHeight(this)); ((ImageDrawer)DownsamplePanel).setImageToDraw(downsamplePreviewImage); } idHolder.add(new Integer(1)); currentImage = 1; } repaint(); } /** * @param args the command line arguments */ public static void main(String args[]) { new SOMImageTester().show(); } /** Getter for property DrawSizeX. * @return Value of property DrawSizeX. * */ public int getDrawSizeX() { return DrawSizeX; } /** Setter for property DrawSizeX. * @param DrawSizeX New value of property DrawSizeX. * */ public void setDrawSizeX(int DrawSizeX) { this.DrawSizeX = DrawSizeX; } /** Getter for property DrawSizeY. * @return Value of property DrawSizeY. * */ public int getDrawSizeY() { return DrawSizeY; } /** Setter for property DrawSizeY. * @param DrawSizeY New value of property DrawSizeY. * */ public void setDrawSizeY(int DrawSizeY) { this.DrawSizeY = DrawSizeY; } /** Getter for property ScaleSizeX. * @return Value of property ScaleSizeX. * */ public int getScaleSizeX() { return ScaleSizeX; } /** Setter for property ScaleSizeX. * @param ScaleSizeX New value of property ScaleSizeX. * */ public void setScaleSizeX(int ScaleSizeX) { this.ScaleSizeX = ScaleSizeX; } /** Getter for property ScaleSizeY. * @return Value of property ScaleSizeY. * */ public int getScaleSizeY() { return ScaleSizeY; } /** Setter for property ScaleSizeY. * @param ScaleSizeY New value of property ScaleSizeY. * */ public void setScaleSizeY(int ScaleSizeY) { this.ScaleSizeY = ScaleSizeY; } /** * Clears the current image to white. */ public void clearCurrentImage() { drawImage.getGraphics().setColor(java.awt.Color.WHITE); drawImage.getGraphics().fillRect(0,0, drawImage.getWidth(),drawImage.getHeight()); downSample(); repaint(); } /** * Creates a new image and updates the scroll bar values. */ public void NewImage() { if ( imageHolder != null) { if ( idHolder != null ) { downSample = new java.awt.image.BufferedImage(getScaleSizeX(),getScaleSizeY(),java.awt.image.BufferedImage.TYPE_INT_RGB); drawImage = new java.awt.image.BufferedImage(getDrawSizeX(),getDrawSizeY(),java.awt.image.BufferedImage.TYPE_INT_RGB); clearCurrentImage(); Integer cur_id = (Integer)idHolder.get(currentImage-1); currentImage++; imageHolder.add(drawImage); idHolder.add(cur_id); IDInputTextField.setText(""+cur_id.intValue()); ImageScrollBar.setMaximum(currentImage); ImageScrollBar.setValue(currentImage); ((ImagePainter)PainterPanel).setImageToEdit(drawImage); ((ImageDrawer)DownsamplePanel).setImageToDraw(downsamplePreviewImage); ImageNoLabel.setText("Image 1 of "+currentImage); repaint(); } } } /** * This method is called internally to * see if there are any pixels in the given * scan line. This method is used to perform * autocropping. * * @param y The horizontal line to scan. * @return True if there were any pixels in this * horizontal line. */ protected boolean hLineClear(int y) { int w = drawImage.getWidth(this); for ( int i=0;i<w;i++ ) { if ( pixelMap[(y*w)+i] !=-1 ) return false; } return true; } /** * This method is called to determine .... * * @param x The vertical line to scan. * @return True if there are any pixels in the * specified vertical line. */ protected boolean vLineClear(int x) { int w = drawImage.getWidth(this); int h = drawImage.getHeight(this); for ( int i=0;i<h;i++ ) { if ( pixelMap[(i*w)+x] !=-1 ) return false; } return true; } /** * This method is called to automatically * crop the image so that whitespace is * removed. * * @param w The width of the image. * @param h The height of the image */ protected void findBounds(int w,int h) { // top line for ( int y=0;y<h;y++ ) { if ( !hLineClear(y) ) { downSampleTop=y; break; } } // bottom line for ( int y=h-1;y>=0;y-- ) { if ( !hLineClear(y) ) { downSampleBottom=y; break; } } // left line for ( int x=0;x<w;x++ ) { if ( !vLineClear(x) ) { downSampleLeft = x; break; } } // right line for ( int x=w-1;x>=0;x-- ) { if ( !vLineClear(x) ) { downSampleRight = x; break; } } } /** * Called to downsample a quadrant of the image. * * @param x The x coordinate of the resulting * downsample. * @param y The y coordinate of the resulting * downsample. * @return Returns true if there were ANY pixels * in the specified quadrant. */ protected boolean downSampleQuadrant(int x,int y) { int w = drawImage.getWidth(this); int startX = (int)(downSampleLeft+(x*ratioX)); int startY = (int)(downSampleTop+(y*ratioY)); int endX = (int)(startX + ratioX); int endY = (int)(startY + ratioY); for ( int yy=startY;yy<=endY;yy++ ) { for ( int xx=startX;xx<=endX;xx++ ) { int loc = xx+(yy*w); if ( pixelMap[ loc ]!= -1 ) return true; } } return false; } /** * Called to downsample the image and store * it in the down sample component. */ public void downSample() { int w = drawImage.getWidth(this); int h = drawImage.getHeight(this); java.awt.image.PixelGrabber grabber = new java.awt.image.PixelGrabber(drawImage,0,0,w,h,true); try { grabber.grabPixels(); pixelMap = (int[])grabber.getPixels(); findBounds(w,h); // now downsample ratioX = (double)(downSampleRight - downSampleLeft)/(double)downSample.getWidth(); ratioY = (double)(downSampleBottom - downSampleTop)/(double)downSample.getHeight(); for ( int y=0;y<downSample.getHeight();y++ ) { for ( int x=0;x<downSample.getWidth();x++ ) { if ( downSampleQuadrant(x,y) ) downSample.setRGB(x,y,java.awt.Color.BLACK.getRGB()); else downSample.setRGB(x,y,java.awt.Color.WHITE.getRGB()); } } // We have now down sampled the current draw image to the downSample image. // Now produce a large sclae version of the down sample so user can see it. downsamplePreviewImage = downSample.getScaledInstance(getDrawSizeX(), getDrawSizeY(), java.awt.Image.SCALE_DEFAULT); if ( downsamplePreviewImage!= null) { ((ImageDrawer)DownsamplePanel).setImageToDraw(downsamplePreviewImage); } } catch ( InterruptedException e ) { } } public void SaveImagesOut() { FileOutputStream joone_file = null; DataOutputStream joone_out = null; javax.swing.JFileChooser choose = new javax.swing.JFileChooser(); int result = choose.showSaveDialog(this); try { if ( result == javax.swing.JFileChooser.APPROVE_OPTION ) { joone_file = new FileOutputStream(choose.getSelectedFile()); joone_out = new DataOutputStream(joone_file); for ( int i=0;i<imageHolder.size();i++) { drawImage = (java.awt.image.BufferedImage)imageHolder.get(i); downSample(); for ( int y=0;y<downSample.getHeight();y++) { for ( int x=0;x<downSample.getWidth();x++) { if ( downSample.getRGB(x,y) == java.awt.Color.BLACK.getRGB() ) joone_out.writeBytes("1.0;"); else joone_out.writeBytes("0.0;"); } } joone_out.writeBytes(((Integer)idHolder.get(i)).intValue()+"\n"); } } } catch(IOException ex) { javax.swing.JOptionPane.showInternalMessageDialog(this,"An error occurred while trying to write to the file. Error is "+ex.toString()); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ClearImageButton; private javax.swing.JPanel ControlPanel; private javax.swing.JButton DownSampleButton; private javax.swing.JPanel DownsamplePanel; private javax.swing.JButton HelpButton; private javax.swing.JTextField IDInputTextField; private javax.swing.JPanel ImageHolderPanel; private javax.swing.JLabel ImageIDLabel; private javax.swing.JLabel ImageNoLabel; private javax.swing.JScrollBar ImageScrollBar; private javax.swing.JPanel InfoPanel; private javax.swing.JButton NewImageButton; private javax.swing.JPanel PainterPanel; private javax.swing.JButton QuitButton; private javax.swing.JButton SaveImagesButton; // End of variables declaration//GEN-END:variables }
mivianmf/ocr-ia
samples/editor/som/SOMImageTester.java
Java
lgpl-2.1
22,078
import time import sys import re ignore_regex = ( #Twitter Usernames r"""(@[\w]+)""" , #Twitter Hashtags r"""(#[\w]+)""" , #URLs r"""(http[s]?://[\w_./]+)""" , #HTML Entities r"""(&[a-z]+;)""" #, #Non-Alphabet Word #r"""([^a-z^A-Z]+)""" ) stop_list = [w.strip() for w in open("data/stop_words.txt","rb").readlines()] def tokenize(text): for i in ignore_regex: text = re.sub(i, ' ', text) # Split by all alpha number characters except "`,-,_" tokens = re.split("[\s,.?!:)({}\"=*\[\]|;^<>~]+", text) filtered_tokens = set() for t in tokens: # Select only alphabetical words which can have "',-,_" in them. Length of word must be > 2. if re.match("(^[a-z][a-z'\-_]*[a-z]$)",t) is not None and t not in stop_list: filtered_tokens.add(t.lower()) return filtered_tokens if __name__ == "__main__": for l in open(sys.argv[1],"rb").readlines(): wl = tokenize(l) print " ".join(wl)
nkoilada/twitter_sentiment
tokens.py
Python
lgpl-2.1
915