text
stringlengths
4
1.01M
import { Game } from './game'; import { Point } from './primitives'; import { Util } from './util'; export class Viewport { public target: Point; public position: Point = { x: 0, y: 0 }; private _game: Game; private _width: number; private _height: number; constructor(gameInstance: Game) { this._game = gameInstance; this._width = gameInstance.canvas.width; this._height = gameInstance.canvas.height; } private calculatePosition(): void { this.position.x = Util.clamp( this.target.x - this._width / 2, 0, this._game.map.width - this._width ); this.position.y = Util.clamp( this.target.y - this._height / 2, 0, this._game.map.height - this._height ); } update(): void { this.calculatePosition(); } }
#include <linux/kernel.h> #include <asm/cputype.h> #include <asm/idmap.h> #include <asm/pgalloc.h> #include <asm/pgtable.h> #include <asm/sections.h> #include <asm/system_info.h> pgd_t *idmap_pgd; #ifdef CONFIG_ARM_LPAE static void idmap_add_pmd(pud_t *pud, unsigned long addr, unsigned long end, unsigned long prot) { pmd_t *pmd; unsigned long next; if (pud_none_or_clear_bad(pud) || (pud_val(*pud) & L_PGD_SWAPPER)) { pmd = pmd_alloc_one(&init_mm, addr); if (!pmd) { pr_warning("Failed to allocate identity pmd.\n"); return; } pud_populate(&init_mm, pud, pmd); pmd += pmd_index(addr); } else pmd = pmd_offset(pud, addr); do { next = pmd_addr_end(addr, end); *pmd = __pmd((addr & PMD_MASK) | prot); flush_pmd_entry(pmd); } while (pmd++, addr = next, addr != end); } #else /* !CONFIG_ARM_LPAE */ static void idmap_add_pmd(pud_t *pud, unsigned long addr, unsigned long end, unsigned long prot) { pmd_t *pmd = pmd_offset(pud, addr); addr = (addr & PMD_MASK) | prot; pmd[0] = __pmd(addr); addr += SECTION_SIZE; pmd[1] = __pmd(addr); flush_pmd_entry(pmd); } #endif /* CONFIG_ARM_LPAE */ static void idmap_add_pud(pgd_t *pgd, unsigned long addr, unsigned long end, unsigned long prot) { pud_t *pud = pud_offset(pgd, addr); unsigned long next; do { next = pud_addr_end(addr, end); idmap_add_pmd(pud, addr, next, prot); } while (pud++, addr = next, addr != end); } void identity_mapping_add(pgd_t *pgd, unsigned long addr, unsigned long end) { unsigned long prot, next; prot = PMD_TYPE_SECT | PMD_SECT_AP_WRITE | PMD_SECT_AF; if (cpu_architecture() <= CPU_ARCH_ARMv5TEJ && !cpu_is_xscale()) prot |= PMD_BIT4; pgd += pgd_index(addr); do { next = pgd_addr_end(addr, end); idmap_add_pud(pgd, addr, next, prot); } while (pgd++, addr = next, addr != end); } extern char __idmap_text_start[], __idmap_text_end[]; static int __init init_static_idmap(void) { phys_addr_t idmap_start, idmap_end; idmap_pgd = pgd_alloc(&init_mm); if (!idmap_pgd) return -ENOMEM; /* Add an identity mapping for the physical address of the section. */ idmap_start = virt_to_phys((void *)__idmap_text_start); idmap_end = virt_to_phys((void *)__idmap_text_end); pr_info("Setting up static identity map for 0x%llx - 0x%llx\n", (long long)idmap_start, (long long)idmap_end); identity_mapping_add(idmap_pgd, idmap_start, idmap_end); return 0; } early_initcall(init_static_idmap); /* * In order to soft-boot, we need to switch to a 1:1 mapping for the * cpu_reset functions. This will then ensure that we have predictable * results when turning off the mmu. */ void setup_mm_for_reboot(void) { /* Clean and invalidate L1. */ flush_cache_all(); /* Switch to the identity mapping. */ cpu_switch_mm(idmap_pgd, &init_mm); /* Flush the TLB. */ local_flush_tlb_all(); }
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2016 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from superdesk import etree as sd_etree from lxml import etree from flask_babel import lazy_gettext def extract_html_macro(item, **kwargs): """Delete from body_html all html tags except links""" if "body_html" not in item: return None root = sd_etree.parse_html(item["body_html"], content="html") links = {} count = 0 # extract all links and add them to a dictionary with a unique # generated key for every link for a in root.findall(".//a"): links["__##link" + str(count) + "##__"] = etree.tostring(a, encoding="unicode") count = count + 1 # replace all text links with the generated keys # regenerate html back from root in order to avoid issues # on link replacements where are used text links generated from root body_html = etree.tostring(root, encoding="unicode") for link in links: body_html = body_html.replace(links[link], link) body_html = body_html.replace("<p>", "__##br##__") body_html = body_html.replace("</p>", "__##br##__") body_html = body_html.replace("<br/>", "__##br##__") # extract text from the html that don't contains any link, # it just contains link keys that are not affected by text extraction # because they are already text root = sd_etree.parse_html(body_html, content="html") body_html = etree.tostring(root, encoding="unicode", method="text") # in extracted text replace the link keys with links for link in links: body_html = body_html.replace(link, links[link]) body_html = body_html.replace("\n", "__##br##__") list_paragraph = body_html.split("__##br##__") item["body_html"] = "".join("<p>" + p + "</p>" for p in list_paragraph if p and p.strip()) return item name = "Extract Html Macro" label = lazy_gettext("Extract Html Macro") callback = extract_html_macro access_type = "frontend" action_type = "direct"
require 'rails_helper' RSpec.describe User, type: :model do it { should validate_presence_of :email } it { should validate_presence_of :password } it { should validate_presence_of :name } it { should validate_length_of(:name).is_at_least(2).is_at_most(20) } it { should validate_uniqueness_of(:email).ignoring_case_sensitivity } describe 'pending approval' do let(:user){ create(:user) } it 'change pending approval from nil to false' do expect do user.confirm_verification! end.to change { user.pending_approval }.from(nil).to(false) end it 'change pending approval from nil to true' do expect do user.decline_verification! end.to change { user.pending_approval }.from(nil).to(true) end end describe 'pending approval' do it 'change pending approval from nil to false' do user = create(:user) expect do user.ban_user! end.to change { user.ban_user }.from(false).to(true) end it 'change pending approval from nil to true' do user = create(:user, ban_user: true) expect do user.cancel_ban_user! end.to change { user.ban_user }.from(true).to(false) end end describe '.find_for_oauth' do let!(:user){ create(:user) } let(:auth){ OmniAuth::AuthHash.new(provider: 'vkontakte', uid: '123456') } context 'user already registered' do it 'returns the user' do user.authorizations.create(provider: 'vkontakte', uid: '123456') expect(User.find_for_oauth(auth)).to eq user end end context 'user has not authorization' do context 'user already exist' do let(:auth) do OmniAuth::AuthHash.new( provider: 'vkontakte', uid: '123456', info: { email: user.email, name: user.name } ) end let(:auth_email_nil) do OmniAuth::AuthHash.new( provider: 'vkontakte', uid: '123456', info: { email: '', name: 'New Name' } ) end it 'does not create new user' do expect do User.find_for_oauth(auth) end.to_not change(User, :count) end it 'creates authorization for user' do expect do User.find_for_oauth(auth) end.to change(user.authorizations, :count).by(1) end it 'creates authorizations with provider and uid' do authorization = User.find_for_oauth(auth).authorizations.first expect(authorization.provider).to eq auth.provider expect(authorization.uid).to eq auth.uid end it 'returns the user' do expect(User.find_for_oauth(auth)).to eq user end it 'returns nil if email blank' do expect(User.find_for_oauth(auth_email_nil)).to be_nil end end context 'user does not exist' do let(:auth) do OmniAuth::AuthHash.new( provider: 'vkontakte', uid: '123456', info: { email: 'new@user.com', first_name: 'First Name', last_name: 'Last Name', city: 'City', url: 'http://test.url' } ) end let(:auth_email_nil) do OmniAuth::AuthHash.new( provider: 'vkontakte', uid: '123456', info: { email: '', first_name: 'First Name', last_name: 'Last Name', city: 'City', url: 'http://test.url' } ) end it 'creates new user'do expect { User.find_for_oauth(auth) }.to change(User, :count).by(1) end it 'return new user' do expect(User.find_for_oauth(auth)).to be_a(User) end it 'fills user name' do user = User.find_for_oauth(auth) expect(user.name).to eq auth.info.first_name end it 'fills user surname' do user = User.find_for_oauth(auth) expect(user.surname).to eq auth.info.last_name end it 'fills user email' do user = User.find_for_oauth(auth) expect(user.email).to eq auth.info.email end it 'creates authorization for user' do user = User.find_for_oauth(auth) expect(user.authorizations).to_not be_empty end it 'create authorization with provider and uid' do authorization = User.find_for_oauth(auth).authorizations.first expect(authorization.provider).to eq auth.provider expect(authorization.uid).to eq auth.uid end it 'returns nil if email blank' do expect(User.find_for_oauth(auth_email_nil)).to be_nil end end end end end
# yadt-config-rpm-maker # Copyright (C) 2011-2013 Immobilien Scout GmbH # # 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 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import shutil import subprocess from pysvn import ClientError from datetime import datetime from logging import ERROR, Formatter, FileHandler, getLogger from os import mkdir, remove, environ from os.path import exists, abspath from shutil import rmtree from subprocess import PIPE, Popen from config_rpm_maker import configuration from config_rpm_maker.configuration.properties import (is_no_clean_up_enabled, get_log_level, get_repo_packages_regex, get_config_rpm_prefix, is_config_viewer_only_enabled, get_path_to_spec_file) from config_rpm_maker.svnservice import SvnServiceException from config_rpm_maker.configuration import build_config_viewer_host_directory from config_rpm_maker.dependency import Dependency from config_rpm_maker.exceptions import BaseConfigRpmMakerException from config_rpm_maker.hostresolver import HostResolver from config_rpm_maker.utilities.logutils import verbose from config_rpm_maker.segment import OVERLAY_ORDER, ALL_SEGEMENTS from config_rpm_maker.token.tokenreplacer import TokenReplacer from config_rpm_maker.utilities.profiler import measure_execution_time LOGGER = getLogger(__name__) class CouldNotCreateConfigDirException(BaseConfigRpmMakerException): error_info = "Could not create host configuration directory :" class CouldNotBuildRpmException(BaseConfigRpmMakerException): error_info = "Could not create rpm for host :" class ConfigDirAlreadyExistsException(BaseConfigRpmMakerException): error_info = "Config dir already exists: " class CouldNotTarConfigurationDirectoryException(BaseConfigRpmMakerException): error_info = "Could not tar configuration directory: " class HostRpmBuilder(object): def __init__(self, thread_name, hostname, revision, work_dir, svn_service_queue, error_logging_handler=None): self.thread_name = thread_name self.hostname = hostname self.revision = revision self.work_dir = work_dir self.error_logging_handler = error_logging_handler self.output_file_path = os.path.join(self.work_dir, self.hostname + '.output') self.error_file_path = os.path.join(self.work_dir, self.hostname + '.error') self.logger = self._create_logger() self.svn_service_queue = svn_service_queue self.config_rpm_prefix = get_config_rpm_prefix() self.host_config_dir = os.path.join(self.work_dir, self.config_rpm_prefix + self.hostname) self.variables_dir = os.path.join(self.host_config_dir, 'VARIABLES') self.rpm_requires_path = os.path.join(self.variables_dir, 'RPM_REQUIRES') self.rpm_provides_path = os.path.join(self.variables_dir, 'RPM_PROVIDES') self.spec_file_path = os.path.join(self.host_config_dir, self.config_rpm_prefix + self.hostname + '.spec') self.config_viewer_host_dir = build_config_viewer_host_directory(hostname, revision=self.revision) self.rpm_build_dir = os.path.join(self.work_dir, 'rpmbuild') def build(self): LOGGER.info('%s: building configuration rpm(s) for host "%s"', self.thread_name, self.hostname) self.logger.info("Building config rpm for host %s revision %s", self.hostname, self.revision) if exists(self.host_config_dir): raise ConfigDirAlreadyExistsException( 'ERROR: "%s" exists already although I should be creating it now.' % self.host_config_dir) try: mkdir(self.host_config_dir) except Exception as exception: raise CouldNotCreateConfigDirException( 'Could not create host config directory "%s".' % self.host_config_dir, exception) overall_requires = [] overall_provides = [] overall_svn_paths = [] overall_exported = {} for segment in OVERLAY_ORDER: svn_paths, exported_paths, requires, provides = self._overlay_segment(segment) overall_exported[segment] = exported_paths overall_svn_paths += svn_paths overall_requires += requires overall_provides += provides self.logger.debug("Overall_exported: %s", overall_exported) self.logger.info("Overall_requires: %s", overall_requires) self.logger.info("Overall_provides: %s", overall_provides) self.logger.debug("Overall_svn_paths: %s", overall_svn_paths) if not exists(self.variables_dir): mkdir(self.variables_dir) self._write_dependency_file(overall_requires, self.rpm_requires_path, accumulate_duplicates=False) self._write_dependency_file(overall_provides, self.rpm_provides_path, accumulate_duplicates=True) self._write_file(os.path.join(self.variables_dir, 'REVISION'), self.revision) rpm_name_variable_file = os.path.join(self.variables_dir, 'RPM_NAME') self.is_a_group_rpm = exists(rpm_name_variable_file) self._save_segment_variables( do_not_write_host_segment_variable=self.is_a_group_rpm) if self.is_a_group_rpm: # Do some preliminary token filtering so that the RPM_NAME is expanded try: TokenReplacer.filter_directory(os.path.dirname(self.variables_dir), self.variables_dir, thread_name=self.thread_name, skip=False) except Exception as e: LOGGER.warning("Problem during preliminary filtering of " "variables for group {0}: {1}".format(self.hostname, e)) self.rpm_name = self._get_content(rpm_name_variable_file).rstrip() LOGGER.info('Host {0} will trigger group rpm build with name {1}'.format(self.hostname, self.rpm_name)) self.spec_file_path = os.path.join(self.host_config_dir, self.config_rpm_prefix + self.rpm_name + '.spec') self._write_file(os.path.join(self.variables_dir, 'INSTALL_PROTECTION_DEPENDENCY'), '') else: self._write_file(rpm_name_variable_file, self.hostname) self.rpm_name = self.hostname self._write_file(os.path.join(self.variables_dir, 'INSTALL_PROTECTION_DEPENDENCY'), 'hostname-@@@HOST@@@') repo_packages_regex = get_repo_packages_regex() self._write_dependency_file(overall_requires, os.path.join(self.variables_dir, 'RPM_REQUIRES_REPOS'), filter_regex=repo_packages_regex) self._write_dependency_file(overall_requires, os.path.join(self.variables_dir, 'RPM_REQUIRES_NON_REPOS'), filter_regex=repo_packages_regex, positive_filter=False) self._export_spec_file() self._save_log_entries_to_variable(overall_svn_paths) self._save_overlaying_to_variable(overall_exported) self._move_variables_out_of_rpm_dir() self._save_file_list() self._save_network_variables() patch_info = self._generate_patch_info() self._copy_files_for_config_viewer() # write patch info into variable and config viewer self._write_file(os.path.join(self.variables_dir, 'VARIABLES'), patch_info) self._write_file(os.path.join(self.config_viewer_host_dir, self.hostname + '.variables'), patch_info) self._filter_tokens_in_rpm_sources() if not is_config_viewer_only_enabled(): self._build_rpm_using_rpmbuild() LOGGER.debug('%s: writing configviewer data for host "%s"', self.thread_name, self.hostname) self._filter_tokens_in_config_viewer() self._write_revision_file_for_config_viewer() self._write_overlaying_for_config_viewer(overall_exported) self._remove_logger_handlers() self._clean_up() return self._find_rpms() def _clean_up(self): if is_no_clean_up_enabled(): verbose(LOGGER).debug('Not cleaning up anything for host "%s"', self.hostname) return LOGGER.debug('Cleaning up temporary files for host "%s"', self.hostname) rmtree(self.variables_dir) rmtree(self.host_config_dir) remove(self.output_file_path) remove(self.error_file_path) def _filter_tokens_in_config_viewer(self): def configviewer_token_replacer(token, replacement): filtered_replacement = replacement.rstrip() return '<strong title="%s">%s</strong>' % (token, filtered_replacement) token_replacer = TokenReplacer.filter_directory(self.config_viewer_host_dir, self.variables_dir, html_escape=True, replacer_function=configviewer_token_replacer, thread_name=self.thread_name) tokens_unused = set(token_replacer.token_values.keys()) - token_replacer.token_used path_to_unused_variables = os.path.join(self.config_viewer_host_dir, 'unused_variables.txt') self._write_file(path_to_unused_variables, '\n'.join(sorted(tokens_unused))) token_replacer.filter_file(path_to_unused_variables, html_escape=True) def _write_revision_file_for_config_viewer(self): revision_file_path = os.path.join(self.config_viewer_host_dir, self.hostname + '.rev') self._write_file(revision_file_path, self.revision) def _find_rpms(self): result = [] for root, dirs, files in os.walk(os.path.join(self.rpm_build_dir, 'RPMS')): for filename in files: if filename.startswith(self.config_rpm_prefix + self.rpm_name) and filename.endswith('.rpm'): result.append(os.path.join(root, filename)) for root, dirs, files in os.walk(os.path.join(self.rpm_build_dir, 'SRPMS')): for filename in files: if filename.startswith(self.config_rpm_prefix + self.rpm_name) and filename.endswith('.rpm'): result.append(os.path.join(root, filename)) return result @measure_execution_time def _build_rpm_using_rpmbuild(self): tar_path = self._tar_sources() working_environment = environ.copy() working_environment['HOME'] = abspath(self.work_dir) absolute_rpm_build_path = abspath(self.rpm_build_dir) clean_option = "--clean" if is_no_clean_up_enabled(): clean_option = "" rpmbuild_cmd = "rpmbuild %s --define '_topdir %s' -ta %s" % ( clean_option, absolute_rpm_build_path, tar_path) LOGGER.debug('%s: building rpms by executing "%s"', self.thread_name, rpmbuild_cmd) self.logger.info("Executing '%s' ...", rpmbuild_cmd) process = Popen(rpmbuild_cmd, shell=True, env=working_environment, stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() self.logger.info(stdout) if stderr: self.logger.error(stderr) if process.returncode: raise CouldNotBuildRpmException( 'Could not build RPM for host "%s": stdout="%s", stderr="%s"' % ( self.hostname, stdout.strip(), stderr.strip())) @measure_execution_time def _tar_sources(self): if self.is_a_group_rpm: group_config_dir = os.path.join(self.work_dir, self.config_rpm_prefix + self.rpm_name) shutil.move(self.host_config_dir, group_config_dir) self.host_config_dir = group_config_dir output_file = group_config_dir + '.tar.gz' tar_cmd = 'tar -cvzf "%s" -C %s %s' % ( output_file, self.work_dir, self.config_rpm_prefix + self.rpm_name) else: output_file = self.host_config_dir + '.tar.gz' tar_cmd = 'tar -cvzf "%s" -C %s %s' % ( output_file, self.work_dir, self.config_rpm_prefix + self.hostname) self.logger.debug("Executing %s ...", tar_cmd) process = subprocess.Popen(tar_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() if process.returncode: stdout = stdout.strip() stderr = stderr.strip() raise CouldNotTarConfigurationDirectoryException( 'Creating tar of config dir failed:\n stdout="%s",\n stderr="%s"' % (stdout, stderr)) return output_file @measure_execution_time def _filter_tokens_in_rpm_sources(self): TokenReplacer.filter_directory(self.host_config_dir, self.variables_dir, thread_name=self.thread_name) @measure_execution_time def _copy_files_for_config_viewer(self): if os.path.exists(self.config_viewer_host_dir): shutil.rmtree(self.config_viewer_host_dir) shutil.copytree(self.host_config_dir, self.config_viewer_host_dir, symlinks=True) shutil.copytree(self.variables_dir, os.path.join(self.config_viewer_host_dir, 'VARIABLES')) def _generate_patch_info(self): name_filter = lambda name: name not in ('SVNLOG', 'OVERLAYING') variables = filter(name_filter, os.listdir(self.variables_dir)) info_lines = [] for variable_name in sorted(variables): variable_value = self._get_content( os.path.join(self.variables_dir, variable_name)) info_lines.append(variable_name.rjust(40) + ' : ' + variable_value) return "\n".join(info_lines) + "\n" @measure_execution_time def _save_network_variables(self): ip, fqdn, aliases = HostResolver().resolve(self.hostname) self._write_file(os.path.join(self.variables_dir, 'IP'), ip) self._write_file(os.path.join(self.variables_dir, 'FQDN'), fqdn) self._write_file(os.path.join(self.variables_dir, 'ALIASES'), aliases) def _save_segment_variables(self, do_not_write_host_segment_variable): if do_not_write_host_segment_variable: all_segments = OVERLAY_ORDER[:-1] else: all_segments = ALL_SEGEMENTS for segment in all_segments: self._write_file( os.path.join(self.variables_dir, segment.get_variable_name()), segment.get(self.hostname)[-1]) def _save_file_list(self): path = os.path.join(self.work_dir, 'filelist.' + self.hostname) with open(path, 'w') as file_list: for root, _, file_names in os.walk(self.host_config_dir): for file_name in file_names: file_list.write(os.path.join(root, file_name) + "\n") def _move_variables_out_of_rpm_dir(self): new_var_dir = os.path.join(self.work_dir, 'VARIABLES.' + self.hostname) shutil.move(self.variables_dir, new_var_dir) self.variables_dir = new_var_dir def _save_log_entries_to_variable(self, svn_paths): svn_service = self._get_next_svn_service_from_queue() try: logs = svn_service.get_logs_for_revision(self.revision) except SvnServiceException, exc: svn_log = "Could not retrieve log for revision: {0}".format(exc) else: svn_log = self._render_log(logs[0]) finally: self.svn_service_queue.put(svn_service) self._write_file(os.path.join(self.variables_dir, 'SVNLOG'), svn_log) def _save_overlaying_to_variable(self, exported_dict): overlaying = {} for segment in OVERLAY_ORDER: for segment_name, path in exported_dict[segment]: overlaying[path] = segment_name lines = [segment_name.rjust(25) + ' : /' + path for path, segment_name in sorted(overlaying.items())] content = "\n".join(lines) self._write_file(os.path.join(self.variables_dir, 'OVERLAYING'), content) def _write_overlaying_for_config_viewer(self, exported_dict): overlaying = {} for segment in OVERLAY_ORDER: for segment_name, path in exported_dict[segment]: overlaying[path] = segment_name lines = [segment_name + ':/' + path for path, segment_name in sorted(overlaying.items())] content = "\n".join(lines) + "\n" file_name = os.path.join(self.config_viewer_host_dir, self.hostname + '.overlaying') self._write_file(file_name, content) def _render_log(self, log): author = log.get("author", "unknown_author") return """ ------------------------------------------------------------------------ r%s | %s | %s Change set: %s %s""" % (log['revision'].number, author, datetime.fromtimestamp(log['date']).strftime("%Y-%m-%d %H:%M:%S"), "\n ".join([path['action'] + ' ' + path['path'] for path in log['changed_paths']]), log['message']) def _export_spec_file(self): svn_service = self._get_next_svn_service_from_queue() try: svn_service.export(get_path_to_spec_file(), self.spec_file_path, self.revision) finally: self.svn_service_queue.put(svn_service) @measure_execution_time def _get_next_svn_service_from_queue(self): return self.svn_service_queue.get() def _overlay_segment(self, segment): requires = [] provides = [] svn_base_paths = [] exported_paths = [] for svn_path in segment.get_svn_paths(self.hostname): svn_service = self._get_next_svn_service_from_queue() try: new_exported_paths = svn_service.export(svn_path, self.host_config_dir, self.revision) exported_paths += new_exported_paths except ClientError: pass finally: self.svn_service_queue.put(svn_service) svn_base_paths.append(svn_path) requires += self._parse_dependency_file(self.rpm_requires_path) provides += self._parse_dependency_file(self.rpm_provides_path) return svn_base_paths, exported_paths, requires, provides def _parse_dependency_file(self, path): if os.path.exists(path): content = self._get_content(path) return [item for line in content.split('\n') for item in line.split(',')] return [] def _write_dependency_file(self, dependencies, file_path, accumulate_duplicates=True, filter_regex='.*', positive_filter=True): dep = Dependency(accumulate_dependencies=accumulate_duplicates, filter_regex=filter_regex, positive_filter=positive_filter) dep.add(dependencies) self._write_file(file_path, str(dep)) def _write_file(self, file_path, content): with open(file_path, 'w') as file_to_write: file_to_write.write(content) def _get_content(self, path): with open(path, 'r') as file_to_read: return file_to_read.read() def _remove_logger_handlers(self): self.logger.removeHandler(self.error_handler) self.logger.removeHandler(self.handler) self.error_handler.close() self.handler.close() def _create_logger(self): log_level = get_log_level() formatter = Formatter(configuration.LOG_FILE_FORMAT, configuration.LOG_FILE_DATE_FORMAT) self.handler = FileHandler(self.output_file_path) self.handler.setFormatter(formatter) self.handler.setLevel(log_level) self.error_handler = FileHandler(self.error_file_path) self.error_handler.setFormatter(formatter) self.error_handler.setLevel(ERROR) logger = getLogger(self.hostname) logger.addHandler(self.handler) logger.addHandler(self.error_handler) logger.setLevel(log_level) if self.error_logging_handler: logger.addHandler(self.error_logging_handler) return logger
/* * Copyright (C) 2015 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas 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. * * Canvas 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 program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import PropTypes from 'prop-types' import customTypes from './PropTypes' import I18n from 'i18n!theme_editor' // consider anything other than null or undefined (including '') as "set" function isSet(val) { return val === null || val === undefined } export default React.createClass({ displayName: 'ThemeEditorImageRow', propTypes: { varDef: customTypes.image, userInput: customTypes.userVariableInput, onChange: PropTypes.func.isRequired, currentValue: PropTypes.string, placeholder: PropTypes.string }, getDefaultProps(){ return { userInput: {} } }, // valid input: null, '', or an HTMLInputElement setValue(inputElementOrNewValue) { var chosenValue = inputElementOrNewValue if (!inputElementOrNewValue) { //if it's null or '' // if they hit the "Undo" or "Use Default" button, // we want to also clear out the value of the <input type=file> // but we don't want to mess with its value otherwise this.refs.fileInput.getDOMNode().value = '' } else { chosenValue = window.URL.createObjectURL(inputElementOrNewValue.files[0]) } this.props.onChange(chosenValue) }, render() { var inputName = 'brand_config[variables][' + this.props.varDef.variable_name + ']' var imgSrc = this.props.userInput.val || this.props.placeholder return ( <section className="Theme__editor-accordion_element Theme__editor-upload"> <div className="te-Flex"> <div className="Theme__editor-form--upload"> <div className="Theme__editor-upload_header"> <h4 className="Theme__editor-upload_title" > { this.props.varDef.human_name } </h4> <span className="Theme__editor-upload_restrictions"> { this.props.varDef.helper_text } </span> </div> <div className={'Theme__editor_preview-img-container Theme__editor_preview-img-container--' + this.props.varDef.variable_name}> {/* ^ this utility class is to control the background color that shows behind the images you can customize in theme editor - see theme_editor.scss */} <div className="Theme__editor_preview-img"> { imgSrc && <img src={imgSrc} className="Theme__editor-placeholder" alt="" /> } </div> </div> <div className="Theme__editor-image_upload"> <input type="hidden" name={!this.props.userInput.val && inputName} value={(this.props.userInput.val === '') ? '' : this.props.currentValue} /> <label className="Theme__editor-image_upload-label"> <span className="screenreader-only"> { this.props.varDef.human_name } </span> <input type="file" className="Theme__editor-input_upload" name={this.props.userInput.val && inputName} accept={this.props.varDef.accept} onChange={event => this.setValue(event.target)} ref="fileInput" /> <span className="Theme__editor-button_upload Button Button--link" aria-hidden="true"> { I18n.t('Select Image') } </span> </label> {this.props.userInput.val || this.props.currentValue ? ( <button type="button" className="Button Button--link" onClick={() => this.setValue(isSet(this.props.userInput.val) ? '' : null)} > { isSet(this.props.userInput.val) ? I18n.t('Use Default') : I18n.t('Undo') } </button> ) : ( null )} </div> </div> </div> </section> ) } })
/* Copyright (c) 2009-2013, Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 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. * */ #include <linux/module.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/err.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/ioport.h> #include <linux/uaccess.h> #include <linux/debugfs.h> #include <linux/seq_file.h> #include <linux/pm_runtime.h> #include <linux/of.h> #include <linux/dma-mapping.h> #include <linux/usb.h> #include <linux/usb/otg.h> #include <linux/usb/ulpi.h> #include <linux/usb/gadget.h> #include <linux/usb/hcd.h> #include <linux/usb/quirks.h> #include <linux/qpnp/qpnp-adc.h> #include <linux/usb/msm_hsusb.h> #include <linux/usb/msm_hsusb_hw.h> #include <linux/usb/msm_ext_chg.h> #include <linux/regulator/consumer.h> #include <linux/mfd/pm8xxx/pm8921-charger.h> #include <linux/mfd/pm8xxx/misc.h> #include <linux/mhl_8334.h> #include <mach/scm.h> #include <mach/clk.h> #include <mach/mpm.h> #include <mach/msm_xo.h> #include <mach/msm_bus.h> #include <mach/rpm-regulator.h> #include <linux/usb/htc_info.h> #include <mach/cable_detect.h> #include <mach/devices_cmdline.h> #define MSM_USB_BASE (motg->regs) #define DRIVER_NAME "msm_otg" #define ID_TIMER_FREQ (jiffies + msecs_to_jiffies(500)) #define CHG_RECHECK_DELAY (jiffies + msecs_to_jiffies(2000)) #define ULPI_IO_TIMEOUT_USEC (10 * 1000) #define USB_PHY_3P3_VOL_MIN 3050000 #define USB_PHY_3P3_VOL_MAX 3300000 #define USB_PHY_3P3_HPM_LOAD 50000 #define USB_PHY_3P3_LPM_LOAD 4000 #define USB_PHY_1P8_VOL_MIN 1800000 #define USB_PHY_1P8_VOL_MAX 1800000 #define USB_PHY_1P8_HPM_LOAD 50000 #define USB_PHY_1P8_LPM_LOAD 4000 #define USB_PHY_VDD_DIG_VOL_NONE 0 #define USB_PHY_VDD_DIG_VOL_MIN 1045000 #define USB_PHY_VDD_DIG_VOL_MAX 1320000 #define USB_SUSPEND_DELAY_TIME (500 * HZ/1000) #define RETRY_CHECK_TIMES 5 enum msm_otg_phy_reg_mode { USB_PHY_REG_OFF, USB_PHY_REG_ON, USB_PHY_REG_LPM_ON, USB_PHY_REG_LPM_OFF, }; int msm_otg_usb_disable = 0; static int msm_id_backup = 1; static char *override_phy_init; module_param(override_phy_init, charp, S_IRUGO|S_IWUSR); MODULE_PARM_DESC(override_phy_init, "Override HSUSB PHY Init Settings"); unsigned int lpm_disconnect_thresh = 1000; module_param(lpm_disconnect_thresh , uint, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(lpm_disconnect_thresh, "Delay before entering LPM on USB disconnect"); static bool floated_charger_enable; module_param(floated_charger_enable , bool, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(floated_charger_enable, "Whether to enable floated charger"); static DEFINE_MUTEX(smwork_sem); static DEFINE_MUTEX(notify_sem); static void send_usb_connect_notify(struct work_struct *w) { static struct t_usb_status_notifier *notifier; struct msm_otg *motg = container_of(w, struct msm_otg, notifier_work); struct usb_otg *otg; if (!motg) return; otg = motg->phy.otg; motg->connect_type_ready = 1; USBH_INFO("send connect type %d\n", motg->connect_type); mutex_lock(&notify_sem); list_for_each_entry(notifier, &g_lh_usb_notifier_list, notifier_link) { if (notifier->func != NULL) { notifier->func(motg->connect_type); } } mutex_unlock(&notify_sem); } int htc_msm_usb_register_notifier(struct t_usb_status_notifier *notifier) { if (!notifier || !notifier->name || !notifier->func) return -EINVAL; mutex_lock(&notify_sem); list_add(&notifier->notifier_link, &g_lh_usb_notifier_list); mutex_unlock(&notify_sem); return 0; } static DECLARE_COMPLETION(pmic_vbus_init); static struct msm_otg *the_msm_otg = NULL; static bool debug_aca_enabled; static bool debug_bus_voting_enabled; static bool mhl_det_in_progress; static struct regulator *hsusb_3p3; static struct regulator *hsusb_1p8; static struct regulator *hsusb_vdd; static struct regulator *vbus_otg; static struct regulator *mhl_usb_hs_switch; static struct power_supply *psy; static bool aca_id_turned_on; static bool legacy_power_supply; static inline bool aca_enabled(void) { #ifdef CONFIG_USB_MSM_ACA return true; #else return debug_aca_enabled; #endif } static int vdd_val[VDD_TYPE_MAX][VDD_VAL_MAX] = { { [VDD_NONE] = RPM_VREG_CORNER_NONE, [VDD_MIN] = RPM_VREG_CORNER_NOMINAL, [VDD_MAX] = RPM_VREG_CORNER_HIGH, }, { [VDD_NONE] = USB_PHY_VDD_DIG_VOL_NONE, [VDD_MIN] = USB_PHY_VDD_DIG_VOL_MIN, [VDD_MAX] = USB_PHY_VDD_DIG_VOL_MAX, }, }; static int msm_hsusb_ldo_init(struct msm_otg *motg, int init) { int rc = 0; if (init) { hsusb_3p3 = devm_regulator_get(motg->phy.dev, "HSUSB_3p3"); if (IS_ERR(hsusb_3p3)) { dev_err(motg->phy.dev, "unable to get hsusb 3p3\n"); return PTR_ERR(hsusb_3p3); } rc = regulator_set_voltage(hsusb_3p3, USB_PHY_3P3_VOL_MIN, USB_PHY_3P3_VOL_MAX); if (rc) { dev_err(motg->phy.dev, "unable to set voltage level for" "hsusb 3p3\n"); return rc; } hsusb_1p8 = devm_regulator_get(motg->phy.dev, "HSUSB_1p8"); if (IS_ERR(hsusb_1p8)) { dev_err(motg->phy.dev, "unable to get hsusb 1p8\n"); rc = PTR_ERR(hsusb_1p8); goto put_3p3_lpm; } rc = regulator_set_voltage(hsusb_1p8, USB_PHY_1P8_VOL_MIN, USB_PHY_1P8_VOL_MAX); if (rc) { dev_err(motg->phy.dev, "unable to set voltage level " "for hsusb 1p8\n"); goto put_1p8; } return 0; } put_1p8: regulator_set_voltage(hsusb_1p8, 0, USB_PHY_1P8_VOL_MAX); put_3p3_lpm: regulator_set_voltage(hsusb_3p3, 0, USB_PHY_3P3_VOL_MAX); return rc; } static int msm_hsusb_config_vddcx(int high) { struct msm_otg *motg = the_msm_otg; enum usb_vdd_type vdd_type = motg->vdd_type; int max_vol = vdd_val[vdd_type][VDD_MAX]; int min_vol; int ret; min_vol = vdd_val[vdd_type][!!high]; ret = regulator_set_voltage(hsusb_vdd, min_vol, max_vol); if (ret) { pr_err("%s: unable to set the voltage for regulator " "HSUSB_VDDCX\n", __func__); return ret; } pr_debug("%s: min_vol:%d max_vol:%d\n", __func__, min_vol, max_vol); return ret; } static int msm_hsusb_ldo_enable(struct msm_otg *motg, enum msm_otg_phy_reg_mode mode) { int ret = 0; if (IS_ERR(hsusb_1p8)) { pr_err("%s: HSUSB_1p8 is not initialized\n", __func__); return -ENODEV; } if (IS_ERR(hsusb_3p3)) { pr_err("%s: HSUSB_3p3 is not initialized\n", __func__); return -ENODEV; } switch (mode) { case USB_PHY_REG_ON: ret = regulator_set_optimum_mode(hsusb_1p8, USB_PHY_1P8_HPM_LOAD); if (ret < 0) { pr_err("%s: Unable to set HPM of the regulator " "HSUSB_1p8\n", __func__); return ret; } ret = regulator_enable(hsusb_1p8); if (ret) { dev_err(motg->phy.dev, "%s: unable to enable the hsusb 1p8\n", __func__); regulator_set_optimum_mode(hsusb_1p8, 0); return ret; } ret = regulator_set_optimum_mode(hsusb_3p3, USB_PHY_3P3_HPM_LOAD); if (ret < 0) { pr_err("%s: Unable to set HPM of the regulator " "HSUSB_3p3\n", __func__); regulator_set_optimum_mode(hsusb_1p8, 0); regulator_disable(hsusb_1p8); return ret; } ret = regulator_enable(hsusb_3p3); if (ret) { dev_err(motg->phy.dev, "%s: unable to enable the hsusb 3p3\n", __func__); regulator_set_optimum_mode(hsusb_3p3, 0); regulator_set_optimum_mode(hsusb_1p8, 0); regulator_disable(hsusb_1p8); return ret; } break; case USB_PHY_REG_OFF: ret = regulator_disable(hsusb_1p8); if (ret) { dev_err(motg->phy.dev, "%s: unable to disable the hsusb 1p8\n", __func__); return ret; } ret = regulator_set_optimum_mode(hsusb_1p8, 0); if (ret < 0) pr_err("%s: Unable to set LPM of the regulator " "HSUSB_1p8\n", __func__); #if 0 ret = regulator_disable(hsusb_3p3); if (ret) { dev_err(motg->phy.dev, "%s: unable to disable the hsusb 3p3\n", __func__); return ret; } ret = regulator_set_optimum_mode(hsusb_3p3, 0); if (ret < 0) pr_err("%s: Unable to set LPM of the regulator " "HSUSB_3p3\n", __func__); #endif break; case USB_PHY_REG_LPM_ON: ret = regulator_set_optimum_mode(hsusb_1p8, USB_PHY_1P8_LPM_LOAD); if (ret < 0) { pr_err("%s: Unable to set LPM of the regulator: HSUSB_1p8\n", __func__); return ret; } ret = regulator_set_optimum_mode(hsusb_3p3, USB_PHY_3P3_LPM_LOAD); if (ret < 0) { pr_err("%s: Unable to set LPM of the regulator: HSUSB_3p3\n", __func__); regulator_set_optimum_mode(hsusb_1p8, USB_PHY_REG_ON); return ret; } break; case USB_PHY_REG_LPM_OFF: ret = regulator_set_optimum_mode(hsusb_1p8, USB_PHY_1P8_HPM_LOAD); if (ret < 0) { pr_err("%s: Unable to set HPM of the regulator: HSUSB_1p8\n", __func__); return ret; } ret = regulator_set_optimum_mode(hsusb_3p3, USB_PHY_3P3_HPM_LOAD); if (ret < 0) { pr_err("%s: Unable to set HPM of the regulator: HSUSB_3p3\n", __func__); regulator_set_optimum_mode(hsusb_1p8, USB_PHY_REG_ON); return ret; } break; default: pr_err("%s: Unsupported mode (%d).", __func__, mode); return -ENOTSUPP; } pr_debug("%s: USB reg mode (%d) (OFF/HPM/LPM)\n", __func__, mode); return ret < 0 ? ret : 0; } static void msm_hsusb_mhl_switch_enable(struct msm_otg *motg, bool on) { struct msm_otg_platform_data *pdata = motg->pdata; if (!pdata->mhl_enable) return; if (!mhl_usb_hs_switch) { pr_err("%s: mhl_usb_hs_switch is NULL.\n", __func__); return; } if (on) { if (regulator_enable(mhl_usb_hs_switch)) pr_err("unable to enable mhl_usb_hs_switch\n"); } else { regulator_disable(mhl_usb_hs_switch); } } static int ulpi_read(struct usb_phy *phy, u32 reg) { struct msm_otg *motg = container_of(phy, struct msm_otg, phy); int cnt = 0; writel(ULPI_RUN | ULPI_READ | ULPI_ADDR(reg), USB_ULPI_VIEWPORT); while (cnt < ULPI_IO_TIMEOUT_USEC) { if (!(readl(USB_ULPI_VIEWPORT) & ULPI_RUN)) break; udelay(1); cnt++; } if (cnt >= ULPI_IO_TIMEOUT_USEC) { dev_err(phy->dev, "ulpi_read: timeout %08x\n", readl(USB_ULPI_VIEWPORT)); dev_err(phy->dev, "PORTSC: %08x USBCMD: %08x\n", readl_relaxed(USB_PORTSC), readl_relaxed(USB_USBCMD)); return -ETIMEDOUT; } return ULPI_DATA_READ(readl(USB_ULPI_VIEWPORT)); } static int ulpi_write(struct usb_phy *phy, u32 val, u32 reg) { struct msm_otg *motg = container_of(phy, struct msm_otg, phy); int cnt = 0; writel(ULPI_RUN | ULPI_WRITE | ULPI_ADDR(reg) | ULPI_DATA(val), USB_ULPI_VIEWPORT); while (cnt < ULPI_IO_TIMEOUT_USEC) { if (!(readl(USB_ULPI_VIEWPORT) & ULPI_RUN)) break; udelay(1); cnt++; } if (cnt >= ULPI_IO_TIMEOUT_USEC) { dev_err(phy->dev, "ulpi_write: timeout\n"); dev_err(phy->dev, "PORTSC: %08x USBCMD: %08x\n", readl_relaxed(USB_PORTSC), readl_relaxed(USB_USBCMD)); return -ETIMEDOUT; } return 0; } static struct usb_phy_io_ops msm_otg_io_ops = { .read = ulpi_read, .write = ulpi_write, }; extern unsigned int system_rev; #define EVM 0x99 #define EVM1 99 #define XA 0 #define XB 1 #define XC 2 #define XD 3 #define PVT 0x80 static void ulpi_init(struct msm_otg *motg) { struct msm_otg_platform_data *pdata = motg->pdata; int aseq[10]; int *seq = NULL; if (override_phy_init) { pr_debug("%s(): HUSB PHY Init:%s\n", __func__, override_phy_init); get_options(override_phy_init, ARRAY_SIZE(aseq), aseq); seq = &aseq[1]; } else { seq = pdata->phy_init_seq; } if (!seq) return; while (seq[0] >= 0) { if (override_phy_init) pr_debug("ulpi: write 0x%02x to 0x%02x\n", seq[0], seq[1]); USBH_INFO("ulpi: write 0x%02x to 0x%02x\n", seq[0], seq[1]); ulpi_write(&motg->phy, seq[0], seq[1]); seq += 2; } } static int msm_otg_link_clk_reset(struct msm_otg *motg, bool assert) { int ret; if (assert) { if (!IS_ERR(motg->clk)) { ret = clk_reset(motg->clk, CLK_RESET_ASSERT); } else { dev_dbg(motg->phy.dev, "block_reset ASSERT\n"); clk_disable_unprepare(motg->pclk); clk_disable_unprepare(motg->core_clk); ret = clk_reset(motg->core_clk, CLK_RESET_ASSERT); } if (ret) dev_err(motg->phy.dev, "usb hs_clk assert failed\n"); } else { if (!IS_ERR(motg->clk)) { ret = clk_reset(motg->clk, CLK_RESET_DEASSERT); } else { dev_dbg(motg->phy.dev, "block_reset DEASSERT\n"); ret = clk_reset(motg->core_clk, CLK_RESET_DEASSERT); ndelay(200); clk_prepare_enable(motg->core_clk); clk_prepare_enable(motg->pclk); } if (ret) dev_err(motg->phy.dev, "usb hs_clk deassert failed\n"); } return ret; } static int msm_otg_phy_reset(struct msm_otg *motg) { u32 val; int ret; struct msm_otg_platform_data *pdata = motg->pdata; val = readl_relaxed(USB_AHBMODE); if (val & AHB2AHB_BYPASS) { pr_err("%s(): AHB2AHB_BYPASS SET: AHBMODE:%x\n", __func__, val); val &= ~AHB2AHB_BYPASS_BIT_MASK; writel_relaxed(val | AHB2AHB_BYPASS_CLEAR, USB_AHBMODE); pr_err("%s(): AHBMODE: %x\n", __func__, readl_relaxed(USB_AHBMODE)); } ret = msm_otg_link_clk_reset(motg, 1); if (ret) return ret; usleep_range(1000, 1200); ret = msm_otg_link_clk_reset(motg, 0); if (ret) return ret; if (pdata && pdata->enable_sec_phy) writel_relaxed(readl_relaxed(USB_PHY_CTRL2) | (1<<16), USB_PHY_CTRL2); val = readl(USB_PORTSC) & ~PORTSC_PTS_MASK; writel(val | PORTSC_PTS_ULPI, USB_PORTSC); dev_info(motg->phy.dev, "phy_reset: success\n"); return 0; } #define LINK_RESET_TIMEOUT_USEC (250 * 1000) static int msm_otg_link_reset(struct msm_otg *motg) { int cnt = 0; struct msm_otg_platform_data *pdata = motg->pdata; writel_relaxed(USBCMD_RESET, USB_USBCMD); while (cnt < LINK_RESET_TIMEOUT_USEC) { if (!(readl_relaxed(USB_USBCMD) & USBCMD_RESET)) break; udelay(1); cnt++; } if (cnt >= LINK_RESET_TIMEOUT_USEC) return -ETIMEDOUT; writel_relaxed(0x80000000, USB_PORTSC); writel_relaxed(0x0, USB_AHBBURST); writel_relaxed(0x08, USB_AHBMODE); if (pdata && pdata->enable_sec_phy) writel_relaxed(readl_relaxed(USB_PHY_CTRL2) | (1<<16), USB_PHY_CTRL2); return 0; } static void usb_phy_reset(struct msm_otg *motg) { u32 val; if (motg->pdata->phy_type != SNPS_28NM_INTEGRATED_PHY) return; val = readl_relaxed(USB_PHY_CTRL); val &= ~PHY_POR_BIT_MASK; val |= PHY_POR_ASSERT; writel_relaxed(val, USB_PHY_CTRL); usleep_range(10, 15); val = readl_relaxed(USB_PHY_CTRL); val &= ~PHY_POR_BIT_MASK; val |= PHY_POR_DEASSERT; writel_relaxed(val, USB_PHY_CTRL); mb(); } static int msm_otg_reset(struct usb_phy *phy) { struct msm_otg *motg = container_of(phy, struct msm_otg, phy); struct msm_otg_platform_data *pdata = motg->pdata; int ret; u32 val = 0; u32 ulpi_val = 0; if (pdata->disable_reset_on_disconnect) { if (motg->reset_counter) return 0; else motg->reset_counter++; } if (!IS_ERR(motg->clk)) clk_prepare_enable(motg->clk); ret = msm_otg_phy_reset(motg); if (ret) { dev_err(phy->dev, "phy_reset failed\n"); return ret; } aca_id_turned_on = false; ret = msm_otg_link_reset(motg); if (ret) { dev_err(phy->dev, "link reset failed\n"); return ret; } msleep(100); usb_phy_reset(motg); ulpi_init(motg); usb_phy_reset(motg); if (!IS_ERR(motg->clk)) clk_disable_unprepare(motg->clk); if (pdata->otg_control == OTG_PHY_CONTROL) { val = readl_relaxed(USB_OTGSC); if (pdata->mode == USB_OTG) { ulpi_val = ULPI_INT_IDGRD | ULPI_INT_SESS_VALID; val |= OTGSC_IDIE | OTGSC_BSVIE; } else if (pdata->mode == USB_PERIPHERAL) { ulpi_val = ULPI_INT_SESS_VALID; val |= OTGSC_BSVIE; } writel_relaxed(val, USB_OTGSC); ulpi_write(phy, ulpi_val, ULPI_USB_INT_EN_RISE); ulpi_write(phy, ulpi_val, ULPI_USB_INT_EN_FALL); } else if (pdata->otg_control == OTG_PMIC_CONTROL) { ulpi_write(phy, OTG_COMP_DISABLE, ULPI_SET(ULPI_PWR_CLK_MNG_REG)); pm8xxx_usb_id_pullup(1); } if (motg->caps & ALLOW_VDD_MIN_WITH_RETENTION_DISABLED) writel_relaxed(readl_relaxed(USB_OTGSC) & ~(OTGSC_IDPU), USB_OTGSC); return 0; } static const char *timer_string(int bit) { switch (bit) { case A_WAIT_VRISE: return "a_wait_vrise"; case A_WAIT_VFALL: return "a_wait_vfall"; case B_SRP_FAIL: return "b_srp_fail"; case A_WAIT_BCON: return "a_wait_bcon"; case A_AIDL_BDIS: return "a_aidl_bdis"; case A_BIDL_ADIS: return "a_bidl_adis"; case B_ASE0_BRST: return "b_ase0_brst"; case A_TST_MAINT: return "a_tst_maint"; case B_TST_SRP: return "b_tst_srp"; case B_TST_CONFIG: return "b_tst_config"; default: return "UNDEFINED"; } } static enum hrtimer_restart msm_otg_timer_func(struct hrtimer *hrtimer) { struct msm_otg *motg = container_of(hrtimer, struct msm_otg, timer); switch (motg->active_tmout) { case A_WAIT_VRISE: set_bit(A_VBUS_VLD, &motg->inputs); break; case A_TST_MAINT: set_bit(A_BUS_DROP, &motg->inputs); break; case B_TST_SRP: set_bit(B_BUS_REQ, &motg->inputs); break; case B_TST_CONFIG: clear_bit(A_CONN, &motg->inputs); break; default: set_bit(motg->active_tmout, &motg->tmouts); } pr_debug("expired %s timer\n", timer_string(motg->active_tmout)); queue_work(system_nrt_wq, &motg->sm_work); return HRTIMER_NORESTART; } static void msm_otg_del_timer(struct msm_otg *motg) { int bit = motg->active_tmout; pr_debug("deleting %s timer. remaining %lld msec\n", timer_string(bit), div_s64(ktime_to_us(hrtimer_get_remaining( &motg->timer)), 1000)); hrtimer_cancel(&motg->timer); clear_bit(bit, &motg->tmouts); } static void msm_otg_start_timer(struct msm_otg *motg, int time, int bit) { clear_bit(bit, &motg->tmouts); motg->active_tmout = bit; pr_debug("starting %s timer\n", timer_string(bit)); hrtimer_start(&motg->timer, ktime_set(time / 1000, (time % 1000) * 1000000), HRTIMER_MODE_REL); } static void msm_otg_init_timer(struct msm_otg *motg) { hrtimer_init(&motg->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); motg->timer.function = msm_otg_timer_func; } static int msm_otg_start_hnp(struct usb_otg *otg) { struct msm_otg *motg = container_of(otg->phy, struct msm_otg, phy); if (otg->phy->state != OTG_STATE_A_HOST) { pr_err("HNP can not be initiated in %s state\n", otg_state_string(otg->phy->state)); return -EINVAL; } pr_debug("A-Host: HNP initiated\n"); clear_bit(A_BUS_REQ, &motg->inputs); queue_work(system_nrt_wq, &motg->sm_work); return 0; } static int msm_otg_start_srp(struct usb_otg *otg) { struct msm_otg *motg = container_of(otg->phy, struct msm_otg, phy); u32 val; int ret = 0; if (otg->phy->state != OTG_STATE_B_IDLE) { pr_err("SRP can not be initiated in %s state\n", otg_state_string(otg->phy->state)); ret = -EINVAL; goto out; } if ((jiffies - motg->b_last_se0_sess) < msecs_to_jiffies(TB_SRP_INIT)) { pr_debug("initial conditions of SRP are not met. Try again" "after some time\n"); ret = -EAGAIN; goto out; } pr_debug("B-Device SRP started\n"); ulpi_write(otg->phy, 0x03, 0x97); val = readl_relaxed(USB_OTGSC); writel_relaxed((val & ~OTGSC_INTSTS_MASK) | OTGSC_HADP, USB_OTGSC); out: return ret; } static void msm_otg_host_hnp_enable(struct usb_otg *otg, bool enable) { struct usb_hcd *hcd = bus_to_hcd(otg->host); struct usb_device *rhub = otg->host->root_hub; if (enable) { pm_runtime_disable(&rhub->dev); rhub->state = USB_STATE_NOTATTACHED; hcd->driver->bus_suspend(hcd); clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags); } else { usb_remove_hcd(hcd); msm_otg_reset(otg->phy); usb_add_hcd(hcd, hcd->irq, IRQF_SHARED); } } static int msm_otg_set_suspend(struct usb_phy *phy, int suspend) { struct msm_otg *motg = container_of(phy, struct msm_otg, phy); if (aca_enabled()) return 0; if (suspend) { switch (phy->state) { case OTG_STATE_A_WAIT_BCON: if (TA_WAIT_BCON > 0) break; case OTG_STATE_A_HOST: pr_debug("host bus suspend\n"); clear_bit(A_BUS_REQ, &motg->inputs); if (!atomic_read(&motg->in_lpm)) queue_work(system_nrt_wq, &motg->sm_work); break; case OTG_STATE_B_PERIPHERAL: pr_debug("peripheral bus suspend\n"); if (!(motg->caps & ALLOW_LPM_ON_DEV_SUSPEND)) break; set_bit(A_BUS_SUSPEND, &motg->inputs); if (!atomic_read(&motg->in_lpm)) queue_delayed_work(system_nrt_wq, &motg->suspend_work, USB_SUSPEND_DELAY_TIME); break; default: break; } } else { switch (phy->state) { case OTG_STATE_A_WAIT_BCON: set_bit(A_BUS_REQ, &motg->inputs); if (atomic_read(&motg->in_lpm)) pm_runtime_resume(phy->dev); break; case OTG_STATE_A_SUSPEND: set_bit(A_BUS_REQ, &motg->inputs); phy->state = OTG_STATE_A_HOST; if (atomic_read(&motg->in_lpm)) pm_runtime_resume(phy->dev); break; case OTG_STATE_B_PERIPHERAL: pr_debug("peripheral bus resume\n"); if (!(motg->caps & ALLOW_LPM_ON_DEV_SUSPEND)) break; clear_bit(A_BUS_SUSPEND, &motg->inputs); if (atomic_read(&motg->in_lpm)) queue_work(system_nrt_wq, &motg->sm_work); break; default: break; } } return 0; } static void msm_otg_bus_vote(struct msm_otg *motg, enum usb_bus_vote vote) { int ret; struct msm_otg_platform_data *pdata = motg->pdata; if (pdata->bus_scale_table && vote >= pdata->bus_scale_table->num_usecases) vote = USB_NO_PERF_VOTE; if (motg->bus_perf_client) { ret = msm_bus_scale_client_update_request( motg->bus_perf_client, vote); if (ret) dev_err(motg->phy.dev, "%s: Failed to vote (%d)\n" "for bus bw %d\n", __func__, vote, ret); } } #define PHY_SUSPEND_TIMEOUT_USEC (500 * 1000) #define PHY_RESUME_TIMEOUT_USEC (100 * 1000) #ifdef CONFIG_PM_SLEEP static int msm_otg_suspend(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; struct usb_bus *bus = phy->otg->host; struct msm_otg_platform_data *pdata = motg->pdata; int cnt = 0; bool host_bus_suspend, device_bus_suspend, dcp, prop_charger; bool floated_charger; u32 phy_ctrl_val = 0, cmd_val; unsigned ret; u32 portsc, config2; u32 func_ctrl; if (atomic_read(&motg->in_lpm)) return 0; if (motg->pdata->delay_lpm_hndshk_on_disconnect && !msm_bam_lpm_ok()) return -EBUSY; motg->ui_enabled = 0; disable_irq(motg->irq); host_bus_suspend = !test_bit(MHL, &motg->inputs) && phy->otg->host && !test_bit(ID, &motg->inputs); device_bus_suspend = phy->otg->gadget && test_bit(ID, &motg->inputs) && test_bit(A_BUS_SUSPEND, &motg->inputs) && motg->caps & ALLOW_LPM_ON_DEV_SUSPEND; dcp = motg->chg_type == USB_DCP_CHARGER; prop_charger = motg->chg_type == USB_PROPRIETARY_CHARGER; floated_charger = motg->chg_type == USB_FLOATED_CHARGER; config2 = readl_relaxed(USB_GENCONFIG2); if (device_bus_suspend) config2 |= GENCFG2_LINESTATE_DIFF_WAKEUP_EN; else config2 &= ~GENCFG2_LINESTATE_DIFF_WAKEUP_EN; writel_relaxed(config2, USB_GENCONFIG2); if ((test_bit(B_SESS_VLD, &motg->inputs) && !device_bus_suspend && !dcp && !prop_charger && !floated_charger) || test_bit(A_BUS_REQ, &motg->inputs)) { motg->ui_enabled = 1; enable_irq(motg->irq); return -EBUSY; } if (motg->pdata->phy_type == CI_45NM_INTEGRATED_PHY) { ulpi_read(phy, 0x14); if (pdata->otg_control == OTG_PHY_CONTROL) ulpi_write(phy, 0x01, 0x30); ulpi_write(phy, 0x08, 0x09); } if (motg->caps & ALLOW_VDD_MIN_WITH_RETENTION_DISABLED) { func_ctrl = ulpi_read(phy, ULPI_FUNC_CTRL); func_ctrl &= ~ULPI_FUNC_CTRL_OPMODE_MASK; func_ctrl |= ULPI_FUNC_CTRL_OPMODE_NONDRIVING; ulpi_write(phy, func_ctrl, ULPI_FUNC_CTRL); ulpi_write(phy, ULPI_IFC_CTRL_AUTORESUME, ULPI_CLR(ULPI_IFC_CTRL)); } portsc = readl_relaxed(USB_PORTSC); if (!(portsc & PORTSC_PHCD)) { writel_relaxed(portsc | PORTSC_PHCD, USB_PORTSC); while (cnt < PHY_SUSPEND_TIMEOUT_USEC) { if (readl_relaxed(USB_PORTSC) & PORTSC_PHCD) break; udelay(1); cnt++; } } if (cnt >= PHY_SUSPEND_TIMEOUT_USEC) { dev_err(phy->dev, "Unable to suspend PHY\n"); msm_otg_reset(phy); motg->ui_enabled = 1; enable_irq(motg->irq); return -ETIMEDOUT; } cmd_val = readl_relaxed(USB_USBCMD); if (host_bus_suspend || device_bus_suspend || (motg->pdata->otg_control == OTG_PHY_CONTROL)) cmd_val |= ASYNC_INTR_CTRL | ULPI_STP_CTRL; else cmd_val |= ULPI_STP_CTRL; writel_relaxed(cmd_val, USB_USBCMD); if (motg->caps & ALLOW_PHY_RETENTION && !device_bus_suspend && !dcp && (!host_bus_suspend || ((motg->caps & ALLOW_HOST_PHY_RETENTION) && (pdata->dpdm_pulldown_added || !(portsc & PORTSC_CCS))))) { phy_ctrl_val = readl_relaxed(USB_PHY_CTRL); if (motg->pdata->otg_control == OTG_PHY_CONTROL) { if ((motg->pdata->mode == USB_OTG) || (motg->pdata->mode == USB_HOST)) phy_ctrl_val |= (PHY_IDHV_INTEN | PHY_OTGSESSVLDHV_INTEN); else phy_ctrl_val |= PHY_OTGSESSVLDHV_INTEN; } if (host_bus_suspend) phy_ctrl_val |= PHY_CLAMP_DPDMSE_EN; if (!(motg->caps & ALLOW_VDD_MIN_WITH_RETENTION_DISABLED)) { writel_relaxed(phy_ctrl_val & ~PHY_RETEN, USB_PHY_CTRL); motg->lpm_flags |= PHY_RETENTIONED; } else { writel_relaxed(phy_ctrl_val, USB_PHY_CTRL); } } mb(); if (!(phy->state == OTG_STATE_B_PERIPHERAL && test_bit(A_BUS_SUSPEND, &motg->inputs)) || !motg->pdata->core_clk_always_on_workaround) { clk_disable_unprepare(motg->pclk); clk_disable_unprepare(motg->core_clk); motg->lpm_flags |= CLOCKS_DOWN; } if (!host_bus_suspend || ((motg->caps & ALLOW_HOST_PHY_RETENTION) && (pdata->dpdm_pulldown_added || !(portsc & PORTSC_CCS)))) { if (!IS_ERR(motg->xo_clk)) { clk_disable_unprepare(motg->xo_clk); motg->lpm_flags |= XO_SHUTDOWN; } else { ret = msm_xo_mode_vote(motg->xo_handle, MSM_XO_MODE_OFF); if (ret) dev_err(phy->dev, "%s fail to devote XO %d\n", __func__, ret); else motg->lpm_flags |= XO_SHUTDOWN; } } if (motg->caps & ALLOW_PHY_POWER_COLLAPSE && !host_bus_suspend && !dcp) { msm_hsusb_ldo_enable(motg, USB_PHY_REG_OFF); motg->lpm_flags |= PHY_PWR_COLLAPSED; } else if (motg->caps & ALLOW_PHY_REGULATORS_LPM && !host_bus_suspend && !device_bus_suspend && !dcp) { msm_hsusb_ldo_enable(motg, USB_PHY_REG_LPM_ON); motg->lpm_flags |= PHY_REGULATORS_LPM; } if (motg->lpm_flags & PHY_RETENTIONED || (motg->caps & ALLOW_VDD_MIN_WITH_RETENTION_DISABLED)) { msm_hsusb_config_vddcx(0); msm_hsusb_mhl_switch_enable(motg, 0); } if (device_may_wakeup(phy->dev)) { if (motg->async_irq) enable_irq_wake(motg->async_irq); else enable_irq_wake(motg->irq); if (motg->pdata->pmic_id_irq) enable_irq_wake(motg->pdata->pmic_id_irq); if (pdata->otg_control == OTG_PHY_CONTROL && pdata->mpm_otgsessvld_int) msm_mpm_set_pin_wake(pdata->mpm_otgsessvld_int, 1); if (host_bus_suspend && pdata->mpm_dpshv_int) msm_mpm_set_pin_wake(pdata->mpm_dpshv_int, 1); if (host_bus_suspend && pdata->mpm_dmshv_int) msm_mpm_set_pin_wake(pdata->mpm_dmshv_int, 1); } if (bus) clear_bit(HCD_FLAG_HW_ACCESSIBLE, &(bus_to_hcd(bus))->flags); msm_otg_bus_vote(motg, USB_NO_PERF_VOTE); motg->host_bus_suspend = host_bus_suspend; atomic_set(&motg->in_lpm, 1); if (motg->async_irq) enable_irq(motg->async_irq); if (device_bus_suspend || host_bus_suspend || !motg->async_irq) { motg->ui_enabled = 1; enable_irq(motg->irq); } wake_unlock(&motg->wlock); dev_info(phy->dev, "USB in low power mode\n"); return 0; } static int msm_otg_resume(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; struct usb_bus *bus = phy->otg->host; struct msm_otg_platform_data *pdata = motg->pdata; int cnt = 0; unsigned temp; u32 phy_ctrl_val = 0; unsigned ret; u32 func_ctrl; if (!atomic_read(&motg->in_lpm)) return 0; USBH_INFO("%s\n", __func__); if (motg->pdata->delay_lpm_hndshk_on_disconnect) msm_bam_notify_lpm_resume(); if (motg->ui_enabled) { motg->ui_enabled = 0; disable_irq(motg->irq); } wake_lock(&motg->wlock); msm_otg_bus_vote(motg, USB_MIN_PERF_VOTE); if (motg->lpm_flags & XO_SHUTDOWN) { if (!IS_ERR(motg->xo_clk)) { clk_prepare_enable(motg->xo_clk); } else { ret = msm_xo_mode_vote(motg->xo_handle, MSM_XO_MODE_ON); if (ret) dev_err(phy->dev, "%s fail to vote for XO %d\n", __func__, ret); } motg->lpm_flags &= ~XO_SHUTDOWN; } if (motg->lpm_flags & CLOCKS_DOWN) { clk_prepare_enable(motg->core_clk); clk_prepare_enable(motg->pclk); motg->lpm_flags &= ~CLOCKS_DOWN; } if (motg->lpm_flags & PHY_PWR_COLLAPSED) { msm_hsusb_ldo_enable(motg, USB_PHY_REG_ON); motg->lpm_flags &= ~PHY_PWR_COLLAPSED; } else if (motg->lpm_flags & PHY_REGULATORS_LPM) { msm_hsusb_ldo_enable(motg, USB_PHY_REG_LPM_OFF); motg->lpm_flags &= ~PHY_REGULATORS_LPM; } if (motg->lpm_flags & PHY_RETENTIONED || (motg->caps & ALLOW_VDD_MIN_WITH_RETENTION_DISABLED)) { msm_hsusb_mhl_switch_enable(motg, 1); msm_hsusb_config_vddcx(1); phy_ctrl_val = readl_relaxed(USB_PHY_CTRL); phy_ctrl_val |= PHY_RETEN; if (motg->pdata->otg_control == OTG_PHY_CONTROL) phy_ctrl_val &= ~(PHY_IDHV_INTEN | PHY_OTGSESSVLDHV_INTEN); phy_ctrl_val &= ~(PHY_CLAMP_DPDMSE_EN); writel_relaxed(phy_ctrl_val, USB_PHY_CTRL); motg->lpm_flags &= ~PHY_RETENTIONED; } temp = readl(USB_USBCMD); temp &= ~ASYNC_INTR_CTRL; temp &= ~ULPI_STP_CTRL; writel(temp, USB_USBCMD); if (!(readl(USB_PORTSC) & PORTSC_PHCD)) goto skip_phy_resume; writel(readl(USB_PORTSC) & ~PORTSC_PHCD, USB_PORTSC); while (cnt < PHY_RESUME_TIMEOUT_USEC) { if (!(readl(USB_PORTSC) & PORTSC_PHCD)) break; udelay(1); cnt++; } if (cnt >= PHY_RESUME_TIMEOUT_USEC) { USBH_ERR("Unable to resume USB." "Re-plugin the cable\n"); msm_otg_reset(phy); } skip_phy_resume: if (motg->caps & ALLOW_VDD_MIN_WITH_RETENTION_DISABLED) { func_ctrl = ulpi_read(phy, ULPI_FUNC_CTRL); func_ctrl &= ~ULPI_FUNC_CTRL_OPMODE_MASK; func_ctrl |= ULPI_FUNC_CTRL_OPMODE_NORMAL; ulpi_write(phy, func_ctrl, ULPI_FUNC_CTRL); } if (device_may_wakeup(phy->dev)) { if (motg->async_irq) disable_irq_wake(motg->async_irq); else disable_irq_wake(motg->irq); if (motg->pdata->pmic_id_irq) disable_irq_wake(motg->pdata->pmic_id_irq); if (pdata->otg_control == OTG_PHY_CONTROL && pdata->mpm_otgsessvld_int) msm_mpm_set_pin_wake(pdata->mpm_otgsessvld_int, 0); if (motg->host_bus_suspend && pdata->mpm_dpshv_int) msm_mpm_set_pin_wake(pdata->mpm_dpshv_int, 0); if (motg->host_bus_suspend && pdata->mpm_dmshv_int) msm_mpm_set_pin_wake(pdata->mpm_dmshv_int, 0); } if (bus) set_bit(HCD_FLAG_HW_ACCESSIBLE, &(bus_to_hcd(bus))->flags); atomic_set(&motg->in_lpm, 0); if (motg->async_int) { enable_irq(motg->async_int); motg->async_int = 0; } motg->ui_enabled = 1; enable_irq(motg->irq); if (motg->async_irq) disable_irq(motg->async_irq); dev_info(phy->dev, "USB exited from low power mode\n"); return 0; } #endif static void msm_otg_notify_host_mode(struct msm_otg *motg, bool host_mode) { if (!psy) { pr_err("No USB power supply registered!\n"); return; } if (legacy_power_supply) { if (host_mode) { power_supply_set_scope(psy, POWER_SUPPLY_SCOPE_SYSTEM); } else { power_supply_set_scope(psy, POWER_SUPPLY_SCOPE_DEVICE); if (test_bit(ID_A, &motg->inputs)) msleep(50); } } else { motg->host_mode = host_mode; power_supply_changed(psy); } } static int msm_otg_notify_chg_type(struct msm_otg *motg) { static int charger_type; if (charger_type == motg->chg_type) return 0; if (motg->chg_type == USB_SDP_CHARGER) charger_type = POWER_SUPPLY_TYPE_USB; else if (motg->chg_type == USB_CDP_CHARGER) charger_type = POWER_SUPPLY_TYPE_USB_CDP; else if (motg->chg_type == USB_DCP_CHARGER || motg->chg_type == USB_PROPRIETARY_CHARGER || motg->chg_type == USB_FLOATED_CHARGER) charger_type = POWER_SUPPLY_TYPE_USB_DCP; else if ((motg->chg_type == USB_ACA_DOCK_CHARGER || motg->chg_type == USB_ACA_A_CHARGER || motg->chg_type == USB_ACA_B_CHARGER || motg->chg_type == USB_ACA_C_CHARGER)) charger_type = POWER_SUPPLY_TYPE_USB_ACA; else charger_type = POWER_SUPPLY_TYPE_UNKNOWN; if (!psy) { pr_err("No USB power supply registered!\n"); return -EINVAL; } pr_debug("setting usb power supply type %d\n", charger_type); power_supply_set_supply_type(psy, charger_type); return 0; } static int msm_otg_notify_power_supply(struct msm_otg *motg, unsigned mA) { if (!psy) { dev_dbg(motg->phy.dev, "no usb power supply registered\n"); goto psy_error; } if (motg->cur_power == 0 && mA > 2) { if (power_supply_set_online(psy, true)) goto psy_error; if (power_supply_set_current_limit(psy, 1000*mA)) goto psy_error; } else if (motg->cur_power > 0 && (mA == 0 || mA == 2)) { if (power_supply_set_online(psy, false)) goto psy_error; if (power_supply_set_current_limit(psy, 0)) goto psy_error; } else { if (power_supply_set_online(psy, true)) goto psy_error; if (power_supply_set_current_limit(psy, 1000*mA)) goto psy_error; } power_supply_changed(psy); return 0; psy_error: dev_dbg(motg->phy.dev, "power supply error when setting property\n"); return -ENXIO; } static void msm_otg_notify_charger(struct msm_otg *motg, unsigned mA) { struct usb_gadget *g = motg->phy.otg->gadget; if (g && g->is_a_peripheral) return; if ((motg->chg_type == USB_ACA_DOCK_CHARGER || motg->chg_type == USB_ACA_A_CHARGER || motg->chg_type == USB_ACA_B_CHARGER || motg->chg_type == USB_ACA_C_CHARGER) && mA > IDEV_ACA_CHG_LIMIT) mA = IDEV_ACA_CHG_LIMIT; if (msm_otg_notify_chg_type(motg)) dev_err(motg->phy.dev, "Failed notifying %d charger type to PMIC\n", motg->chg_type); if (motg->cur_power == mA) return; dev_info(motg->phy.dev, "Avail curr from USB = %u\n", mA); if (msm_otg_notify_power_supply(motg, mA)) pm8921_charger_vbus_draw(mA); motg->cur_power = mA; } static void msm_otg_notify_usb_attached(struct usb_phy *phy) { struct msm_otg *motg = the_msm_otg; if (motg->connect_type != CONNECT_TYPE_USB) { motg->connect_type = CONNECT_TYPE_USB; queue_work(motg->usb_wq, &motg->notifier_work); } } static int msm_otg_set_power(struct usb_phy *phy, unsigned mA) { struct msm_otg *motg = container_of(phy, struct msm_otg, phy); if (motg->chg_type == USB_SDP_CHARGER) msm_otg_notify_charger(motg, mA); return 0; } static void msm_otg_start_host(struct usb_otg *otg, int on) { struct msm_otg *motg = container_of(otg->phy, struct msm_otg, phy); struct msm_otg_platform_data *pdata = motg->pdata; struct usb_hcd *hcd; if (!otg->host) return; hcd = bus_to_hcd(otg->host); if (on) { dev_dbg(otg->phy->dev, "host on\n"); if (pdata->otg_control == OTG_PHY_CONTROL) ulpi_write(otg->phy, OTG_COMP_DISABLE, ULPI_SET(ULPI_PWR_CLK_MNG_REG)); if (pdata->setup_gpio) pdata->setup_gpio(OTG_STATE_A_HOST); usb_add_hcd(hcd, hcd->irq, IRQF_SHARED); } else { dev_dbg(otg->phy->dev, "host off\n"); usb_remove_hcd(hcd); writel_relaxed(0x80000000, USB_PORTSC); if (pdata->setup_gpio) pdata->setup_gpio(OTG_STATE_UNDEFINED); if (pdata->otg_control == OTG_PHY_CONTROL) ulpi_write(otg->phy, OTG_COMP_DISABLE, ULPI_CLR(ULPI_PWR_CLK_MNG_REG)); } } static int msm_otg_usbdev_notify(struct notifier_block *self, unsigned long action, void *priv) { struct msm_otg *motg = container_of(self, struct msm_otg, usbdev_nb); struct usb_otg *otg = motg->phy.otg; struct usb_device *udev = priv; if (action == USB_BUS_ADD || action == USB_BUS_REMOVE) goto out; if (udev->bus != otg->host) goto out; if (!udev->parent || udev->parent->parent || motg->chg_type == USB_ACA_DOCK_CHARGER) goto out; switch (action) { case USB_DEVICE_ADD: if (aca_enabled()) usb_disable_autosuspend(udev); if (otg->phy->state == OTG_STATE_A_WAIT_BCON) { pr_debug("B_CONN set\n"); set_bit(B_CONN, &motg->inputs); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_HOST; if (udev->quirks & USB_QUIRK_OTG_PET) msm_otg_start_timer(motg, TA_TST_MAINT, A_TST_MAINT); } case USB_DEVICE_CONFIG: if (udev->actconfig) motg->mA_port = udev->actconfig->desc.bMaxPower * 2; else motg->mA_port = IUNIT; if (otg->phy->state == OTG_STATE_B_HOST) msm_otg_del_timer(motg); break; case USB_DEVICE_REMOVE: if ((otg->phy->state == OTG_STATE_A_HOST) || (otg->phy->state == OTG_STATE_A_SUSPEND)) { pr_debug("B_CONN clear\n"); clear_bit(B_CONN, &motg->inputs); if (udev->bus->otg_vbus_off) { udev->bus->otg_vbus_off = 0; set_bit(A_BUS_DROP, &motg->inputs); } queue_work(system_nrt_wq, &motg->sm_work); } default: break; } if (test_bit(ID_A, &motg->inputs)) msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX - motg->mA_port); out: return NOTIFY_OK; } static void msm_hsusb_vbus_power(struct msm_otg *motg, bool on) { int ret; static bool vbus_is_on; if (vbus_is_on == on) return; if (motg->pdata->vbus_power) { ret = motg->pdata->vbus_power(on); if (!ret) vbus_is_on = on; return; } if (!vbus_otg) { pr_err("vbus_otg is NULL."); return; } if (on) { msm_otg_notify_host_mode(motg, on); ret = regulator_enable(vbus_otg); if (ret) { pr_err("unable to enable vbus_otg\n"); return; } vbus_is_on = true; } else { ret = regulator_disable(vbus_otg); if (ret) { pr_err("unable to disable vbus_otg\n"); return; } msm_otg_notify_host_mode(motg, on); vbus_is_on = false; } if (on) { motg->connect_type = CONNECT_TYPE_INTERNAL; queue_work(motg->usb_wq, &motg->notifier_work); } else { motg->connect_type = CONNECT_TYPE_CLEAR; queue_work(motg->usb_wq, &motg->notifier_work); } } static int msm_otg_set_host(struct usb_otg *otg, struct usb_bus *host) { struct msm_otg *motg = container_of(otg->phy, struct msm_otg, phy); struct usb_hcd *hcd; if (motg->pdata->mode == USB_PERIPHERAL) { USBH_INFO("Host mode is not supported\n"); return -ENODEV; } if (!motg->pdata->vbus_power && host) { vbus_otg = devm_regulator_get(motg->phy.dev, "vbus_otg"); if (IS_ERR(vbus_otg)) { pr_err("Unable to get vbus_otg\n"); return PTR_ERR(vbus_otg); } } if (!host) { USB_WARNING("%s: no host\n", __func__); if (otg->phy->state == OTG_STATE_A_HOST) { pm_runtime_get_sync(otg->phy->dev); usb_unregister_notify(&motg->usbdev_nb); msm_otg_start_host(otg, 0); msm_hsusb_vbus_power(motg, 0); otg->host = NULL; otg->phy->state = OTG_STATE_UNDEFINED; queue_work(system_nrt_wq, &motg->sm_work); } else { otg->host = NULL; } return 0; } hcd = bus_to_hcd(host); hcd->power_budget = motg->pdata->power_budget; #ifdef CONFIG_USB_OTG host->otg_port = 1; #endif motg->usbdev_nb.notifier_call = msm_otg_usbdev_notify; usb_register_notify(&motg->usbdev_nb); otg->host = host; dev_dbg(otg->phy->dev, "host driver registered w/ tranceiver\n"); if (motg->pdata->mode == USB_HOST || otg->gadget) { pm_runtime_get_sync(otg->phy->dev); queue_work(system_nrt_wq, &motg->sm_work); } return 0; } static void msm_otg_start_peripheral(struct usb_otg *otg, int on) { struct msm_otg *motg = container_of(otg->phy, struct msm_otg, phy); struct msm_otg_platform_data *pdata = motg->pdata; if (!otg->gadget) return; if (on) { dev_dbg(otg->phy->dev, "gadget on\n"); if (pdata->setup_gpio) pdata->setup_gpio(OTG_STATE_B_PERIPHERAL); if (debug_bus_voting_enabled) msm_otg_bus_vote(motg, USB_MAX_PERF_VOTE); usb_gadget_vbus_connect(otg->gadget); } else { dev_dbg(otg->phy->dev, "gadget off\n"); usb_gadget_vbus_disconnect(otg->gadget); msm_otg_bus_vote(motg, USB_MIN_PERF_VOTE); if (pdata->setup_gpio) pdata->setup_gpio(OTG_STATE_UNDEFINED); } } static void msm_otg_notify_usb_disabled(void) { struct msm_otg *motg = the_msm_otg; USBH_INFO("%s\n", __func__); queue_work(system_nrt_wq, &motg->sm_work); } static int msm_otg_set_peripheral(struct usb_otg *otg, struct usb_gadget *gadget) { struct msm_otg *motg = container_of(otg->phy, struct msm_otg, phy); if (motg->pdata->mode == USB_HOST) { USBH_ERR("Peripheral mode is not supported\n"); return -ENODEV; } if (!gadget) { USB_WARNING("%s: no gadget\n", __func__); if (otg->phy->state == OTG_STATE_B_PERIPHERAL) { pm_runtime_get_sync(otg->phy->dev); msm_otg_start_peripheral(otg, 0); otg->gadget = NULL; otg->phy->state = OTG_STATE_UNDEFINED; queue_work(system_nrt_wq, &motg->sm_work); } else { otg->gadget = NULL; } return 0; } otg->gadget = gadget; USBH_DEBUG("peripheral driver registered w/ tranceiver\n"); if (motg->pdata->mode == USB_PERIPHERAL || otg->host) { USB_WARNING("peripheral only, otg->host exist\n"); pm_runtime_get_sync(otg->phy->dev); queue_work(system_nrt_wq, &motg->sm_work); } return 0; } static bool msm_otg_read_pmic_id_state(struct msm_otg *motg) { unsigned long flags; int id; if (!motg->pdata->pmic_id_irq) return -ENODEV; local_irq_save(flags); id = irq_read_line(motg->pdata->pmic_id_irq); local_irq_restore(flags); return !!id; } static int msm_otg_mhl_register_callback(struct msm_otg *motg, void (*callback)(int on)) { struct usb_phy *phy = &motg->phy; int ret; if (!motg->pdata->mhl_enable) { dev_dbg(phy->dev, "MHL feature not enabled\n"); return -ENODEV; } if (motg->pdata->otg_control != OTG_PMIC_CONTROL || !motg->pdata->pmic_id_irq) { dev_dbg(phy->dev, "MHL can not be supported without PMIC Id\n"); return -ENODEV; } if (!motg->pdata->mhl_dev_name) { dev_dbg(phy->dev, "MHL device name does not exist.\n"); return -ENODEV; } if (callback) ret = mhl_register_callback(motg->pdata->mhl_dev_name, callback); else ret = mhl_unregister_callback(motg->pdata->mhl_dev_name); if (ret) dev_dbg(phy->dev, "mhl_register_callback(%s) return error=%d\n", motg->pdata->mhl_dev_name, ret); else motg->mhl_enabled = true; return ret; } static void msm_otg_mhl_notify_online(int on) { struct msm_otg *motg = the_msm_otg; struct usb_phy *phy = &motg->phy; bool queue = false; dev_dbg(phy->dev, "notify MHL %s%s\n", on ? "" : "dis", "connected"); if (on) { set_bit(MHL, &motg->inputs); } else { clear_bit(MHL, &motg->inputs); queue = true; } if (queue && phy->state != OTG_STATE_UNDEFINED) schedule_work(&motg->sm_work); } static bool msm_otg_is_mhl(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; int is_mhl, ret; ret = mhl_device_discovery(motg->pdata->mhl_dev_name, &is_mhl); if (ret || is_mhl != MHL_DISCOVERY_RESULT_MHL) { clear_bit(MHL, &motg->inputs); dev_dbg(phy->dev, "MHL device not found\n"); return false; } set_bit(MHL, &motg->inputs); dev_dbg(phy->dev, "MHL device found\n"); return true; } static bool msm_chg_mhl_detect(struct msm_otg *motg) { bool ret, id; return false; if (!motg->mhl_enabled) return false; id = msm_otg_read_pmic_id_state(motg); if (id) return false; mhl_det_in_progress = true; ret = msm_otg_is_mhl(motg); mhl_det_in_progress = false; return ret; } static void msm_otg_chg_check_timer_func(unsigned long data) { struct msm_otg *motg = (struct msm_otg *) data; struct usb_otg *otg = motg->phy.otg; if (atomic_read(&motg->in_lpm) || !test_bit(B_SESS_VLD, &motg->inputs) || otg->phy->state != OTG_STATE_B_PERIPHERAL || otg->gadget->speed != USB_SPEED_UNKNOWN) { dev_dbg(otg->phy->dev, "Nothing to do in chg_check_timer\n"); return; } USBH_INFO("%s: count = %d, connect_type = %d\n", __func__, motg->chg_check_count, motg->connect_type); if ((readl_relaxed(USB_PORTSC) & PORTSC_LS) == PORTSC_LS ||cable_get_accessory_type() == DOCK_STATE_CAR) { USBH_INFO( "DCP is detected as SDP\n"); set_bit(B_FALSE_SDP, &motg->inputs); queue_work(system_nrt_wq, &motg->sm_work); if (motg->connect_type != CONNECT_TYPE_AC) { motg->connect_type = CONNECT_TYPE_AC; queue_work(motg->usb_wq, &motg->notifier_work); } } else { if (motg->chg_check_count < RETRY_CHECK_TIMES) { motg->chg_check_count++; mod_timer(&motg->chg_check_timer, CHG_RECHECK_DELAY); } } } static bool msm_chg_aca_detect(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 int_sts; bool ret = false; if (!aca_enabled()) goto out; if (motg->pdata->phy_type == CI_45NM_INTEGRATED_PHY) goto out; int_sts = ulpi_read(phy, 0x87); switch (int_sts & 0x1C) { case 0x08: if (!test_and_set_bit(ID_A, &motg->inputs)) { dev_dbg(phy->dev, "ID_A\n"); motg->chg_type = USB_ACA_A_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; clear_bit(ID_B, &motg->inputs); clear_bit(ID_C, &motg->inputs); set_bit(ID, &motg->inputs); ret = true; } break; case 0x0C: if (!test_and_set_bit(ID_B, &motg->inputs)) { USBH_DEBUG("ID_B\n"); motg->chg_type = USB_ACA_B_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; clear_bit(ID_A, &motg->inputs); clear_bit(ID_C, &motg->inputs); set_bit(ID, &motg->inputs); ret = true; } break; case 0x10: if (!test_and_set_bit(ID_C, &motg->inputs)) { USBH_DEBUG("ID_C\n"); motg->chg_type = USB_ACA_C_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; clear_bit(ID_A, &motg->inputs); clear_bit(ID_B, &motg->inputs); set_bit(ID, &motg->inputs); ret = true; } break; case 0x04: if (test_and_clear_bit(ID, &motg->inputs)) { dev_dbg(phy->dev, "ID_GND\n"); motg->chg_type = USB_INVALID_CHARGER; motg->chg_state = USB_CHG_STATE_UNDEFINED; clear_bit(ID_A, &motg->inputs); clear_bit(ID_B, &motg->inputs); clear_bit(ID_C, &motg->inputs); ret = true; } break; default: ret = test_and_clear_bit(ID_A, &motg->inputs) | test_and_clear_bit(ID_B, &motg->inputs) | test_and_clear_bit(ID_C, &motg->inputs) | !test_and_set_bit(ID, &motg->inputs); if (ret) { USBH_DEBUG("ID A/B/C/GND is no more\n"); motg->chg_type = USB_INVALID_CHARGER; motg->chg_state = USB_CHG_STATE_UNDEFINED; } } out: return ret; } static void msm_chg_enable_aca_det(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; if (!aca_enabled()) return; switch (motg->pdata->phy_type) { case SNPS_28NM_INTEGRATED_PHY: writel_relaxed(readl_relaxed(USB_OTGSC) & ~(OTGSC_IDPU | OTGSC_IDIE), USB_OTGSC); ulpi_write(phy, 0x01, 0x0C); ulpi_write(phy, 0x10, 0x0F); ulpi_write(phy, 0x10, 0x12); pm8xxx_usb_id_pullup(0); ulpi_write(phy, 0x20, 0x85); aca_id_turned_on = true; break; default: break; } } static void msm_chg_enable_aca_intr(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; if (!aca_enabled()) return; switch (motg->pdata->phy_type) { case SNPS_28NM_INTEGRATED_PHY: ulpi_write(phy, 0x01, 0x94); break; default: break; } } static void msm_chg_disable_aca_intr(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; if (!aca_enabled()) return; switch (motg->pdata->phy_type) { case SNPS_28NM_INTEGRATED_PHY: ulpi_write(phy, 0x01, 0x95); break; default: break; } } static bool msm_chg_check_aca_intr(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; bool ret = false; if (!aca_enabled()) return ret; switch (motg->pdata->phy_type) { case SNPS_28NM_INTEGRATED_PHY: if (ulpi_read(phy, 0x91) & 1) { USBH_DEBUG("RID change\n"); ulpi_write(phy, 0x01, 0x92); ret = msm_chg_aca_detect(motg); } default: break; } return ret; } static void msm_otg_id_timer_func(unsigned long data) { struct msm_otg *motg = (struct msm_otg *) data; if (!aca_enabled()) return; if (atomic_read(&motg->in_lpm)) { dev_dbg(motg->phy.dev, "timer: in lpm\n"); return; } if (motg->phy.state == OTG_STATE_A_SUSPEND) goto out; if (msm_chg_check_aca_intr(motg)) { dev_dbg(motg->phy.dev, "timer: aca work\n"); queue_work(system_nrt_wq, &motg->sm_work); } out: if (!test_bit(ID, &motg->inputs) || test_bit(ID_A, &motg->inputs)) mod_timer(&motg->id_timer, ID_TIMER_FREQ); } static bool msm_chg_check_secondary_det(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 chg_det; bool ret = false; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); ret = chg_det & (1 << 4); break; case SNPS_28NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x87); ret = chg_det & 1; break; default: break; } return ret; } static void msm_chg_enable_secondary_det(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 chg_det; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); chg_det |= ~(1 << 1); ulpi_write(phy, chg_det, 0x34); udelay(20); chg_det &= ~(1 << 3); ulpi_write(phy, chg_det, 0x34); chg_det &= ~(1 << 2); ulpi_write(phy, chg_det, 0x34); chg_det &= ~(1 << 1); ulpi_write(phy, chg_det, 0x34); udelay(20); chg_det &= ~(1 << 0); ulpi_write(phy, chg_det, 0x34); break; case SNPS_28NM_INTEGRATED_PHY: ulpi_write(phy, 0x8, 0x85); ulpi_write(phy, 0x2, 0x85); ulpi_write(phy, 0x1, 0x85); break; default: break; } } static bool msm_chg_check_primary_det(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 chg_det; bool ret = false; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); ret = chg_det & (1 << 4); break; case SNPS_28NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x87); ret = chg_det & 1; ulpi_write(phy, 0x3, 0x86); msleep(20); break; default: break; } return ret; } static void msm_chg_enable_primary_det(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 chg_det; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); chg_det &= ~(1 << 0); ulpi_write(phy, chg_det, 0x34); break; case SNPS_28NM_INTEGRATED_PHY: ulpi_write(phy, 0x2, 0x85); ulpi_write(phy, 0x1, 0x85); break; default: break; } } static bool msm_chg_check_dcd(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 line_state; bool ret = false; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: line_state = ulpi_read(phy, 0x15); ret = !(line_state & 1); break; case SNPS_28NM_INTEGRATED_PHY: line_state = ulpi_read(phy, 0x87); ret = line_state & 2; break; default: break; } return ret; } static void msm_chg_disable_dcd(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 chg_det; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); chg_det &= ~(1 << 5); ulpi_write(phy, chg_det, 0x34); break; case SNPS_28NM_INTEGRATED_PHY: ulpi_write(phy, 0x10, 0x86); break; default: break; } } static void msm_chg_enable_dcd(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 chg_det; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); chg_det |= (1 << 5); ulpi_write(phy, chg_det, 0x34); break; case SNPS_28NM_INTEGRATED_PHY: ulpi_write(phy, 0x10, 0x85); break; default: break; } } static void msm_chg_block_on(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 func_ctrl, chg_det; func_ctrl = ulpi_read(phy, ULPI_FUNC_CTRL); func_ctrl &= ~ULPI_FUNC_CTRL_OPMODE_MASK; func_ctrl |= ULPI_FUNC_CTRL_OPMODE_NONDRIVING; ulpi_write(phy, func_ctrl, ULPI_FUNC_CTRL); switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); chg_det &= ~(1 << 3); ulpi_write(phy, chg_det, 0x34); chg_det &= ~(1 << 1); ulpi_write(phy, chg_det, 0x34); udelay(20); break; case SNPS_28NM_INTEGRATED_PHY: ulpi_write(phy, 0x6, 0xC); ulpi_write(phy, 0x1F, 0x86); ulpi_write(phy, 0x1F, 0x92); ulpi_write(phy, 0x1F, 0x95); udelay(100); break; default: break; } } static void msm_chg_block_off(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 func_ctrl, chg_det; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); chg_det |= ~(1 << 1); ulpi_write(phy, chg_det, 0x34); break; case SNPS_28NM_INTEGRATED_PHY: ulpi_write(phy, 0x3F, 0x86); ulpi_write(phy, 0x1F, 0x92); ulpi_write(phy, 0x1F, 0x95); ulpi_write(phy, 0x6, 0xB); break; default: break; } func_ctrl = ulpi_read(phy, ULPI_FUNC_CTRL); func_ctrl &= ~ULPI_FUNC_CTRL_OPMODE_MASK; func_ctrl |= ULPI_FUNC_CTRL_OPMODE_NORMAL; ulpi_write(phy, func_ctrl, ULPI_FUNC_CTRL); } static const char *chg_to_string(enum usb_chg_type chg_type) { switch (chg_type) { case USB_SDP_CHARGER: return "USB_SDP_CHARGER"; case USB_DCP_CHARGER: return "USB_DCP_CHARGER"; case USB_CDP_CHARGER: return "USB_CDP_CHARGER"; case USB_ACA_A_CHARGER: return "USB_ACA_A_CHARGER"; case USB_ACA_B_CHARGER: return "USB_ACA_B_CHARGER"; case USB_ACA_C_CHARGER: return "USB_ACA_C_CHARGER"; case USB_ACA_DOCK_CHARGER: return "USB_ACA_DOCK_CHARGER"; case USB_PROPRIETARY_CHARGER: return "USB_PROPRIETARY_CHARGER"; case USB_FLOATED_CHARGER: return "USB_FLOATED_CHARGER"; default: return "INVALID_CHARGER"; } } #define MSM_CHG_DCD_TIMEOUT (750 * HZ/1000) #define MSM_CHG_DCD_POLL_TIME (50 * HZ/1000) #define MSM_CHG_PRIMARY_DET_TIME (50 * HZ/1000) #define MSM_CHG_SECONDARY_DET_TIME (50 * HZ/1000) static void msm_chg_detect_work(struct work_struct *w) { struct msm_otg *motg = container_of(w, struct msm_otg, chg_work.work); struct usb_phy *phy = &motg->phy; bool is_dcd = false, tmout, vout, is_aca; static bool dcd; u32 line_state, dm_vlgc; unsigned long delay; dev_dbg(phy->dev, "chg detection work\n"); if (test_bit(MHL, &motg->inputs)) { dev_dbg(phy->dev, "detected MHL, escape chg detection work\n"); return; } switch (motg->chg_state) { case USB_CHG_STATE_UNDEFINED: msm_chg_block_on(motg); msm_chg_enable_dcd(motg); msm_chg_enable_aca_det(motg); motg->chg_state = USB_CHG_STATE_WAIT_FOR_DCD; motg->dcd_time = 0; delay = MSM_CHG_DCD_POLL_TIME; break; case USB_CHG_STATE_WAIT_FOR_DCD: if (msm_chg_mhl_detect(motg)) { msm_chg_block_off(motg); motg->chg_state = USB_CHG_STATE_DETECTED; motg->chg_type = USB_INVALID_CHARGER; queue_work(system_nrt_wq, &motg->sm_work); return; } is_aca = msm_chg_aca_detect(motg); if (is_aca) { if (test_bit(ID_A, &motg->inputs)) { motg->chg_state = USB_CHG_STATE_WAIT_FOR_DCD; } else { delay = 0; break; } } is_dcd = msm_chg_check_dcd(motg); motg->dcd_time += MSM_CHG_DCD_POLL_TIME; tmout = motg->dcd_time >= MSM_CHG_DCD_TIMEOUT; if (is_dcd || tmout) { if (is_dcd) dcd = true; else dcd = false; msm_chg_disable_dcd(motg); msm_chg_enable_primary_det(motg); delay = MSM_CHG_PRIMARY_DET_TIME; motg->chg_state = USB_CHG_STATE_DCD_DONE; } else { delay = MSM_CHG_DCD_POLL_TIME; } break; case USB_CHG_STATE_DCD_DONE: vout = msm_chg_check_primary_det(motg); line_state = readl_relaxed(USB_PORTSC) & PORTSC_LS; dm_vlgc = line_state & PORTSC_LS_DM; if (vout && !dm_vlgc) { if (test_bit(ID_A, &motg->inputs)) { motg->chg_type = USB_ACA_DOCK_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; motg->connect_type = CONNECT_TYPE_UNKNOWN; delay = 0; break; } if (line_state) { motg->chg_type = USB_PROPRIETARY_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; motg->connect_type = CONNECT_TYPE_UNKNOWN; delay = 0; } else { msm_chg_enable_secondary_det(motg); delay = MSM_CHG_SECONDARY_DET_TIME; motg->chg_state = USB_CHG_STATE_PRIMARY_DONE; } } else { if (test_bit(ID_A, &motg->inputs)) { motg->chg_type = USB_ACA_A_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; motg->connect_type = CONNECT_TYPE_UNKNOWN; delay = 0; break; } if (line_state) { motg->chg_type = USB_PROPRIETARY_CHARGER; motg->connect_type = CONNECT_TYPE_AC; } else if (!dcd && floated_charger_enable) { motg->chg_type = USB_FLOATED_CHARGER; motg->connect_type = CONNECT_TYPE_UNKNOWN; } else { motg->chg_type = USB_SDP_CHARGER; motg->connect_type = CONNECT_TYPE_UNKNOWN; } motg->chg_state = USB_CHG_STATE_DETECTED; delay = 0; } break; case USB_CHG_STATE_PRIMARY_DONE: vout = msm_chg_check_secondary_det(motg); if (vout) motg->chg_type = USB_DCP_CHARGER; else motg->chg_type = USB_CDP_CHARGER; motg->connect_type = CONNECT_TYPE_AC; motg->chg_state = USB_CHG_STATE_SECONDARY_DONE; case USB_CHG_STATE_SECONDARY_DONE: motg->chg_state = USB_CHG_STATE_DETECTED; case USB_CHG_STATE_DETECTED: msm_otg_notify_chg_type(motg); msm_chg_block_off(motg); msm_chg_enable_aca_det(motg); udelay(100); msm_chg_enable_aca_intr(motg); USBH_INFO("chg_type = %s\n", chg_to_string(motg->chg_type)); queue_work(system_nrt_wq, &motg->sm_work); queue_work(motg->usb_wq, &motg->notifier_work); return; default: return; } queue_delayed_work(system_nrt_wq, &motg->chg_work, delay); } static void msm_otg_init_sm(struct msm_otg *motg) { struct msm_otg_platform_data *pdata = motg->pdata; u32 otgsc = readl(USB_OTGSC); switch (pdata->mode) { case USB_OTG: if (pdata->otg_control == OTG_USER_CONTROL) { if (pdata->default_mode == USB_HOST) { clear_bit(ID, &motg->inputs); } else if (pdata->default_mode == USB_PERIPHERAL) { set_bit(ID, &motg->inputs); set_bit(B_SESS_VLD, &motg->inputs); } else { set_bit(ID, &motg->inputs); clear_bit(B_SESS_VLD, &motg->inputs); } } else if (pdata->otg_control == OTG_PHY_CONTROL) { if (otgsc & OTGSC_ID) { set_bit(ID, &motg->inputs); } else { clear_bit(ID, &motg->inputs); set_bit(A_BUS_REQ, &motg->inputs); } if (otgsc & OTGSC_BSV) set_bit(B_SESS_VLD, &motg->inputs); else clear_bit(B_SESS_VLD, &motg->inputs); } else if (pdata->otg_control == OTG_PMIC_CONTROL) { if (cable_get_accessory_type() == DOCK_STATE_USB_HOST) clear_bit(ID, &motg->inputs); else set_bit(ID, &motg->inputs); wait_for_completion(&pmic_vbus_init); } break; case USB_HOST: clear_bit(ID, &motg->inputs); break; case USB_PERIPHERAL: set_bit(ID, &motg->inputs); if (pdata->otg_control == OTG_PHY_CONTROL) { if (otgsc & OTGSC_BSV) set_bit(B_SESS_VLD, &motg->inputs); else clear_bit(B_SESS_VLD, &motg->inputs); } else if (pdata->otg_control == OTG_PMIC_CONTROL) { wait_for_completion(&pmic_vbus_init); } break; default: break; } } static void msm_otg_wait_for_ext_chg_done(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; unsigned long t; if (motg->ext_chg_active) { pr_debug("before msm_otg ext chg wait\n"); t = wait_for_completion_timeout(&motg->ext_chg_wait, msecs_to_jiffies(3000)); if (!t) pr_err("msm_otg ext chg wait timeout\n"); else pr_debug("msm_otg ext chg wait done\n"); } if (motg->ext_chg_opened) { if (phy->flags & ENABLE_DP_MANUAL_PULLUP) { ulpi_write(phy, ULPI_MISC_A_VBUSVLDEXT | ULPI_MISC_A_VBUSVLDEXTSEL, ULPI_CLR(ULPI_MISC_A)); } ulpi_write(phy, 0x3F, 0x86); ulpi_write(phy, 0x6, 0xB); } } static void msm_otg_sm_work(struct work_struct *w) { struct msm_otg *motg = container_of(w, struct msm_otg, sm_work); struct usb_otg *otg = motg->phy.otg; bool work = 0, srp_reqd, dcp; USBH_INFO("%s: state:%s bit:0x%08x\n", __func__, otg_state_string(otg->phy->state), (unsigned) motg->inputs); mutex_lock(&smwork_sem); pm_runtime_resume(otg->phy->dev); pr_debug("%s work\n", otg_state_string(otg->phy->state)); switch (otg->phy->state) { case OTG_STATE_UNDEFINED: msm_otg_reset(otg->phy); msm_otg_init_sm(motg); if (!psy && legacy_power_supply) { psy = power_supply_get_by_name("usb"); if (!psy) pr_err("couldn't get usb power supply\n"); } otg->phy->state = OTG_STATE_B_IDLE; if (!test_bit(B_SESS_VLD, &motg->inputs) && test_bit(ID, &motg->inputs)) { pm_runtime_put_noidle(otg->phy->dev); pm_runtime_suspend(otg->phy->dev); break; } case OTG_STATE_B_IDLE: if (test_bit(MHL, &motg->inputs)) { pm_runtime_put_noidle(otg->phy->dev); pm_runtime_suspend(otg->phy->dev); } else if ((!test_bit(ID, &motg->inputs) || test_bit(ID_A, &motg->inputs)) && otg->host) { USBH_INFO("!id || id_a\n"); if (msm_chg_mhl_detect(motg)) { work = 1; break; } clear_bit(B_BUS_REQ, &motg->inputs); set_bit(A_BUS_REQ, &motg->inputs); otg->phy->state = OTG_STATE_A_IDLE; work = 1; } else if (test_bit(B_SESS_VLD, &motg->inputs)) { USBH_INFO("b_sess_vld\n"); switch (motg->chg_state) { case USB_CHG_STATE_UNDEFINED: msm_chg_detect_work(&motg->chg_work.work); break; case USB_CHG_STATE_DETECTED: switch (motg->chg_type) { case USB_DCP_CHARGER: ulpi_write(otg->phy, 0x2, 0x85); if (motg->ext_chg_opened) { init_completion( &motg->ext_chg_wait); motg->ext_chg_active = true; } case USB_PROPRIETARY_CHARGER: msm_otg_notify_charger(motg, IDEV_CHG_MAX); pm_runtime_put_sync(otg->phy->dev); break; case USB_FLOATED_CHARGER: msm_otg_notify_charger(motg, IDEV_CHG_MAX); pm_runtime_put_noidle(otg->phy->dev); pm_runtime_suspend(otg->phy->dev); break; case USB_ACA_B_CHARGER: msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); break; case USB_CDP_CHARGER: msm_otg_notify_charger(motg, IDEV_CHG_MAX); msm_otg_start_peripheral(otg, 1); otg->phy->state = OTG_STATE_B_PERIPHERAL; break; case USB_ACA_C_CHARGER: msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); msm_otg_start_peripheral(otg, 1); otg->phy->state = OTG_STATE_B_PERIPHERAL; break; case USB_SDP_CHARGER: msm_otg_start_peripheral(otg, 1); otg->phy->state = OTG_STATE_B_PERIPHERAL; motg->chg_check_count = 0; mod_timer(&motg->chg_check_timer, CHG_RECHECK_DELAY); break; default: break; } USBH_INFO("b_sess_vld, chg_state %d chg_type %d usb_disable %d\n",motg->chg_state ,motg->chg_type, msm_otg_usb_disable); break; default: break; } } else if (test_bit(B_BUS_REQ, &motg->inputs)) { USBH_INFO("b_sess_end && b_bus_req\n"); if (msm_otg_start_srp(otg) < 0) { clear_bit(B_BUS_REQ, &motg->inputs); work = 1; break; } otg->phy->state = OTG_STATE_B_SRP_INIT; msm_otg_start_timer(motg, TB_SRP_FAIL, B_SRP_FAIL); break; } else { pr_debug("chg_work cancel"); USBH_INFO("!b_sess_vld && id\n"); del_timer_sync(&motg->chg_check_timer); clear_bit(B_FALSE_SDP, &motg->inputs); clear_bit(A_BUS_REQ, &motg->inputs); cancel_delayed_work_sync(&motg->chg_work); dcp = (motg->chg_type == USB_DCP_CHARGER); motg->chg_state = USB_CHG_STATE_UNDEFINED; motg->chg_type = USB_INVALID_CHARGER; msm_otg_notify_charger(motg, 0); if (dcp) { msm_otg_wait_for_ext_chg_done(motg); ulpi_write(otg->phy, 0x2, 0x86); } msm_otg_reset(otg->phy); if (motg->connect_type != CONNECT_TYPE_NONE) { motg->connect_type = CONNECT_TYPE_NONE; queue_work(motg->usb_wq, &motg->notifier_work); } pm_runtime_put_noidle(otg->phy->dev); pm_runtime_mark_last_busy(otg->phy->dev); pm_runtime_autosuspend(otg->phy->dev); } break; case OTG_STATE_B_SRP_INIT: if (!test_bit(ID, &motg->inputs) || test_bit(ID_A, &motg->inputs) || test_bit(ID_C, &motg->inputs) || (test_bit(B_SESS_VLD, &motg->inputs) && !test_bit(ID_B, &motg->inputs))) { USBH_INFO("!id || id_a/c || b_sess_vld+!id_b\n"); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_B_IDLE; ulpi_write(otg->phy, 0x0, 0x98); work = 1; } else if (test_bit(B_SRP_FAIL, &motg->tmouts)) { USBH_INFO("b_srp_fail\n"); pr_info("A-device did not respond to SRP\n"); clear_bit(B_BUS_REQ, &motg->inputs); clear_bit(B_SRP_FAIL, &motg->tmouts); otg_send_event(OTG_EVENT_NO_RESP_FOR_SRP); ulpi_write(otg->phy, 0x0, 0x98); otg->phy->state = OTG_STATE_B_IDLE; motg->b_last_se0_sess = jiffies; work = 1; } break; case OTG_STATE_B_PERIPHERAL: if (test_bit(B_SESS_VLD, &motg->inputs) && test_bit(B_FALSE_SDP, &motg->inputs)) { pr_debug("B_FALSE_SDP\n"); msm_otg_start_peripheral(otg, 0); motg->chg_type = USB_DCP_CHARGER; clear_bit(B_FALSE_SDP, &motg->inputs); otg->phy->state = OTG_STATE_B_IDLE; work = 1; } else if (!test_bit(ID, &motg->inputs) || test_bit(ID_A, &motg->inputs) || test_bit(ID_B, &motg->inputs) || !test_bit(B_SESS_VLD, &motg->inputs)) { if (motg->connect_type != CONNECT_TYPE_NONE) { motg->connect_type = CONNECT_TYPE_NONE; queue_work(motg->usb_wq, &motg->notifier_work); } USBH_INFO("!id || id_a/b || !b_sess_vld\n"); motg->chg_state = USB_CHG_STATE_UNDEFINED; motg->chg_type = USB_INVALID_CHARGER; msm_otg_notify_charger(motg, 0); srp_reqd = otg->gadget->otg_srp_reqd; msm_otg_start_peripheral(otg, 0); if (test_bit(ID_B, &motg->inputs)) clear_bit(ID_B, &motg->inputs); clear_bit(B_BUS_REQ, &motg->inputs); otg->phy->state = OTG_STATE_B_IDLE; motg->b_last_se0_sess = jiffies; if (srp_reqd) msm_otg_start_timer(motg, TB_TST_SRP, B_TST_SRP); else work = 1; } else if (test_bit(B_BUS_REQ, &motg->inputs) && otg->gadget->b_hnp_enable && test_bit(A_BUS_SUSPEND, &motg->inputs)) { USBH_INFO("b_bus_req && b_hnp_en && a_bus_suspend\n"); msm_otg_start_timer(motg, TB_ASE0_BRST, B_ASE0_BRST); udelay(1000); msm_otg_start_peripheral(otg, 0); otg->phy->state = OTG_STATE_B_WAIT_ACON; otg->host->is_b_host = 1; msm_otg_start_host(otg, 1); } else if (test_bit(A_BUS_SUSPEND, &motg->inputs) && test_bit(B_SESS_VLD, &motg->inputs)) { pr_debug("a_bus_suspend && b_sess_vld\n"); if (motg->caps & ALLOW_LPM_ON_DEV_SUSPEND) { pm_runtime_put_noidle(otg->phy->dev); pm_runtime_suspend(otg->phy->dev); } } else if (test_bit(ID_C, &motg->inputs)) { USBH_INFO("id_c\n"); msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); } else if (test_bit(B_SESS_VLD, &motg->inputs) && msm_otg_usb_disable == 1) { USBH_INFO("b_sess_vld && htc_usb_disable = 1\n"); if (motg->connect_type == CONNECT_TYPE_UNKNOWN) del_timer_sync(&motg->chg_check_timer); msm_otg_start_peripheral(otg, 0); otg->phy->state = OTG_STATE_B_IDLE; } break; case OTG_STATE_B_WAIT_ACON: if (!test_bit(ID, &motg->inputs) || test_bit(ID_A, &motg->inputs) || test_bit(ID_B, &motg->inputs) || !test_bit(B_SESS_VLD, &motg->inputs)) { USBH_INFO("!id || id_a/b || !b_sess_vld\n"); msm_otg_del_timer(motg); msm_otg_start_host(otg, 0); otg->host->is_b_host = 0; clear_bit(B_BUS_REQ, &motg->inputs); clear_bit(A_BUS_SUSPEND, &motg->inputs); motg->b_last_se0_sess = jiffies; otg->phy->state = OTG_STATE_B_IDLE; msm_otg_reset(otg->phy); work = 1; } else if (test_bit(A_CONN, &motg->inputs)) { USBH_INFO("a_conn\n"); clear_bit(A_BUS_SUSPEND, &motg->inputs); otg->phy->state = OTG_STATE_B_HOST; msm_otg_start_timer(motg, TB_TST_CONFIG, B_TST_CONFIG); } else if (test_bit(B_ASE0_BRST, &motg->tmouts)) { USBH_INFO("b_ase0_brst_tmout\n"); pr_info("B HNP fail:No response from A device\n"); msm_otg_start_host(otg, 0); msm_otg_reset(otg->phy); otg->host->is_b_host = 0; clear_bit(B_ASE0_BRST, &motg->tmouts); clear_bit(A_BUS_SUSPEND, &motg->inputs); clear_bit(B_BUS_REQ, &motg->inputs); otg_send_event(OTG_EVENT_HNP_FAILED); otg->phy->state = OTG_STATE_B_IDLE; work = 1; } else if (test_bit(ID_C, &motg->inputs)) { msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); } break; case OTG_STATE_B_HOST: if (!test_bit(B_BUS_REQ, &motg->inputs) || !test_bit(A_CONN, &motg->inputs) || !test_bit(B_SESS_VLD, &motg->inputs)) { USBH_INFO("!b_bus_req || !a_conn || !b_sess_vld\n"); clear_bit(A_CONN, &motg->inputs); clear_bit(B_BUS_REQ, &motg->inputs); msm_otg_start_host(otg, 0); otg->host->is_b_host = 0; otg->phy->state = OTG_STATE_B_IDLE; msm_otg_reset(otg->phy); work = 1; } else if (test_bit(ID_C, &motg->inputs)) { msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); } break; case OTG_STATE_A_IDLE: otg->default_a = 1; if (test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) { USBH_INFO("id && !id_a\n"); otg->default_a = 0; clear_bit(A_BUS_DROP, &motg->inputs); otg->phy->state = OTG_STATE_B_IDLE; del_timer_sync(&motg->id_timer); msm_otg_link_reset(motg); msm_chg_enable_aca_intr(motg); msm_otg_notify_charger(motg, 0); work = 1; } else if (!test_bit(A_BUS_DROP, &motg->inputs) && (test_bit(A_SRP_DET, &motg->inputs) || test_bit(A_BUS_REQ, &motg->inputs))) { USBH_INFO("!a_bus_drop && (a_srp_det || a_bus_req)\n"); clear_bit(A_SRP_DET, &motg->inputs); writel_relaxed((readl_relaxed(USB_OTGSC) & ~OTGSC_INTSTS_MASK) & ~OTGSC_DPIE, USB_OTGSC); otg->phy->state = OTG_STATE_A_WAIT_VRISE; usleep_range(10000, 12000); if (test_bit(ID_A, &motg->inputs)) msm_otg_notify_charger(motg, 0); else msm_hsusb_vbus_power(motg, 1); msm_otg_start_timer(motg, TA_WAIT_VRISE, A_WAIT_VRISE); } else { USBH_INFO("No session requested\n"); clear_bit(A_BUS_DROP, &motg->inputs); if (test_bit(ID_A, &motg->inputs)) { msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); } else if (!test_bit(ID, &motg->inputs)) { msm_otg_notify_charger(motg, 0); writel_relaxed(0x13, USB_USBMODE); writel_relaxed((readl_relaxed(USB_OTGSC) & ~OTGSC_INTSTS_MASK) | OTGSC_DPIE, USB_OTGSC); mb(); } } break; case OTG_STATE_A_WAIT_VRISE: if ((test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) || test_bit(A_BUS_DROP, &motg->inputs) || test_bit(A_WAIT_VRISE, &motg->tmouts)) { USBH_INFO("id || a_bus_drop || a_wait_vrise_tmout\n"); clear_bit(A_BUS_REQ, &motg->inputs); msm_otg_del_timer(motg); msm_hsusb_vbus_power(motg, 0); otg->phy->state = OTG_STATE_A_WAIT_VFALL; msm_otg_start_timer(motg, TA_WAIT_VFALL, A_WAIT_VFALL); } else if (test_bit(A_VBUS_VLD, &motg->inputs)) { USBH_INFO("a_vbus_vld\n"); otg->phy->state = OTG_STATE_A_WAIT_BCON; if (TA_WAIT_BCON > 0) msm_otg_start_timer(motg, TA_WAIT_BCON, A_WAIT_BCON); clear_bit(B_SESS_VLD, &motg->inputs); msm_otg_start_host(otg, 1); msm_chg_enable_aca_det(motg); msm_chg_disable_aca_intr(motg); mod_timer(&motg->id_timer, ID_TIMER_FREQ); if (msm_chg_check_aca_intr(motg)) work = 1; } break; case OTG_STATE_A_WAIT_BCON: if ((test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) || test_bit(A_BUS_DROP, &motg->inputs) || test_bit(A_WAIT_BCON, &motg->tmouts)) { USBH_INFO("(id && id_a/b/c) || a_bus_drop ||" "a_wait_bcon_tmout\n"); if (test_bit(A_WAIT_BCON, &motg->tmouts)) { pr_info("Device No Response\n"); otg_send_event(OTG_EVENT_DEV_CONN_TMOUT); } msm_otg_del_timer(motg); clear_bit(A_BUS_REQ, &motg->inputs); clear_bit(B_CONN, &motg->inputs); msm_otg_start_host(otg, 0); if (test_bit(ID_A, &motg->inputs)) msm_otg_notify_charger(motg, IDEV_CHG_MIN); else msm_hsusb_vbus_power(motg, 0); otg->phy->state = OTG_STATE_A_WAIT_VFALL; msm_otg_start_timer(motg, TA_WAIT_VFALL, A_WAIT_VFALL); } else if (!test_bit(A_VBUS_VLD, &motg->inputs)) { USBH_INFO("!a_vbus_vld\n"); clear_bit(B_CONN, &motg->inputs); msm_otg_del_timer(motg); msm_otg_start_host(otg, 0); otg->phy->state = OTG_STATE_A_VBUS_ERR; msm_otg_reset(otg->phy); } else if (test_bit(ID_A, &motg->inputs)) { msm_hsusb_vbus_power(motg, 0); } else if (!test_bit(A_BUS_REQ, &motg->inputs)) { if (TA_WAIT_BCON < 0) pm_runtime_put_sync(otg->phy->dev); } else if (!test_bit(ID, &motg->inputs)) { msm_hsusb_vbus_power(motg, 1); } break; case OTG_STATE_A_HOST: if ((test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) || test_bit(A_BUS_DROP, &motg->inputs)) { USBH_INFO("id_a/b/c || a_bus_drop\n"); clear_bit(B_CONN, &motg->inputs); clear_bit(A_BUS_REQ, &motg->inputs); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_WAIT_VFALL; msm_otg_start_host(otg, 0); if (!test_bit(ID_A, &motg->inputs)) msm_hsusb_vbus_power(motg, 0); msm_otg_start_timer(motg, TA_WAIT_VFALL, A_WAIT_VFALL); } else if (!test_bit(A_VBUS_VLD, &motg->inputs)) { USBH_INFO("!a_vbus_vld\n"); clear_bit(B_CONN, &motg->inputs); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_VBUS_ERR; msm_otg_start_host(otg, 0); msm_otg_reset(otg->phy); } else if (!test_bit(A_BUS_REQ, &motg->inputs)) { USBH_INFO("!a_bus_req\n"); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_SUSPEND; if (otg->host->b_hnp_enable) msm_otg_start_timer(motg, TA_AIDL_BDIS, A_AIDL_BDIS); else pm_runtime_put_sync(otg->phy->dev); } else if (!test_bit(B_CONN, &motg->inputs)) { USBH_INFO("!b_conn\n"); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_WAIT_BCON; if (TA_WAIT_BCON > 0) msm_otg_start_timer(motg, TA_WAIT_BCON, A_WAIT_BCON); if (msm_chg_check_aca_intr(motg)) work = 1; } else if (test_bit(ID_A, &motg->inputs)) { msm_otg_del_timer(motg); msm_hsusb_vbus_power(motg, 0); if (motg->chg_type == USB_ACA_DOCK_CHARGER) msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); else msm_otg_notify_charger(motg, IDEV_CHG_MIN - motg->mA_port); } else if (!test_bit(ID, &motg->inputs)) { motg->chg_state = USB_CHG_STATE_UNDEFINED; motg->chg_type = USB_INVALID_CHARGER; msm_otg_notify_charger(motg, 0); msm_hsusb_vbus_power(motg, 1); } break; case OTG_STATE_A_SUSPEND: if ((test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) || test_bit(A_BUS_DROP, &motg->inputs) || test_bit(A_AIDL_BDIS, &motg->tmouts)) { USBH_INFO("id_a/b/c || a_bus_drop ||" "a_aidl_bdis_tmout\n"); msm_otg_del_timer(motg); clear_bit(B_CONN, &motg->inputs); otg->phy->state = OTG_STATE_A_WAIT_VFALL; msm_otg_start_host(otg, 0); msm_otg_reset(otg->phy); if (!test_bit(ID_A, &motg->inputs)) msm_hsusb_vbus_power(motg, 0); msm_otg_start_timer(motg, TA_WAIT_VFALL, A_WAIT_VFALL); } else if (!test_bit(A_VBUS_VLD, &motg->inputs)) { USBH_INFO("!a_vbus_vld\n"); msm_otg_del_timer(motg); clear_bit(B_CONN, &motg->inputs); otg->phy->state = OTG_STATE_A_VBUS_ERR; msm_otg_start_host(otg, 0); msm_otg_reset(otg->phy); } else if (!test_bit(B_CONN, &motg->inputs) && otg->host->b_hnp_enable) { USBH_INFO("!b_conn && b_hnp_enable"); otg->phy->state = OTG_STATE_A_PERIPHERAL; msm_otg_host_hnp_enable(otg, 1); otg->gadget->is_a_peripheral = 1; msm_otg_start_peripheral(otg, 1); } else if (!test_bit(B_CONN, &motg->inputs) && !otg->host->b_hnp_enable) { USBH_INFO("!b_conn && !b_hnp_enable"); set_bit(A_BUS_REQ, &motg->inputs); otg->phy->state = OTG_STATE_A_WAIT_BCON; if (TA_WAIT_BCON > 0) msm_otg_start_timer(motg, TA_WAIT_BCON, A_WAIT_BCON); } else if (test_bit(ID_A, &motg->inputs)) { msm_hsusb_vbus_power(motg, 0); msm_otg_notify_charger(motg, IDEV_CHG_MIN - motg->mA_port); } else if (!test_bit(ID, &motg->inputs)) { msm_otg_notify_charger(motg, 0); msm_hsusb_vbus_power(motg, 1); } break; case OTG_STATE_A_PERIPHERAL: if ((test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) || test_bit(A_BUS_DROP, &motg->inputs)) { USBH_INFO("id _f/b/c || a_bus_drop\n"); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_WAIT_VFALL; msm_otg_start_peripheral(otg, 0); otg->gadget->is_a_peripheral = 0; msm_otg_start_host(otg, 0); msm_otg_reset(otg->phy); if (!test_bit(ID_A, &motg->inputs)) msm_hsusb_vbus_power(motg, 0); msm_otg_start_timer(motg, TA_WAIT_VFALL, A_WAIT_VFALL); } else if (!test_bit(A_VBUS_VLD, &motg->inputs)) { USBH_INFO("!a_vbus_vld\n"); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_VBUS_ERR; msm_otg_start_peripheral(otg, 0); otg->gadget->is_a_peripheral = 0; msm_otg_start_host(otg, 0); } else if (test_bit(A_BIDL_ADIS, &motg->tmouts)) { USBH_INFO("a_bidl_adis_tmout\n"); msm_otg_start_peripheral(otg, 0); otg->gadget->is_a_peripheral = 0; otg->phy->state = OTG_STATE_A_WAIT_BCON; set_bit(A_BUS_REQ, &motg->inputs); msm_otg_host_hnp_enable(otg, 0); if (TA_WAIT_BCON > 0) msm_otg_start_timer(motg, TA_WAIT_BCON, A_WAIT_BCON); } else if (test_bit(ID_A, &motg->inputs)) { msm_hsusb_vbus_power(motg, 0); msm_otg_notify_charger(motg, IDEV_CHG_MIN - motg->mA_port); } else if (!test_bit(ID, &motg->inputs)) { USBH_INFO("!id\n"); msm_otg_notify_charger(motg, 0); msm_hsusb_vbus_power(motg, 1); } break; case OTG_STATE_A_WAIT_VFALL: if (test_bit(A_WAIT_VFALL, &motg->tmouts)) { clear_bit(A_VBUS_VLD, &motg->inputs); otg->phy->state = OTG_STATE_A_IDLE; work = 1; } break; case OTG_STATE_A_VBUS_ERR: if ((test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) || test_bit(A_BUS_DROP, &motg->inputs) || test_bit(A_CLR_ERR, &motg->inputs)) { otg->phy->state = OTG_STATE_A_WAIT_VFALL; if (!test_bit(ID_A, &motg->inputs)) msm_hsusb_vbus_power(motg, 0); msm_otg_start_timer(motg, TA_WAIT_VFALL, A_WAIT_VFALL); motg->chg_state = USB_CHG_STATE_UNDEFINED; motg->chg_type = USB_INVALID_CHARGER; msm_otg_notify_charger(motg, 0); } break; default: break; } mutex_unlock(&smwork_sem); if (work) queue_work(system_nrt_wq, &motg->sm_work); } static void msm_otg_suspend_work(struct work_struct *w) { struct msm_otg *motg = container_of(w, struct msm_otg, suspend_work.work); if (test_bit(A_BUS_SUSPEND, &motg->inputs)) msm_otg_sm_work(&motg->sm_work); } static irqreturn_t msm_otg_irq(int irq, void *data) { struct msm_otg *motg = data; struct usb_otg *otg = motg->phy.otg; u32 otgsc = 0, usbsts, pc; bool work = 0; irqreturn_t ret = IRQ_HANDLED; if (atomic_read(&motg->in_lpm)) { pr_debug("OTG IRQ: %d in LPM\n", irq); disable_irq_nosync(irq); motg->async_int = irq; if (!atomic_read(&motg->pm_suspended)) pm_request_resume(otg->phy->dev); return IRQ_HANDLED; } usbsts = readl(USB_USBSTS); otgsc = readl(USB_OTGSC); if (!(otgsc & OTG_OTGSTS_MASK) && !(usbsts & OTG_USBSTS_MASK)) return IRQ_NONE; if ((otgsc & OTGSC_IDIS) && (otgsc & OTGSC_IDIE)) { if (otgsc & OTGSC_ID) { dev_dbg(otg->phy->dev, "ID set\n"); set_bit(ID, &motg->inputs); } else { dev_dbg(otg->phy->dev, "ID clear\n"); set_bit(A_BUS_REQ, &motg->inputs); clear_bit(ID, &motg->inputs); msm_chg_enable_aca_det(motg); } writel_relaxed(otgsc, USB_OTGSC); work = 1; } else if (otgsc & OTGSC_DPIS) { pr_debug("DPIS detected\n"); writel_relaxed(otgsc, USB_OTGSC); set_bit(A_SRP_DET, &motg->inputs); set_bit(A_BUS_REQ, &motg->inputs); work = 1; } else if ((otgsc & OTGSC_BSVIE) && (otgsc & OTGSC_BSVIS)) { writel_relaxed(otgsc, USB_OTGSC); if ((otg->phy->state >= OTG_STATE_A_IDLE) && !test_bit(ID_A, &motg->inputs)) return IRQ_HANDLED; if (otgsc & OTGSC_BSV) { dev_dbg(otg->phy->dev, "BSV set\n"); set_bit(B_SESS_VLD, &motg->inputs); } else { dev_dbg(otg->phy->dev, "BSV clear\n"); clear_bit(B_SESS_VLD, &motg->inputs); clear_bit(A_BUS_SUSPEND, &motg->inputs); msm_chg_check_aca_intr(motg); } work = 1; } else if (usbsts & STS_PCI) { pc = readl_relaxed(USB_PORTSC); pr_debug("portsc = %x\n", pc); ret = IRQ_NONE; work = 1; switch (otg->phy->state) { case OTG_STATE_A_SUSPEND: if (otg->host->b_hnp_enable && (pc & PORTSC_CSC) && !(pc & PORTSC_CCS)) { pr_debug("B_CONN clear\n"); clear_bit(B_CONN, &motg->inputs); msm_otg_del_timer(motg); } break; case OTG_STATE_A_PERIPHERAL: msm_otg_del_timer(motg); work = 0; break; case OTG_STATE_B_WAIT_ACON: if ((pc & PORTSC_CSC) && (pc & PORTSC_CCS)) { pr_debug("A_CONN set\n"); set_bit(A_CONN, &motg->inputs); msm_otg_del_timer(motg); } break; case OTG_STATE_B_HOST: if ((pc & PORTSC_CSC) && !(pc & PORTSC_CCS)) { pr_debug("A_CONN clear\n"); clear_bit(A_CONN, &motg->inputs); msm_otg_del_timer(motg); } break; case OTG_STATE_A_WAIT_BCON: if (TA_WAIT_BCON < 0) set_bit(A_BUS_REQ, &motg->inputs); default: work = 0; break; } } else if (usbsts & STS_URI) { ret = IRQ_NONE; switch (otg->phy->state) { case OTG_STATE_A_PERIPHERAL: msm_otg_del_timer(motg); work = 0; break; default: work = 0; break; } } else if (usbsts & STS_SLI) { ret = IRQ_NONE; work = 0; switch (otg->phy->state) { case OTG_STATE_B_PERIPHERAL: if (otg->gadget->b_hnp_enable) { set_bit(A_BUS_SUSPEND, &motg->inputs); set_bit(B_BUS_REQ, &motg->inputs); work = 1; } break; case OTG_STATE_A_PERIPHERAL: msm_otg_start_timer(motg, TA_BIDL_ADIS, A_BIDL_ADIS); break; default: break; } } else if ((usbsts & PHY_ALT_INT)) { writel_relaxed(PHY_ALT_INT, USB_USBSTS); if (msm_chg_check_aca_intr(motg)) work = 1; ret = IRQ_HANDLED; } if (work) queue_work(system_nrt_wq, &motg->sm_work); return ret; } void msm_otg_set_vbus_state(int online) { static bool init; struct msm_otg *motg = the_msm_otg; printk(KERN_INFO "[USB] %s:%d\n", __func__, online); if (online) { pr_debug("PMIC: BSV set\n"); set_bit(B_SESS_VLD, &motg->inputs); } else { pr_debug("PMIC: BSV clear\n"); clear_bit(B_SESS_VLD, &motg->inputs); } #if 0 if (!test_bit(ID, &motg->inputs)) { if (init) return; } #endif if (!init) { init = true; complete(&pmic_vbus_init); pr_debug("PMIC: BSV init complete\n"); return; } if (test_bit(MHL, &motg->inputs) || mhl_det_in_progress) { pr_debug("PMIC: BSV interrupt ignored in MHL\n"); return; } wake_lock_timeout(&motg->cable_detect_wlock, 3 * HZ); if (atomic_read(&motg->pm_suspended)) motg->sm_work_pending = true; else queue_work(system_nrt_wq, &motg->sm_work); } void msm_otg_set_disable_usb(int disable_usb) { struct msm_otg *motg = the_msm_otg; msm_otg_usb_disable = disable_usb; if (motg->chg_state == USB_CHG_STATE_DETECTED && (motg->chg_type == USB_DCP_CHARGER || motg->chg_type == USB_PROPRIETARY_CHARGER || motg->chg_type == USB_FLOATED_CHARGER)) { return; } if(disable_usb == 1) { if (!test_bit(ID, &motg->inputs)) set_bit(ID, &motg->inputs); else if (motg->connect_type == CONNECT_TYPE_AC || motg->connect_type == CONNECT_TYPE_NONE) return; } else { if (msm_id_backup == 0) clear_bit(ID, &motg->inputs); else if (motg->connect_type == CONNECT_TYPE_AC || motg->connect_type == CONNECT_TYPE_UNKNOWN || motg->connect_type == CONNECT_TYPE_NONE) return; } queue_work(system_nrt_wq, &motg->sm_work); } static void msm_pmic_id_status_w(struct work_struct *w) { struct msm_otg *motg = container_of(w, struct msm_otg, pmic_id_status_work.work); int work = 0; if (motg->phy.state != OTG_STATE_UNDEFINED) { if (atomic_read(&motg->pm_suspended)) motg->sm_work_pending = true; else queue_work(system_nrt_wq, &motg->sm_work); } return; if (msm_otg_read_pmic_id_state(motg)) { if (!test_and_set_bit(ID, &motg->inputs)) { pr_debug("PMIC: ID set\n"); work = 1; } } else { if (test_and_clear_bit(ID, &motg->inputs)) { pr_debug("PMIC: ID clear\n"); set_bit(A_BUS_REQ, &motg->inputs); work = 1; } } if (work && (motg->phy.state != OTG_STATE_UNDEFINED)) { if (atomic_read(&motg->pm_suspended)) motg->sm_work_pending = true; else queue_work(system_nrt_wq, &motg->sm_work); } } #define MSM_PMIC_ID_STATUS_DELAY 5 static irqreturn_t msm_pmic_id_irq(int irq, void *data) { struct msm_otg *motg = data; printk(KERN_INFO "[USBH] %s\n",__func__); return IRQ_HANDLED; if (test_bit(MHL, &motg->inputs) || mhl_det_in_progress) { pr_debug("PMIC: Id interrupt ignored in MHL\n"); return IRQ_HANDLED; } if (!aca_id_turned_on) queue_delayed_work(system_nrt_wq, &motg->pmic_id_status_work, msecs_to_jiffies(MSM_PMIC_ID_STATUS_DELAY)); return IRQ_HANDLED; } static int msm_otg_mode_show(struct seq_file *s, void *unused) { struct msm_otg *motg = s->private; struct usb_otg *otg = motg->phy.otg; switch (otg->phy->state) { case OTG_STATE_A_HOST: seq_printf(s, "host\n"); break; case OTG_STATE_B_PERIPHERAL: seq_printf(s, "peripheral\n"); break; default: seq_printf(s, "none\n"); break; } return 0; } static int msm_otg_mode_open(struct inode *inode, struct file *file) { return single_open(file, msm_otg_mode_show, inode->i_private); } static ssize_t msm_otg_mode_write(struct file *file, const char __user *ubuf, size_t count, loff_t *ppos) { struct seq_file *s = file->private_data; struct msm_otg *motg = s->private; char buf[16]; struct usb_phy *phy = &motg->phy; int status = count; enum usb_mode_type req_mode; memset(buf, 0x00, sizeof(buf)); if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count))) { status = -EFAULT; goto out; } if (!strncmp(buf, "host", 4)) { req_mode = USB_HOST; } else if (!strncmp(buf, "peripheral", 10)) { req_mode = USB_PERIPHERAL; } else if (!strncmp(buf, "none", 4)) { req_mode = USB_NONE; } else { status = -EINVAL; goto out; } switch (req_mode) { case USB_NONE: switch (phy->state) { case OTG_STATE_A_HOST: case OTG_STATE_B_PERIPHERAL: set_bit(ID, &motg->inputs); clear_bit(B_SESS_VLD, &motg->inputs); break; default: goto out; } break; case USB_PERIPHERAL: switch (phy->state) { case OTG_STATE_B_IDLE: case OTG_STATE_A_HOST: set_bit(ID, &motg->inputs); set_bit(B_SESS_VLD, &motg->inputs); break; default: goto out; } break; case USB_HOST: switch (phy->state) { case OTG_STATE_B_IDLE: case OTG_STATE_B_PERIPHERAL: clear_bit(ID, &motg->inputs); break; default: goto out; } break; default: goto out; } pm_runtime_resume(phy->dev); queue_work(system_nrt_wq, &motg->sm_work); out: return status; } const struct file_operations msm_otg_mode_fops = { .open = msm_otg_mode_open, .read = seq_read, .write = msm_otg_mode_write, .llseek = seq_lseek, .release = single_release, }; static int msm_otg_show_otg_state(struct seq_file *s, void *unused) { struct msm_otg *motg = s->private; struct usb_phy *phy = &motg->phy; seq_printf(s, "%s\n", otg_state_string(phy->state)); return 0; } static int msm_otg_otg_state_open(struct inode *inode, struct file *file) { return single_open(file, msm_otg_show_otg_state, inode->i_private); } const struct file_operations msm_otg_state_fops = { .open = msm_otg_otg_state_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int msm_otg_show_chg_type(struct seq_file *s, void *unused) { struct msm_otg *motg = s->private; seq_printf(s, "%s\n", chg_to_string(motg->chg_type)); return 0; } static int msm_otg_chg_open(struct inode *inode, struct file *file) { return single_open(file, msm_otg_show_chg_type, inode->i_private); } const struct file_operations msm_otg_chg_fops = { .open = msm_otg_chg_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int msm_otg_aca_show(struct seq_file *s, void *unused) { if (debug_aca_enabled) seq_printf(s, "enabled\n"); else seq_printf(s, "disabled\n"); return 0; } static int msm_otg_aca_open(struct inode *inode, struct file *file) { return single_open(file, msm_otg_aca_show, inode->i_private); } static ssize_t msm_otg_aca_write(struct file *file, const char __user *ubuf, size_t count, loff_t *ppos) { char buf[8]; memset(buf, 0x00, sizeof(buf)); if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count))) return -EFAULT; if (!strncmp(buf, "enable", 6)) debug_aca_enabled = true; else debug_aca_enabled = false; return count; } const struct file_operations msm_otg_aca_fops = { .open = msm_otg_aca_open, .read = seq_read, .write = msm_otg_aca_write, .llseek = seq_lseek, .release = single_release, }; static int msm_otg_bus_show(struct seq_file *s, void *unused) { if (debug_bus_voting_enabled) seq_printf(s, "enabled\n"); else seq_printf(s, "disabled\n"); return 0; } static int msm_otg_bus_open(struct inode *inode, struct file *file) { return single_open(file, msm_otg_bus_show, inode->i_private); } static ssize_t msm_otg_bus_write(struct file *file, const char __user *ubuf, size_t count, loff_t *ppos) { char buf[8]; struct seq_file *s = file->private_data; struct msm_otg *motg = s->private; memset(buf, 0x00, sizeof(buf)); if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count))) return -EFAULT; if (!strncmp(buf, "enable", 6)) { debug_bus_voting_enabled = true; } else { debug_bus_voting_enabled = false; msm_otg_bus_vote(motg, USB_MIN_PERF_VOTE); } return count; } static int otg_power_get_property_usb(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct msm_otg *motg = container_of(psy, struct msm_otg, usb_psy); switch (psp) { case POWER_SUPPLY_PROP_SCOPE: if (motg->host_mode) val->intval = POWER_SUPPLY_SCOPE_SYSTEM; else val->intval = POWER_SUPPLY_SCOPE_DEVICE; break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: val->intval = motg->voltage_max; break; case POWER_SUPPLY_PROP_CURRENT_MAX: val->intval = motg->current_max; break; case POWER_SUPPLY_PROP_PRESENT: case POWER_SUPPLY_PROP_ONLINE: val->intval = motg->online; break; case POWER_SUPPLY_PROP_TYPE: val->intval = psy->type; break; case POWER_SUPPLY_PROP_HEALTH: val->intval = motg->usbin_health; break; default: return -EINVAL; } return 0; } static int otg_power_set_property_usb(struct power_supply *psy, enum power_supply_property psp, const union power_supply_propval *val) { struct msm_otg *motg = container_of(psy, struct msm_otg, usb_psy); printk(KERN_INFO "[USB] %s:%d\n", __func__, psp); switch (psp) { case POWER_SUPPLY_PROP_PRESENT: msm_otg_set_vbus_state(val->intval); break; case POWER_SUPPLY_PROP_ONLINE: motg->online = val->intval; break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: motg->voltage_max = val->intval; break; case POWER_SUPPLY_PROP_CURRENT_MAX: motg->current_max = val->intval; break; case POWER_SUPPLY_PROP_TYPE: psy->type = val->intval; break; case POWER_SUPPLY_PROP_HEALTH: motg->usbin_health = val->intval; break; default: return -EINVAL; } power_supply_changed(&motg->usb_psy); return 0; } static int otg_power_property_is_writeable_usb(struct power_supply *psy, enum power_supply_property psp) { switch (psp) { case POWER_SUPPLY_PROP_HEALTH: case POWER_SUPPLY_PROP_PRESENT: case POWER_SUPPLY_PROP_ONLINE: case POWER_SUPPLY_PROP_VOLTAGE_MAX: case POWER_SUPPLY_PROP_CURRENT_MAX: return 1; default: break; } return 0; } static char *otg_pm_power_supplied_to[] = { "battery", }; static enum power_supply_property otg_pm_power_props_usb[] = { POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_MAX, POWER_SUPPLY_PROP_CURRENT_MAX, POWER_SUPPLY_PROP_SCOPE, POWER_SUPPLY_PROP_TYPE, }; const struct file_operations msm_otg_bus_fops = { .open = msm_otg_bus_open, .read = seq_read, .write = msm_otg_bus_write, .llseek = seq_lseek, .release = single_release, }; static struct dentry *msm_otg_dbg_root; static int msm_otg_debugfs_init(struct msm_otg *motg) { struct dentry *msm_otg_dentry; msm_otg_dbg_root = debugfs_create_dir("msm_otg", NULL); if (!msm_otg_dbg_root || IS_ERR(msm_otg_dbg_root)) return -ENODEV; if (motg->pdata->mode == USB_OTG && motg->pdata->otg_control == OTG_USER_CONTROL) { msm_otg_dentry = debugfs_create_file("mode", S_IRUGO | S_IWUSR, msm_otg_dbg_root, motg, &msm_otg_mode_fops); if (!msm_otg_dentry) { debugfs_remove(msm_otg_dbg_root); msm_otg_dbg_root = NULL; return -ENODEV; } } msm_otg_dentry = debugfs_create_file("chg_type", S_IRUGO, msm_otg_dbg_root, motg, &msm_otg_chg_fops); if (!msm_otg_dentry) { debugfs_remove_recursive(msm_otg_dbg_root); return -ENODEV; } msm_otg_dentry = debugfs_create_file("aca", S_IRUGO | S_IWUSR, msm_otg_dbg_root, motg, &msm_otg_aca_fops); if (!msm_otg_dentry) { debugfs_remove_recursive(msm_otg_dbg_root); return -ENODEV; } msm_otg_dentry = debugfs_create_file("bus_voting", S_IRUGO | S_IWUSR, msm_otg_dbg_root, motg, &msm_otg_bus_fops); if (!msm_otg_dentry) { debugfs_remove_recursive(msm_otg_dbg_root); return -ENODEV; } msm_otg_dentry = debugfs_create_file("otg_state", S_IRUGO, msm_otg_dbg_root, motg, &msm_otg_state_fops); if (!msm_otg_dentry) { debugfs_remove_recursive(msm_otg_dbg_root); return -ENODEV; } return 0; } static void msm_otg_debugfs_cleanup(void) { debugfs_remove_recursive(msm_otg_dbg_root); } #define MSM_OTG_CMD_ID 0x09 #define MSM_OTG_DEVICE_ID 0x04 #define MSM_OTG_VMID_IDX 0xFF #define MSM_OTG_MEM_TYPE 0x02 struct msm_otg_scm_cmd_buf { unsigned int device_id; unsigned int vmid_idx; unsigned int mem_type; } __attribute__ ((__packed__)); static void msm_otg_pnoc_errata_fix(struct msm_otg *motg) { int ret; struct msm_otg_platform_data *pdata = motg->pdata; struct msm_otg_scm_cmd_buf cmd_buf; if (!pdata->pnoc_errata_fix) return; dev_dbg(motg->phy.dev, "applying fix for pnoc h/w issue\n"); cmd_buf.device_id = MSM_OTG_DEVICE_ID; cmd_buf.vmid_idx = MSM_OTG_VMID_IDX; cmd_buf.mem_type = MSM_OTG_MEM_TYPE; ret = scm_call(SCM_SVC_MP, MSM_OTG_CMD_ID, &cmd_buf, sizeof(cmd_buf), NULL, 0); if (ret) dev_err(motg->phy.dev, "scm command failed to update VMIDMT\n"); } #if defined(CONFIG_USB_OTG) void msm_otg_set_id_state(int id) { struct msm_otg *motg = the_msm_otg; msm_id_backup = id; if (id) { pr_debug("PMIC: ID set\n"); if(msm_otg_usb_disable) return; set_bit(ID, &motg->inputs); } else { pr_debug("PMIC: ID clear\n"); if(msm_otg_usb_disable) return; clear_bit(ID, &motg->inputs); } if (motg->phy.state != OTG_STATE_UNDEFINED) { wake_lock_timeout(&motg->cable_detect_wlock, 3 * HZ); queue_delayed_work(system_nrt_wq, &motg->pmic_id_status_work, msecs_to_jiffies(MSM_PMIC_ID_STATUS_DELAY)); } } static void usb_host_cable_detect(bool cable_in) { if (cable_in) msm_otg_set_id_state(0); else msm_otg_set_id_state(1); } #endif #if defined(CONFIG_USB_OTG) static struct t_usb_host_status_notifier usb_host_status_notifier = { .name = "usb_host", .func = usb_host_cable_detect, }; #endif static u64 msm_otg_dma_mask = DMA_BIT_MASK(64); static struct platform_device *msm_otg_add_pdev( struct platform_device *ofdev, const char *name) { struct platform_device *pdev; const struct resource *res = ofdev->resource; unsigned int num = ofdev->num_resources; int retval; struct ci13xxx_platform_data ci_pdata; struct msm_otg_platform_data *otg_pdata; pdev = platform_device_alloc(name, -1); if (!pdev) { retval = -ENOMEM; goto error; } pdev->dev.coherent_dma_mask = DMA_BIT_MASK(32); pdev->dev.dma_mask = &msm_otg_dma_mask; if (num) { retval = platform_device_add_resources(pdev, res, num); if (retval) goto error; } if (!strcmp(name, "msm_hsusb")) { otg_pdata = (struct msm_otg_platform_data *) ofdev->dev.platform_data; ci_pdata.log2_itc = otg_pdata->log2_itc; ci_pdata.usb_core_id = 0; ci_pdata.l1_supported = otg_pdata->l1_supported; ci_pdata.enable_ahb2ahb_bypass = otg_pdata->enable_ahb2ahb_bypass; retval = platform_device_add_data(pdev, &ci_pdata, sizeof(ci_pdata)); if (retval) goto error; } retval = platform_device_add(pdev); if (retval) goto error; return pdev; error: platform_device_put(pdev); return ERR_PTR(retval); } static int msm_otg_setup_devices(struct platform_device *ofdev, enum usb_mode_type mode, bool init) { const char *gadget_name = "msm_hsusb"; const char *host_name = "msm_hsusb_host"; static struct platform_device *gadget_pdev; static struct platform_device *host_pdev; int retval = 0; if (!init) { if (gadget_pdev) platform_device_unregister(gadget_pdev); if (host_pdev) platform_device_unregister(host_pdev); return 0; } switch (mode) { case USB_OTG: case USB_PERIPHERAL: gadget_pdev = msm_otg_add_pdev(ofdev, gadget_name); if (IS_ERR(gadget_pdev)) { retval = PTR_ERR(gadget_pdev); break; } if (mode == USB_PERIPHERAL) break; case USB_HOST: host_pdev = msm_otg_add_pdev(ofdev, host_name); if (IS_ERR(host_pdev)) { retval = PTR_ERR(host_pdev); if (mode == USB_OTG) platform_device_unregister(gadget_pdev); } break; default: break; } return retval; } __maybe_unused static int msm_otg_register_power_supply(struct platform_device *pdev, struct msm_otg *motg) { int ret; ret = power_supply_register(&pdev->dev, &motg->usb_psy); if (ret < 0) { dev_err(motg->phy.dev, "%s:power_supply_register usb failed\n", __func__); return ret; } legacy_power_supply = false; return 0; } static int msm_otg_ext_chg_open(struct inode *inode, struct file *file) { struct msm_otg *motg = the_msm_otg; pr_debug("msm_otg ext chg open\n"); motg->ext_chg_opened = true; file->private_data = (void *)motg; return 0; } static long msm_otg_ext_chg_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct msm_otg *motg = file->private_data; struct msm_usb_chg_info info = {0}; int ret = 0, val; switch (cmd) { case MSM_USB_EXT_CHG_INFO: info.chg_block_type = USB_CHG_BLOCK_ULPI; info.page_offset = motg->io_res->start & ~PAGE_MASK; info.length = PAGE_SIZE; if (copy_to_user((void __user *)arg, &info, sizeof(info))) { pr_err("%s: copy to user failed\n\n", __func__); ret = -EFAULT; } break; case MSM_USB_EXT_CHG_BLOCK_LPM: if (get_user(val, (int __user *)arg)) { pr_err("%s: get_user failed\n\n", __func__); ret = -EFAULT; break; } pr_debug("%s: LPM block request %d\n", __func__, val); if (val) { if (motg->chg_type == USB_DCP_CHARGER) { if (pm_runtime_suspended(motg->phy.dev)) pm_runtime_resume(motg->phy.dev); else pm_runtime_get_sync(motg->phy.dev); } else { motg->ext_chg_active = false; complete(&motg->ext_chg_wait); ret = -ENODEV; } } else { motg->ext_chg_active = false; complete(&motg->ext_chg_wait); pm_runtime_put(motg->phy.dev); } break; default: ret = -EINVAL; } return ret; } static int msm_otg_ext_chg_mmap(struct file *file, struct vm_area_struct *vma) { struct msm_otg *motg = file->private_data; unsigned long vsize = vma->vm_end - vma->vm_start; int ret; if (vma->vm_pgoff || vsize > PAGE_SIZE) return -EINVAL; vma->vm_pgoff = __phys_to_pfn(motg->io_res->start); vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); ret = io_remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, vsize, vma->vm_page_prot); if (ret < 0) { pr_err("%s: failed with return val %d\n", __func__, ret); return ret; } return 0; } static int msm_otg_ext_chg_release(struct inode *inode, struct file *file) { struct msm_otg *motg = file->private_data; pr_debug("msm_otg ext chg release\n"); motg->ext_chg_opened = false; return 0; } static const struct file_operations msm_otg_ext_chg_fops = { .owner = THIS_MODULE, .open = msm_otg_ext_chg_open, .unlocked_ioctl = msm_otg_ext_chg_ioctl, .mmap = msm_otg_ext_chg_mmap, .release = msm_otg_ext_chg_release, }; static int msm_otg_setup_ext_chg_cdev(struct msm_otg *motg) { int ret; if (motg->pdata->enable_sec_phy || motg->pdata->mode == USB_HOST || motg->pdata->otg_control != OTG_PMIC_CONTROL || psy != &motg->usb_psy) { pr_debug("usb ext chg is not supported by msm otg\n"); return -ENODEV; } ret = alloc_chrdev_region(&motg->ext_chg_dev, 0, 1, "usb_ext_chg"); if (ret < 0) { pr_err("Fail to allocate usb ext char dev region\n"); return ret; } motg->ext_chg_class = class_create(THIS_MODULE, "msm_ext_chg"); if (ret < 0) { pr_err("Fail to create usb ext chg class\n"); goto unreg_chrdev; } cdev_init(&motg->ext_chg_cdev, &msm_otg_ext_chg_fops); motg->ext_chg_cdev.owner = THIS_MODULE; ret = cdev_add(&motg->ext_chg_cdev, motg->ext_chg_dev, 1); if (ret < 0) { pr_err("Fail to add usb ext chg cdev\n"); goto destroy_class; } motg->ext_chg_device = device_create(motg->ext_chg_class, NULL, motg->ext_chg_dev, NULL, "usb_ext_chg"); if (IS_ERR(motg->ext_chg_device)) { pr_err("Fail to create usb ext chg device\n"); ret = PTR_ERR(motg->ext_chg_device); motg->ext_chg_device = NULL; goto del_cdev; } init_completion(&motg->ext_chg_wait); pr_debug("msm otg ext chg cdev setup success\n"); return 0; del_cdev: cdev_del(&motg->ext_chg_cdev); destroy_class: class_destroy(motg->ext_chg_class); unreg_chrdev: unregister_chrdev_region(motg->ext_chg_dev, 1); return ret; } static ssize_t dpdm_pulldown_enable_show(struct device *dev, struct device_attribute *attr, char *buf) { struct msm_otg *motg = the_msm_otg; struct msm_otg_platform_data *pdata = motg->pdata; return snprintf(buf, PAGE_SIZE, "%s\n", pdata->dpdm_pulldown_added ? "enabled" : "disabled"); } static ssize_t dpdm_pulldown_enable_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct msm_otg *motg = the_msm_otg; struct msm_otg_platform_data *pdata = motg->pdata; if (!strnicmp(buf, "enable", 6)) { pdata->dpdm_pulldown_added = true; return size; } else if (!strnicmp(buf, "disable", 7)) { pdata->dpdm_pulldown_added = false; return size; } return -EINVAL; } static DEVICE_ATTR(dpdm_pulldown_enable, S_IRUGO | S_IWUSR, dpdm_pulldown_enable_show, dpdm_pulldown_enable_store); int *htc_msm_otg_get_phy_init(int *phy_init) { __maybe_unused char *mid; __maybe_unused int i; printk("[USB] use dt phy init\n"); return phy_init; } struct msm_otg_platform_data *msm_otg_dt_to_pdata(struct platform_device *pdev) { struct device_node *node = pdev->dev.of_node; struct msm_otg_platform_data *pdata; int len = 0; pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) { pr_err("unable to allocate platform data\n"); return NULL; } of_get_property(node, "qcom,hsusb-otg-phy-init-seq", &len); if (len) { pdata->phy_init_seq = devm_kzalloc(&pdev->dev, len, GFP_KERNEL); if (!pdata->phy_init_seq) return NULL; of_property_read_u32_array(node, "qcom,hsusb-otg-phy-init-seq", pdata->phy_init_seq, len/sizeof(*pdata->phy_init_seq)); } pdata->phy_init_seq = htc_msm_otg_get_phy_init(pdata->phy_init_seq); of_property_read_u32(node, "qcom,hsusb-otg-power-budget", &pdata->power_budget); of_property_read_u32(node, "qcom,hsusb-otg-mode", &pdata->mode); of_property_read_u32(node, "qcom,hsusb-otg-otg-control", &pdata->otg_control); of_property_read_u32(node, "qcom,hsusb-otg-default-mode", &pdata->default_mode); of_property_read_u32(node, "qcom,hsusb-otg-phy-type", &pdata->phy_type); pdata->disable_reset_on_disconnect = of_property_read_bool(node, "qcom,hsusb-otg-disable-reset"); pdata->pnoc_errata_fix = of_property_read_bool(node, "qcom,hsusb-otg-pnoc-errata-fix"); pdata->enable_lpm_on_dev_suspend = of_property_read_bool(node, "qcom,hsusb-otg-lpm-on-dev-suspend"); pdata->core_clk_always_on_workaround = of_property_read_bool(node, "qcom,hsusb-otg-clk-always-on-workaround"); pdata->delay_lpm_on_disconnect = of_property_read_bool(node, "qcom,hsusb-otg-delay-lpm"); pdata->delay_lpm_hndshk_on_disconnect = of_property_read_bool(node, "qcom,hsusb-otg-delay-lpm-hndshk-on-disconnect"); pdata->dp_manual_pullup = of_property_read_bool(node, "qcom,dp-manual-pullup"); pdata->enable_sec_phy = of_property_read_bool(node, "qcom,usb2-enable-hsphy2"); of_property_read_u32(node, "qcom,hsusb-log2-itc", &pdata->log2_itc); of_property_read_u32(node, "qcom,hsusb-otg-mpm-dpsehv-int", &pdata->mpm_dpshv_int); of_property_read_u32(node, "qcom,hsusb-otg-mpm-dmsehv-int", &pdata->mpm_dmshv_int); pdata->pmic_id_irq = platform_get_irq_byname(pdev, "pmic_id_irq"); if (pdata->pmic_id_irq < 0) pdata->pmic_id_irq = 0; pdata->l1_supported = of_property_read_bool(node, "qcom,hsusb-l1-supported"); pdata->enable_ahb2ahb_bypass = of_property_read_bool(node, "qcom,ahb-async-bridge-bypass"); pdata->disable_retention_with_vdd_min = of_property_read_bool(node, "qcom,disable-retention-with-vdd-min"); return pdata; } static int __init msm_otg_probe(struct platform_device *pdev) { int ret = 0; int len = 0; u32 tmp[3]; struct resource *res; struct msm_otg *motg; struct usb_phy *phy; struct msm_otg_platform_data *pdata; dev_info(&pdev->dev, "msm_otg probe\n"); if (pdev->dev.of_node) { dev_dbg(&pdev->dev, "device tree enabled\n"); pdata = msm_otg_dt_to_pdata(pdev); if (!pdata) return -ENOMEM; pdata->bus_scale_table = msm_bus_cl_get_pdata(pdev); if (!pdata->bus_scale_table) dev_dbg(&pdev->dev, "bus scaling is disabled\n"); pdev->dev.platform_data = pdata; ret = msm_otg_setup_devices(pdev, pdata->mode, true); if (ret) { dev_err(&pdev->dev, "devices setup failed\n"); return ret; } } else if (!pdev->dev.platform_data) { dev_err(&pdev->dev, "No platform data given. Bailing out\n"); return -ENODEV; } else { pdata = pdev->dev.platform_data; } motg = devm_kzalloc(&pdev->dev, sizeof(struct msm_otg), GFP_KERNEL); if (!motg) { dev_err(&pdev->dev, "unable to allocate msm_otg\n"); return -ENOMEM; } motg->phy.otg = devm_kzalloc(&pdev->dev, sizeof(struct usb_otg), GFP_KERNEL); if (!motg->phy.otg) { dev_err(&pdev->dev, "unable to allocate usb_otg\n"); return -ENOMEM; } the_msm_otg = motg; motg->pdata = pdata; phy = &motg->phy; phy->dev = &pdev->dev; if (motg->pdata->bus_scale_table) { motg->bus_perf_client = msm_bus_scale_register_client(motg->pdata->bus_scale_table); if (!motg->bus_perf_client) { dev_err(motg->phy.dev, "%s: Failed to register BUS\n" "scaling client!!\n", __func__); } else { debug_bus_voting_enabled = true; msm_otg_bus_vote(motg, USB_MIN_PERF_VOTE); } } if (aca_enabled() && motg->pdata->otg_control != OTG_PMIC_CONTROL) { dev_err(&pdev->dev, "ACA can not be enabled without PMIC\n"); ret = -EINVAL; goto devote_bus_bw; } motg->reset_counter = 0; motg->clk = clk_get(&pdev->dev, "alt_core_clk"); if (IS_ERR(motg->clk)) dev_dbg(&pdev->dev, "alt_core_clk is not present\n"); else clk_set_rate(motg->clk, 60000000); motg->core_clk = clk_get(&pdev->dev, "core_clk"); if (IS_ERR(motg->core_clk)) { motg->core_clk = NULL; dev_err(&pdev->dev, "failed to get core_clk\n"); ret = PTR_ERR(motg->core_clk); goto put_clk; } motg->core_clk_rate = clk_round_rate(motg->core_clk, LONG_MAX); if (IS_ERR_VALUE(motg->core_clk_rate)) { dev_err(&pdev->dev, "fail to get core clk max freq.\n"); } else { ret = clk_set_rate(motg->core_clk, motg->core_clk_rate); if (ret) dev_err(&pdev->dev, "fail to set core_clk freq:%d\n", ret); } motg->pclk = clk_get(&pdev->dev, "iface_clk"); if (IS_ERR(motg->pclk)) { dev_err(&pdev->dev, "failed to get iface_clk\n"); ret = PTR_ERR(motg->pclk); goto put_core_clk; } motg->sleep_clk = devm_clk_get(&pdev->dev, "sleep_clk"); if (IS_ERR(motg->sleep_clk)) { dev_dbg(&pdev->dev, "failed to get sleep_clk\n"); } else { ret = clk_prepare_enable(motg->sleep_clk); if (ret) { dev_err(&pdev->dev, "%s failed to vote sleep_clk%d\n", __func__, ret); goto put_pclk; } } res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "failed to get platform resource mem\n"); ret = -ENODEV; goto disable_sleep_clk; } motg->io_res = res; motg->regs = ioremap(res->start, resource_size(res)); if (!motg->regs) { dev_err(&pdev->dev, "ioremap failed\n"); ret = -ENOMEM; goto disable_sleep_clk; } dev_info(&pdev->dev, "OTG regs = %p\n", motg->regs); motg->irq = platform_get_irq(pdev, 0); if (!motg->irq) { dev_err(&pdev->dev, "platform_get_irq failed\n"); ret = -ENODEV; goto free_regs; } motg->async_irq = platform_get_irq_byname(pdev, "async_irq"); if (motg->async_irq < 0) { dev_dbg(&pdev->dev, "platform_get_irq for async_int failed\n"); motg->async_irq = 0; } USBH_INFO("ignore async_irq %d\n",motg->async_irq); motg->async_irq = 0; motg->xo_clk = clk_get(&pdev->dev, "xo"); if (IS_ERR(motg->xo_clk)) { motg->xo_handle = msm_xo_get(MSM_XO_TCXO_D0, "usb"); if (IS_ERR(motg->xo_handle)) { dev_err(&pdev->dev, "%s fail to get handle for TCXO\n", __func__); ret = PTR_ERR(motg->xo_handle); goto free_regs; } else { ret = msm_xo_mode_vote(motg->xo_handle, MSM_XO_MODE_ON); if (ret) { dev_err(&pdev->dev, "%s XO voting failed %d\n", __func__, ret); goto free_xo_handle; } } } else { ret = clk_prepare_enable(motg->xo_clk); if (ret) { dev_err(&pdev->dev, "%s failed to vote for TCXO %d\n", __func__, ret); goto free_xo_handle; } } clk_prepare_enable(motg->pclk); motg->vdd_type = VDDCX_CORNER; hsusb_vdd = devm_regulator_get(motg->phy.dev, "hsusb_vdd_dig"); if (IS_ERR(hsusb_vdd)) { hsusb_vdd = devm_regulator_get(motg->phy.dev, "HSUSB_VDDCX"); if (IS_ERR(hsusb_vdd)) { dev_err(motg->phy.dev, "unable to get hsusb vddcx\n"); ret = PTR_ERR(hsusb_vdd); goto devote_xo_handle; } motg->vdd_type = VDDCX; } if (pdev->dev.of_node) { of_get_property(pdev->dev.of_node, "qcom,vdd-voltage-level", &len); if (len == sizeof(tmp)) { of_property_read_u32_array(pdev->dev.of_node, "qcom,vdd-voltage-level", tmp, len/sizeof(*tmp)); vdd_val[motg->vdd_type][0] = tmp[0]; vdd_val[motg->vdd_type][1] = tmp[1]; vdd_val[motg->vdd_type][2] = tmp[2]; } else { dev_dbg(&pdev->dev, "Using default hsusb vdd config.\n"); } } ret = msm_hsusb_config_vddcx(1); if (ret) { dev_err(&pdev->dev, "hsusb vddcx configuration failed\n"); goto devote_xo_handle; } ret = regulator_enable(hsusb_vdd); if (ret) { dev_err(&pdev->dev, "unable to enable the hsusb vddcx\n"); goto free_config_vddcx; } ret = msm_hsusb_ldo_init(motg, 1); if (ret) { dev_err(&pdev->dev, "hsusb vreg configuration failed\n"); goto free_hsusb_vdd; } if (pdata->mhl_enable) { mhl_usb_hs_switch = devm_regulator_get(motg->phy.dev, "mhl_usb_hs_switch"); if (IS_ERR(mhl_usb_hs_switch)) { dev_err(&pdev->dev, "Unable to get mhl_usb_hs_switch\n"); ret = PTR_ERR(mhl_usb_hs_switch); goto free_ldo_init; } } ret = msm_hsusb_ldo_enable(motg, USB_PHY_REG_ON); if (ret) { dev_err(&pdev->dev, "hsusb vreg enable failed\n"); goto free_ldo_init; } clk_prepare_enable(motg->core_clk); msm_otg_pnoc_errata_fix(motg); writel(0, USB_USBINTR); writel(0, USB_OTGSC); mb(); motg->usb_wq = create_singlethread_workqueue("msm_hsusb"); if (motg->usb_wq == 0) { USB_ERR("fail to create workqueue\n"); goto free_ldo_init; } ret = msm_otg_mhl_register_callback(motg, msm_otg_mhl_notify_online); if (ret) dev_dbg(&pdev->dev, "MHL can not be supported\n"); wake_lock_init(&motg->wlock, WAKE_LOCK_SUSPEND, "msm_otg"); wake_lock_init(&motg->cable_detect_wlock, WAKE_LOCK_SUSPEND, "msm_usb_cable"); msm_otg_init_timer(motg); INIT_WORK(&motg->sm_work, msm_otg_sm_work); INIT_WORK(&motg->notifier_work, send_usb_connect_notify); INIT_DELAYED_WORK(&motg->chg_work, msm_chg_detect_work); INIT_DELAYED_WORK(&motg->pmic_id_status_work, msm_pmic_id_status_w); INIT_DELAYED_WORK(&motg->suspend_work, msm_otg_suspend_work); setup_timer(&motg->id_timer, msm_otg_id_timer_func, (unsigned long) motg); setup_timer(&motg->chg_check_timer, msm_otg_chg_check_timer_func, (unsigned long) motg); ret = request_irq(motg->irq, msm_otg_irq, IRQF_SHARED, "msm_otg", motg); if (ret) { dev_err(&pdev->dev, "request irq failed\n"); goto destroy_wlock; } if (motg->async_irq) { ret = request_irq(motg->async_irq, msm_otg_irq, IRQF_TRIGGER_RISING, "msm_otg", motg); if (ret) { dev_err(&pdev->dev, "request irq failed (ASYNC INT)\n"); goto free_irq; } disable_irq(motg->async_irq); } if (pdata->otg_control == OTG_PHY_CONTROL && pdata->mpm_otgsessvld_int) msm_mpm_enable_pin(pdata->mpm_otgsessvld_int, 1); if (pdata->mpm_dpshv_int) msm_mpm_enable_pin(pdata->mpm_dpshv_int, 1); if (pdata->mpm_dmshv_int) msm_mpm_enable_pin(pdata->mpm_dmshv_int, 1); phy->init = msm_otg_reset; phy->set_power = msm_otg_set_power; phy->set_suspend = msm_otg_set_suspend; phy->notify_usb_attached = msm_otg_notify_usb_attached; phy->notify_usb_disabled = msm_otg_notify_usb_disabled; phy->io_ops = &msm_otg_io_ops; phy->otg->phy = &motg->phy; phy->otg->set_host = msm_otg_set_host; phy->otg->set_peripheral = msm_otg_set_peripheral; phy->otg->start_hnp = msm_otg_start_hnp; phy->otg->start_srp = msm_otg_start_srp; if (pdata->dp_manual_pullup) phy->flags |= ENABLE_DP_MANUAL_PULLUP; if (pdata->enable_sec_phy) phy->flags |= ENABLE_SECONDARY_PHY; ret = usb_set_transceiver(&motg->phy); if (ret) { dev_err(&pdev->dev, "usb_set_transceiver failed\n"); goto free_async_irq; } if (motg->pdata->mode == USB_OTG && motg->pdata->otg_control == OTG_PMIC_CONTROL) { if (motg->pdata->pmic_id_irq) { ret = request_irq(motg->pdata->pmic_id_irq, msm_pmic_id_irq, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "msm_otg", motg); if (ret) { dev_err(&pdev->dev, "request irq failed for PMIC ID\n"); goto remove_phy; } } else { ret = -ENODEV; dev_err(&pdev->dev, "PMIC IRQ for ID notifications doesn't exist\n"); goto remove_phy; } } msm_hsusb_mhl_switch_enable(motg, 1); platform_set_drvdata(pdev, motg); device_init_wakeup(&pdev->dev, 1); motg->mA_port = IUNIT; ret = msm_otg_debugfs_init(motg); if (ret) dev_dbg(&pdev->dev, "mode debugfs file is" "not available\n"); if (motg->pdata->phy_type == SNPS_28NM_INTEGRATED_PHY) { if (motg->pdata->otg_control == OTG_PMIC_CONTROL && (!(motg->pdata->mode == USB_OTG) || motg->pdata->pmic_id_irq)) motg->caps = ALLOW_PHY_POWER_COLLAPSE | ALLOW_PHY_RETENTION; if (motg->pdata->otg_control == OTG_PHY_CONTROL) motg->caps = ALLOW_PHY_RETENTION | ALLOW_PHY_REGULATORS_LPM; if (motg->pdata->mpm_dpshv_int || motg->pdata->mpm_dmshv_int) motg->caps |= ALLOW_HOST_PHY_RETENTION; device_create_file(&pdev->dev, &dev_attr_dpdm_pulldown_enable); } if (motg->pdata->enable_lpm_on_dev_suspend) motg->caps |= ALLOW_LPM_ON_DEV_SUSPEND; if (motg->pdata->disable_retention_with_vdd_min) motg->caps |= ALLOW_VDD_MIN_WITH_RETENTION_DISABLED; wake_lock(&motg->wlock); pm_runtime_set_active(&pdev->dev); pm_runtime_enable(&pdev->dev); if (motg->pdata->delay_lpm_on_disconnect) { pm_runtime_set_autosuspend_delay(&pdev->dev, lpm_disconnect_thresh); pm_runtime_use_autosuspend(&pdev->dev); } motg->usb_psy.name = "usb"; motg->usb_psy.type = POWER_SUPPLY_TYPE_USB; motg->usb_psy.supplied_to = otg_pm_power_supplied_to; motg->usb_psy.num_supplicants = ARRAY_SIZE(otg_pm_power_supplied_to); motg->usb_psy.properties = otg_pm_power_props_usb; motg->usb_psy.num_properties = ARRAY_SIZE(otg_pm_power_props_usb); motg->usb_psy.get_property = otg_power_get_property_usb; motg->usb_psy.set_property = otg_power_set_property_usb; motg->usb_psy.property_is_writeable = otg_power_property_is_writeable_usb; if (!pm8921_charger_register_vbus_sn(NULL)) { dev_dbg(motg->phy.dev, "%s: legacy support\n", __func__); legacy_power_supply = true; } else { if (!msm_otg_register_power_supply(pdev, motg)) psy = &motg->usb_psy; } if (legacy_power_supply && pdata->otg_control == OTG_PMIC_CONTROL) pm8921_charger_register_vbus_sn(&msm_otg_set_vbus_state); #if defined(CONFIG_USB_OTG) usb_host_detect_register_notifier(&usb_host_status_notifier); #endif ret = msm_otg_setup_ext_chg_cdev(motg); if (ret) dev_dbg(&pdev->dev, "fail to setup cdev\n"); return 0; remove_phy: usb_set_transceiver(NULL); free_async_irq: if (motg->async_irq) free_irq(motg->async_irq, motg); free_irq: free_irq(motg->irq, motg); destroy_wlock: wake_lock_destroy(&motg->wlock); wake_lock_destroy(&motg->cable_detect_wlock); clk_disable_unprepare(motg->core_clk); msm_hsusb_ldo_enable(motg, USB_PHY_REG_OFF); free_ldo_init: msm_hsusb_ldo_init(motg, 0); free_hsusb_vdd: regulator_disable(hsusb_vdd); free_config_vddcx: regulator_set_voltage(hsusb_vdd, vdd_val[motg->vdd_type][VDD_NONE], vdd_val[motg->vdd_type][VDD_MAX]); devote_xo_handle: clk_disable_unprepare(motg->pclk); if (!IS_ERR(motg->xo_clk)) clk_disable_unprepare(motg->xo_clk); else msm_xo_mode_vote(motg->xo_handle, MSM_XO_MODE_OFF); free_xo_handle: if (!IS_ERR(motg->xo_clk)) clk_put(motg->xo_clk); else msm_xo_put(motg->xo_handle); free_regs: iounmap(motg->regs); disable_sleep_clk: if (!IS_ERR(motg->sleep_clk)) clk_disable_unprepare(motg->sleep_clk); put_pclk: clk_put(motg->pclk); put_core_clk: clk_put(motg->core_clk); put_clk: if (!IS_ERR(motg->clk)) clk_put(motg->clk); devote_bus_bw: if (motg->bus_perf_client) { msm_otg_bus_vote(motg, USB_NO_PERF_VOTE); msm_bus_scale_unregister_client(motg->bus_perf_client); } return ret; } static int __devexit msm_otg_remove(struct platform_device *pdev) { struct msm_otg *motg = platform_get_drvdata(pdev); struct usb_phy *phy = &motg->phy; int cnt = 0; if (phy->otg->host || phy->otg->gadget) return -EBUSY; if (!motg->ext_chg_device) { device_destroy(motg->ext_chg_class, motg->ext_chg_dev); cdev_del(&motg->ext_chg_cdev); class_destroy(motg->ext_chg_class); unregister_chrdev_region(motg->ext_chg_dev, 1); } if (pdev->dev.of_node) msm_otg_setup_devices(pdev, motg->pdata->mode, false); if (motg->pdata->otg_control == OTG_PMIC_CONTROL) pm8921_charger_unregister_vbus_sn(0); msm_otg_mhl_register_callback(motg, NULL); msm_otg_debugfs_cleanup(); cancel_delayed_work_sync(&motg->chg_work); cancel_delayed_work_sync(&motg->pmic_id_status_work); cancel_delayed_work_sync(&motg->suspend_work); cancel_work_sync(&motg->sm_work); pm_runtime_resume(&pdev->dev); device_init_wakeup(&pdev->dev, 0); pm_runtime_disable(&pdev->dev); wake_lock_destroy(&motg->wlock); wake_lock_destroy(&motg->cable_detect_wlock); msm_hsusb_mhl_switch_enable(motg, 0); if (motg->pdata->pmic_id_irq) free_irq(motg->pdata->pmic_id_irq, motg); usb_set_transceiver(NULL); free_irq(motg->irq, motg); if ((motg->pdata->phy_type == SNPS_28NM_INTEGRATED_PHY) && (motg->pdata->mpm_dpshv_int || motg->pdata->mpm_dmshv_int)) device_remove_file(&pdev->dev, &dev_attr_dpdm_pulldown_enable); if (motg->pdata->otg_control == OTG_PHY_CONTROL && motg->pdata->mpm_otgsessvld_int) msm_mpm_enable_pin(motg->pdata->mpm_otgsessvld_int, 0); if (motg->pdata->mpm_dpshv_int) msm_mpm_enable_pin(motg->pdata->mpm_dpshv_int, 0); if (motg->pdata->mpm_dmshv_int) msm_mpm_enable_pin(motg->pdata->mpm_dmshv_int, 0); ulpi_read(phy, 0x14); ulpi_write(phy, 0x08, 0x09); writel(readl(USB_PORTSC) | PORTSC_PHCD, USB_PORTSC); while (cnt < PHY_SUSPEND_TIMEOUT_USEC) { if (readl(USB_PORTSC) & PORTSC_PHCD) break; udelay(1); cnt++; } if (cnt >= PHY_SUSPEND_TIMEOUT_USEC) dev_err(phy->dev, "Unable to suspend PHY\n"); clk_disable_unprepare(motg->pclk); clk_disable_unprepare(motg->core_clk); if (!IS_ERR(motg->xo_clk)) { clk_disable_unprepare(motg->xo_clk); clk_put(motg->xo_clk); } else { msm_xo_put(motg->xo_handle); } if (!IS_ERR(motg->sleep_clk)) clk_disable_unprepare(motg->sleep_clk); msm_hsusb_ldo_enable(motg, USB_PHY_REG_OFF); msm_hsusb_ldo_init(motg, 0); regulator_disable(hsusb_vdd); regulator_set_voltage(hsusb_vdd, vdd_val[motg->vdd_type][VDD_NONE], vdd_val[motg->vdd_type][VDD_MAX]); iounmap(motg->regs); pm_runtime_set_suspended(&pdev->dev); clk_put(motg->pclk); if (!IS_ERR(motg->clk)) clk_put(motg->clk); clk_put(motg->core_clk); if (motg->bus_perf_client) { msm_otg_bus_vote(motg, USB_NO_PERF_VOTE); msm_bus_scale_unregister_client(motg->bus_perf_client); } return 0; } #ifdef CONFIG_PM_RUNTIME static int msm_otg_runtime_idle(struct device *dev) { struct msm_otg *motg = dev_get_drvdata(dev); struct usb_phy *phy = &motg->phy; dev_dbg(dev, "OTG runtime idle\n"); if (phy->state == OTG_STATE_UNDEFINED) return -EAGAIN; if (motg->ext_chg_active) { dev_dbg(dev, "Deferring LPM\n"); pm_schedule_suspend(dev, 3000); return -EAGAIN; } return 0; } static int msm_otg_runtime_suspend(struct device *dev) { struct msm_otg *motg = dev_get_drvdata(dev); dev_dbg(dev, "OTG runtime suspend\n"); return msm_otg_suspend(motg); } static int msm_otg_runtime_resume(struct device *dev) { struct msm_otg *motg = dev_get_drvdata(dev); dev_dbg(dev, "OTG runtime resume\n"); pm_runtime_get_noresume(dev); return msm_otg_resume(motg); } #endif #ifdef CONFIG_PM_SLEEP static int msm_otg_pm_suspend(struct device *dev) { int ret = 0; struct msm_otg *motg = dev_get_drvdata(dev); dev_dbg(dev, "OTG PM suspend\n"); atomic_set(&motg->pm_suspended, 1); ret = msm_otg_suspend(motg); if (ret) atomic_set(&motg->pm_suspended, 0); return ret; } static int msm_otg_pm_resume(struct device *dev) { int ret = 0; struct msm_otg *motg = dev_get_drvdata(dev); dev_dbg(dev, "OTG PM resume\n"); atomic_set(&motg->pm_suspended, 0); if (motg->async_int || motg->sm_work_pending) { pm_runtime_get_noresume(dev); ret = msm_otg_resume(motg); pm_runtime_disable(dev); pm_runtime_set_active(dev); pm_runtime_enable(dev); if (motg->sm_work_pending) { motg->sm_work_pending = false; queue_work(system_nrt_wq, &motg->sm_work); } } return ret; } #endif #ifdef CONFIG_PM static const struct dev_pm_ops msm_otg_dev_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(msm_otg_pm_suspend, msm_otg_pm_resume) SET_RUNTIME_PM_OPS(msm_otg_runtime_suspend, msm_otg_runtime_resume, msm_otg_runtime_idle) }; #endif #ifndef CONFIG_USB_DWC3_MSM int64_t htc_qpnp_adc_get_usbid_adc(void) { struct msm_otg *motg = the_msm_otg; struct qpnp_vadc_result result; int err = 0, adc = 0; if (!the_msm_otg) return -EAGAIN; if(!motg->vadc_chip) { motg->vadc_chip = qpnp_get_vadc(motg->phy.dev, "usb_id"); if (IS_ERR(motg->vadc_chip)) { err = PTR_ERR(motg->vadc_chip); printk(KERN_INFO "[USB] %s : qpnp_get_vadc return error code %d\n",__func__,err); motg->vadc_chip = NULL; return -EAGAIN; } } printk(KERN_INFO "[USB] %s : vadc_chip %x\n",__func__,(unsigned int)motg->vadc_chip); err = qpnp_vadc_read(motg->vadc_chip ,P_MUX7_1_1, &result); if (err < 0) { pr_info("[CABLE] %s: get adc fail, err %d\n", __func__, err); return err; } adc = result.physical; adc /= 1000; pr_info("[CABLE] chan=%d, adc_code=%d, measurement=%lld, \ physical=%lld translate voltage %d\n", result.chan, result.adc_code, result.measurement, result.physical, adc); return adc; } #endif static struct of_device_id msm_otg_dt_match[] = { { .compatible = "qcom,hsusb-otg", }, {} }; static struct platform_driver msm_otg_driver = { .remove = __devexit_p(msm_otg_remove), .driver = { .name = DRIVER_NAME, .owner = THIS_MODULE, #ifdef CONFIG_PM .pm = &msm_otg_dev_pm_ops, #endif .of_match_table = msm_otg_dt_match, }, }; static int __init msm_otg_init(void) { return platform_driver_probe(&msm_otg_driver, msm_otg_probe); } static void __exit msm_otg_exit(void) { platform_driver_unregister(&msm_otg_driver); } module_init(msm_otg_init); module_exit(msm_otg_exit); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("MSM USB transceiver driver");
#!/bin/bash # # CLI client for interacting with Freischutz RESTful APIs # # see https://gitlab.com/tdely/freischutz/ Freischutz on GitLab # # author Tobias Dély (tdely) <cleverhatcamouflage@gmail.com> # copyright 2017-present Tobias Dély # license https://directory.fsf.org/wiki/License:BSD-3-Clause BSD-3-Clause # set -o errexit set -o pipefail set -o nounset VERSION='0.9.1' content_type='text/plain' method='GET' algorithm='sha256' id='' key='' data='' ext='' token='' basic_auth=false hawk=false bearer=false extra_header='' verbose=false target='' time=$(date +%s) function display_help() { echo "$(basename ${BASH_SOURCE[0]}) -m <STR> [-d <JSON>][-t] <STR> TARGET" echo " -a STR hash algorithm to use for Hawk, default sha256" echo " -B use basic authentication" echo " -c STR content-type, default text/plain" echo " -d STR data/payload to send" echo " -e STR optional ext value for Hawk" echo " -H use Hawk authentication" echo " -h print this help message and exit" echo " -i INT user id to use with request" echo " -k STR key/password for authentication" echo " -m STR http request method to use" echo " -t display timing info:" echo " - response time: from request until first response byte received" echo " - operation time: from request until last response byte received" echo " -T STR use bearer token authentication" echo " -V verbose output" echo " -v print version and exit" } function display_version() { echo "$(basename ${BASH_SOURCE[0]}) version ${VERSION}" } function hawk_build() { # Parse target local proto=$(echo ${target} | grep -oP "(^https|http)") local host=$(echo ${target} | grep -oP "(?<=${proto}:\\/\\/)([^\\/:]+)") local port=$(echo ${target} | grep -oP "(?<=${host}:)([^\\/]+)" || true) [[ -z "${port}" ]] && port_string='' || port_string=":${port}" local uri=$(echo ${target} | grep -oP "(?<=${host}${port_string})(\\/.+)") local nonce=$(cat /dev/urandom|tr -dc 'a-zA-Z0-9'|fold -w 6|head -n 1) if [ -z "${port}" ]; then if [ "${proto}" = 'http' ]; then port=80 elif [ "${proto}" = 'https' ]; then port=443 else echo 'unknown protocol specified' >&2 exit 1 fi fi # Build Hawk payload string local payload="hawk.1.payload\n" payload+="${content_type}\n" payload+="${data}\n" local payload_hash=$(echo -ne "${payload}"|openssl dgst -${algorithm} -binary|base64 -w0) if [ "$ext" != "" ]; then ext="alg=${algorithm};${ext}" else ext="alg=${algorithm}" fi # Build Hawk header string for MAC local message="hawk.1.header\n" message+="${time}\n" message+="${nonce}\n" message+="${method}\n" message+="${uri}\n" message+="${host}\n" message+="${port}\n" message+="${payload_hash}\n" message+="${ext}\n" local mac=$(echo -ne ${message}|openssl dgst -${algorithm} -hmac ${key} -binary|base64 -w0) if [ ${verbose} = true ]; then echo "-------------------------------------------" echo -ne "${payload}" echo "-------------------------------------------" echo -ne "${message}" echo "-------------------------------------------" echo "MAC:" echo -e "${mac}\n" fi extra_header="Authorization: Hawk id=\"${id}\", ts=\"${time}\", nonce=\"${nonce}\", mac=\"${mac}\", hash=\"${payload_hash}\", ext=\"${ext}\"" } # getopt index variable OPTIND=1 while getopts ":a:Bc:d:e:Hhi:k:m:tT:Vv" opt; do case ${opt} in a) algorithm="${OPTARG}" ;; B) basic_auth=true hawk=false bearer=false ;; c) content_type="${OPTARG}" ;; d) data="${OPTARG}" ;; e) ext="${OPTARG}" ;; H) hawk=true basic_auth=false bearer=false ;; h) display_help exit 0 ;; i) id="${OPTARG}" ;; k) key="${OPTARG}" ;; m) method="${OPTARG^^}" ;; t) timing="\n\n--TIMING DETAILS\nResponse time: %{time_starttransfer}\nOperation time: %{time_total}\n" ;; T) basic_auth=false hawk=false bearer=true token="${OPTARG}" ;; V) verbose=true ;; v) display_version exit 0 ;; \?) echo "Invalid option: -${OPTARG}" >&2 display_help exit 1 ;; :) echo "Option -${OPTARG} requires an argument." >&2 display_help exit 1 ;; esac done # Remove all option arguments shift $(($OPTIND - 1)) if [ -z "${method}" ]; then echo "No method specified" >&2 display_help exit 1 fi if [ "${#}" = 0 ]; then echo "No target specified" >&2 display_help exit 1 fi if [ "${#}" -gt 1 ]; then echo "Too many arguments" >&2 display_help exit 1 fi # Target is first non-option argument target="${1}" if [ ${verbose} = true ]; then echo -e "\n--REQUEST DETAILS" fi if [ ${basic_auth} = true ]; then if [ -z "${id}" ] || [ -z "${key}" ]; then echo "Basic authentication requires -i and -k to be set" fi fi if [ ${hawk} = true ]; then if [ -z "${id}" ] || [ -z "${key}" ]; then echo "Hawk requires -i and -k to be set" fi hawk_build fi # Use tmp files for payload and formatting for timing # easiest way since curl is difficult about whitespace TMP_DATA=$(mktemp) TMP_FORMAT=$(mktemp) echo "${data}" > ${TMP_DATA} echo "${timing:-}" > ${TMP_FORMAT} details='' if [ ${verbose} = true ]; then details="-i -w @${TMP_FORMAT}" echo "--BEGIN CURL" fi # Send HTTP request if [ ${hawk} = true ]; then curl ${details} -d @${TMP_DATA} -X "${method}" -H "Content-Type: ${content_type}" -H "${extra_header}" $target elif [ ${basic_auth} = true ]; then curl ${details} -d @${TMP_DATA} -X "${method}" -H "Content-Type: ${content_type}" -u "${id}:${key}" $target elif [ ${bearer} = true ]; then curl ${details} -d @${TMP_DATA} -X "${method}" -H "Content-Type: ${content_type}" -H "Authorization: Bearer ${token}" $target else curl ${details} -d @${TMP_DATA} -X "${method}" -H "Content-Type: ${content_type}" $target fi if [ ${verbose} = true ]; then echo -e "\n--END CURL" fi echo "" # Clean up rm ${TMP_DATA} rm ${TMP_FORMAT}
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __I_CURSOR_CONTROL_H_INCLUDED__ #define __I_CURSOR_CONTROL_H_INCLUDED__ #include "IReferenceCounted.h" #include "position2d.h" #include "rect.h" namespace irr { namespace gui { class IGUISpriteBank; //! Default icons for cursors enum ECURSOR_ICON { // Following cursors might be system specific, or might use an Irrlicht icon-set. No guarantees so far. ECI_NORMAL, // arrow ECI_CROSS, // Crosshair ECI_HAND, // Hand ECI_HELP, // Arrow and question mark ECI_IBEAM, // typical text-selection cursor ECI_NO, // should not click icon ECI_WAIT, // hourclass ECI_SIZEALL, // arrow in all directions ECI_SIZENESW, // resizes in direction north-east or south-west ECI_SIZENWSE, // resizes in direction north-west or south-east ECI_SIZENS, // resizes in direction north or south ECI_SIZEWE, // resizes in direction west or east ECI_UP, // up-arrow // Implementer note: Should we add system specific cursors, which use guaranteed the system icons, // then I would recommend using a naming scheme like ECI_W32_CROSS, ECI_X11_CROSSHAIR and adding those // additionally. ECI_COUNT // maximal of defined cursors. Note that higher values can be created at runtime }; //! Names for ECURSOR_ICON const c8* const GUICursorIconNames[ECI_COUNT+1] = { "normal", "cross", "hand", "help", "ibeam", "no", "wait", "sizeall", "sizenesw", "sizenwse", "sizens", "sizewe", "sizeup", 0 }; //! structure used to set sprites as cursors. struct SCursorSprite { SCursorSprite() : SpriteBank(0), SpriteId(-1) { } SCursorSprite( gui::IGUISpriteBank * spriteBank, s32 spriteId, const core::position2d<s32> &hotspot=(core::position2d<s32>(0,0)) ) : SpriteBank(spriteBank), SpriteId(spriteId), HotSpot(hotspot) { } IGUISpriteBank * SpriteBank; s32 SpriteId; core::position2d<s32> HotSpot; }; //! platform specific behavior flags for the cursor enum ECURSOR_PLATFORM_BEHAVIOR { //! default - no platform specific behavior ECPB_NONE = 0, //! On X11 try caching cursor updates as XQueryPointer calls can be expensive. /** Update cursor positions only when the irrlicht timer has been updated or the timer is stopped. This means you usually get one cursor update per device->run() which will be fine in most cases. See this forum-thread for a more detailed explanation: http://irrlicht.sourceforge.net/forum/viewtopic.php?f=7&t=45525 */ ECPB_X11_CACHE_UPDATES = 1 }; //! Interface to manipulate the mouse cursor. class ICursorControl : public virtual IReferenceCounted { public: //! Changes the visible state of the mouse cursor. /** \param visible: The new visible state. If true, the cursor will be visible, if false, it will be invisible. */ virtual void setVisible(bool visible) = 0; //! Returns if the cursor is currently visible. /** \return True if the cursor is visible, false if not. */ virtual bool isVisible() const = 0; //! Sets the new position of the cursor. /** The position must be between (0.0f, 0.0f) and (1.0f, 1.0f), where (0.0f, 0.0f) is the top left corner and (1.0f, 1.0f) is the bottom right corner of the render window. \param pos New position of the cursor. */ virtual void setPosition(const core::position2d<f32> &pos) = 0; //! Sets the new position of the cursor. /** The position must be between (0.0f, 0.0f) and (1.0f, 1.0f), where (0.0f, 0.0f) is the top left corner and (1.0f, 1.0f) is the bottom right corner of the render window. \param x New x-coord of the cursor. \param y New x-coord of the cursor. */ virtual void setPosition(f32 x, f32 y) = 0; //! Sets the new position of the cursor. /** \param pos: New position of the cursor. The coordinates are pixel units. */ virtual void setPosition(const core::position2d<s32> &pos) = 0; //! Sets the new position of the cursor. /** \param x New x-coord of the cursor. The coordinates are pixel units. \param y New y-coord of the cursor. The coordinates are pixel units. */ virtual void setPosition(s32 x, s32 y) = 0; //! Returns the current position of the mouse cursor. /** \return Returns the current position of the cursor. The returned position is the position of the mouse cursor in pixel units. */ virtual const core::position2d<s32>& getPosition() = 0; //! Returns the current position of the mouse cursor. /** \return Returns the current position of the cursor. The returned position is a value between (0.0f, 0.0f) and (1.0f, 1.0f), where (0.0f, 0.0f) is the top left corner and (1.0f, 1.0f) is the bottom right corner of the render window. */ virtual core::position2d<f32> getRelativePosition() = 0; //! Sets an absolute reference rect for setting and retrieving the cursor position. /** If this rect is set, the cursor position is not being calculated relative to the rendering window but to this rect. You can set the rect pointer to 0 to disable this feature again. This feature is useful when rendering into parts of foreign windows for example in an editor. \param rect: A pointer to an reference rectangle or 0 to disable the reference rectangle.*/ virtual void setReferenceRect(core::rect<s32>* rect=0) = 0; //! Sets the active cursor icon /** Setting cursor icons is so far only supported on Win32 and Linux */ virtual void setActiveIcon(ECURSOR_ICON iconId) {} //! Gets the currently active icon virtual ECURSOR_ICON getActiveIcon() const { return gui::ECI_NORMAL; } //! Add a custom sprite as cursor icon. /** \return Identification for the icon */ virtual ECURSOR_ICON addIcon(const gui::SCursorSprite& icon) { return gui::ECI_NORMAL; } //! replace a cursor icon. /** Changing cursor icons is so far only supported on Win32 and Linux Note that this only changes the icons within your application, system cursors outside your application will not be affected. */ virtual void changeIcon(ECURSOR_ICON iconId, const gui::SCursorSprite& sprite) {} //! Return a system-specific size which is supported for cursors. Larger icons will fail, smaller icons might work. virtual core::dimension2di getSupportedIconSize() const { return core::dimension2di(0,0); } //! Set platform specific behavior flags. virtual void setPlatformBehavior(ECURSOR_PLATFORM_BEHAVIOR behavior) {} //! Return platform specific behavior. /** \return Behavior set by setPlatformBehavior or ECPB_NONE for platforms not implementing specific behaviors. */ virtual ECURSOR_PLATFORM_BEHAVIOR getPlatformBehavior() const { return ECPB_NONE; } }; } // end namespace gui } // end namespace irr #endif
<?php /** * @version 1.0.0 * @package com_dtax * @copyright Copyright (C) 2016 METIK Marketing, LLC. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @author Freddy Flores <fflores@metikmarketing.com> - https://www.metikmarketing.com */ // No direct access defined('_JEXEC') or die; use Joomla\Utilities\ArrayHelper; /** * links Table class * * @since 1.6 */ class DTaxTablelink extends JTable { /** * Constructor * * @param JDatabase &$db A database connector object */ public function __construct(&$db) { parent::__construct('#__dtax_links', 'id', $db); } /** * Overloaded bind function to pre-process the params. * * @param array $array Named array * @param mixed $ignore Optional array of properties to ignore * * @return null|string null is operation was satisfactory, otherwise returns an error * * @see JTable:bind * @since 1.5 */ public function bind($array, $ignore = '') { if(!$array['created_by']) $array['created_by'] = JFactory::getUser ()->id; <<<<<<< HEAD if(!$array['created'] || $array['created'] = '0000-00-00 00:00:00') $array['created'] = JFactory::getDate ()->toSql (); ======= >>>>>>> 6da42b430d55062734b64ec082d4c7d1c81592e9 if ($array['id'] == 0) { $array['created_by'] = JFactory::getUser()->id; } $task = JFactory::getApplication()->input->get('task'); if ($task == 'apply' || $task == 'save') { $array['date_updated'] = JFactory::getDate()->toSql(); } $input = JFactory::getApplication()->input; $task = $input->getString('task', ''); if (isset($array['params']) && is_array($array['params'])) { $registry = new JRegistry; $registry->loadArray($array['params']); $array['params'] = (string) $registry; } if (isset($array['metadata']) && is_array($array['metadata'])) { $registry = new JRegistry; $registry->loadArray($array['metadata']); $array['metadata'] = (string) $registry; } if (!JFactory::getUser()->authorise('core.admin', 'com_dtax.links.' . $array['id'])) { $actions = JAccess::getActions('com_dtax', 'links'); $default_actions = JAccess::getAssetRules('com_dtax.links.' . $array['id'])->getData(); $array_jaccess = array(); foreach ($actions as $action) { $array_jaccess[$action->name] = $default_actions[$action->name]; } $array['rules'] = $this->JAccessRulestoArray($array_jaccess); } // Bind the rules for ACL where supported. if (isset($array['rules']) && is_array($array['rules'])) { $this->setRules($array['rules']); } return parent::bind($array, $ignore); } /** * This function convert an array of JAccessRule objects into an rules array. * * @param array $jaccessrules An array of JAccessRule objects. * * @return array */ private function JAccessRulestoArray($jaccessrules) { $rules = array(); foreach ($jaccessrules as $action => $jaccess) { $actions = array(); foreach ($jaccess->getData() as $group => $allow) { $actions[$group] = ((bool) $allow); } $rules[$action] = $actions; } return $rules; } /** * Overloaded check function * * @return bool */ public function check() { // If there is an ordering column and this is a new row then get the next ordering value if (property_exists($this, 'ordering') && $this->id == 0) { $this->ordering = self::getNextOrder(); } return parent::check(); } /** * Method to set the publishing state for a row or list of rows in the database * table. The method respects checked out rows by other users and will attempt * to checkin rows that it can after adjustments are made. * * @param mixed $pks An optional array of primary key values to update. If * not set the instance property value is used. * @param integer $state The publishing state. eg. [0 = unpublished, 1 = published] * @param integer $userId The user id of the user performing the operation. * * @return boolean True on success. * * @since 1.0.4 * * @throws Exception */ public function publish($pks = null, $state = 1, $userId = 0) { // Initialise variables. $k = $this->_tbl_key; // Sanitize input. JArrayHelper::toInteger($pks); $userId = (int) $userId; $state = (int) $state; // If there are no primary keys set check to see if the instance key is set. if (empty($pks)) { if ($this->$k) { $pks = array($this->$k); } // Nothing to set publishing state on, return false. else { throw new Exception(500, JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED')); } } // Build the WHERE clause for the primary keys. $where = $k . '=' . implode(' OR ' . $k . '=', $pks); // Determine if there is checkin support for the table. if (!property_exists($this, 'checked_out') || !property_exists($this, 'checked_out_time')) { $checkin = ''; } else { $checkin = ' AND (checked_out = 0 OR checked_out = ' . (int) $userId . ')'; } // Update the publishing state for rows with the given primary keys. $this->_db->setQuery( 'UPDATE `' . $this->_tbl . '`' . ' SET `state` = ' . (int) $state . ' WHERE (' . $where . ')' . $checkin ); $this->_db->execute(); // If checkin is supported and all rows were adjusted, check them in. if ($checkin && (count($pks) == $this->_db->getAffectedRows())) { // Checkin each row. foreach ($pks as $pk) { $this->checkin($pk); } } // If the JTable instance value is in the list of primary keys that were set, set the instance. if (in_array($this->$k, $pks)) { $this->state = $state; } return true; } /** * Define a namespaced asset name for inclusion in the #__assets table * * @return string The asset name * * @see JTable::_getAssetName */ protected function _getAssetName() { $k = $this->_tbl_key; return 'com_dtax.links.' . (int) $this->$k; } /** * Delete a record according to its primary key * * @param mixed $pk Primary key value to delete. Optional. * * @return bool */ public function delete($pk = null) { $this->load($pk); $result = parent::delete($pk); if ($result) { } return $result; } }
require 'spec_helper' # TODO: truncate the redis store and/or stub it beforehand describe 'Hyperion' do it "should work for basic set/fetch" do string1 = random_string f = DefaultKey.new f.key = 'test' f.content = string1 f.save f2 = DefaultKey.find('test') f2.content.should == f.content f3 = IndexedObject.find(string1) f3.should == nil end it "should be able to index a single attribute" do string1 = random_string f = IndexedObject.new f.content = string1 f.other_content = 'zero_cool' f.key = 'testery' f.save f2 = IndexedObject.first(:other_content => 'zero_cool') f2.content.should == f.content f3 = IndexedObject.find('testery') f3.content.should == f.content end it "should take objects at instantiation time" do string1 = random_string n=NoKey.new(:content => string1) n.save n2 = NoKey.find(n.id) n2.content.should == string1 end it "should autogenerate keys" do string1 = random_string n=NoKey.new n.content = string1 n.save n2 = NoKey.find(n.id) n2.content.should == string1 end it 'should autoincrement keys whether specified or not' do end it "should be able to index multiple attributes" do string1 = random_string f = IndexedObject.new f.content = string1 f.other_content = 'zero_cool' f.key = 'testery' f.save f2 = IndexedObject.first(:other_content => 'zero_cool') f2.content.should == f.content f3 = IndexedObject.find('testery') f3.content.should == f.content f4 = IndexedObject.first(:other_content => 'zero_cool', :content => string1) f4.content.should == f.content end it "shouldn't put an index in for an empty value" do string1 = random_string f = IndexedObject.new f.content = string1 f.save f2 = IndexedObject.first(:other_content => nil) f2.should == nil end it "shouldn't matter what order your indexes are specified" do end it "should not have concurrency issues" do end it "should be able to reindex objects" do end it "should update indexes" do end it 'should be OK with key collision' do end it "should die if there's no redis server around" do end it "should allow crazy lengths and contents for both keys and values" do end end
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop //--------------------------------------------------------------------------- USEFORM("UnitFormTronCollectionMenu.cpp", FormTronCollectionMenu); USEFORM("UnitFormClassicTronAbout.cpp", FormClassicTronAbout); USEFORM("UnitFormClassicTronGame.cpp", FormClassicTronGame); USEFORM("UnitFormClassicTronMenu.cpp", FormClassicTronMenu); USEFORM("UnitFormSuperTronAbout.cpp", FormSuperTronAbout); USEFORM("UnitFormSuperTronGame.cpp", FormSuperTronGame); USEFORM("UnitFormSuperTronMenu.cpp", FormSuperTronMenu); USEFORM("UnitFormChart.cpp", FormChart); USEFORM("UnitFormPressKey.cpp", FormPressKey); USEFORM("UnitFormSelectColor.cpp", FormSelectColor); //--------------------------------------------------------------------------- WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { try { Application->Initialize(); Application->Title = "The Tron Collection"; Application->CreateForm(__classid(TFormTronCollectionMenu), &FormTronCollectionMenu); Application->Run(); } catch (Exception &exception) { Application->ShowException(&exception); } catch (...) { try { throw Exception(""); } catch (Exception &exception) { Application->ShowException(&exception); } } return 0; } //---------------------------------------------------------------------------
import os from nose.tools import assert_true, assert_raises, nottest from zabby.core.exceptions import WrongArgumentError from zabby.core.six import integer_types from zabby.core.utils import SIZE_CONVERSION_MODES, write_to_file # assert_is_instance appeared in python 3.2 and was backported to 2.7 try: from nose.tools import assert_is_instance except ImportError: def assert_is_instance(obj, cls, msg=None): assert_true(isinstance(obj, cls), msg) # assert_not_in and assert_less appeared in python 3.1 and was backported to 2.7 try: from nose.tools import (assert_not_in, assert_less, assert_less_equal, assert_in, assert_greater) except ImportError: def assert_not_in(member, collection, msg=None): assert_true(member not in collection, msg) def assert_less(a, b, msg=None): assert_true(a < b, msg) def assert_less_equal(a, b, msg=None): assert_true(a <= b, msg) def assert_in(member, collection, msg=None): assert_true(member in collection, msg) def assert_greater(a, b, msg=None): assert_true(a > b, msg) def ensure_removed(file_path): if os.path.exists(file_path): os.remove(file_path) def ensure_contains_only_formatted_lines(file_path, line_format, n=1): ensure_removed(file_path) for i in range(n): write_to_file(file_path, line_format.format(i)) class FakeThread: def __init__(self, target=None): self._target = target def start(self): self._target() @nottest class TestSizeFunction(): def test_throws_exception_on_wrong_arguments(self): assert_raises(WrongArgumentError, self.function_under_test, self.target, 'wrong') def test_gathers_information_from_host_os(self): self.function_under_test(self.target, host_os=self.host_os) self.host_os_function.assert_called_with(self.target) def test_different_modes_produce_different_results(self): results = list() for conversion_mode in SIZE_CONVERSION_MODES: result = self.function_under_test(self.target, conversion_mode, self.host_os) assert_not_in(result, results) results.append(result) def test_all_modes_produce_positive_results(self): for conversion_mode in SIZE_CONVERSION_MODES: result = self.function_under_test(self.target, conversion_mode, self.host_os) assert_less_equal(0, result)
var zlib = require('zlib'); var async = require('async'); var dirWalk = require('./dirWalk'); var fs = require('fs'); var events = require('events'); var _ = require('underscore'); /** * */ module.exports = { /** * Convienence method for setting CORS options * @param {object} options { origin, maxage, customheaders } * @param {Function} callback Function will be passed (error, reply) on completion */ setContainerCORS : function(options, callback) { if(!this.core.processArgs({ required : ['container'] }, arguments)) { return callback({error:"Bad Arguments"}); } var headers = {}; if (options.origin) { headers['X-Container-Meta-Access-Control-Allow-Origin'] = options.origin; } if (options.maxage) { headers['X-Container-Meta-Access-Control-Max-Age'] = options.maxage; } if (options.customheaders) { headers['X-Container-Meta-Access-Control-Allow-Headers'] = options.customheaders; } return this.editContainerMeta({ container : options.container, meta : headers }, callback); }, enableAccessLog : function(options, callback) { if(!this.core.processArgs({ required : ['container'], default : 'container' }, arguments)) { return callback({error:"Bad Arguments"}); } return this.editContainerMeta({ container: options.container, meta: { 'X-Container-Meta-Access-Log-Delivery' : 'TRUE' } }, callback); }, disableAccessLog : function(options, callback) { if(!this.core.processArgs({ required : ['container'], default : 'container' }, arguments)) { return callback({error:"Bad Arguments"}); } return this.editContainerMeta({ container: options.container, meta: { 'X-Container-Meta-Access-Log-Delivery' : 'FALSE' } }, callback); }, putCompressedObject : function(options, callback) { var self = this; if (!options.compress) return self.putObject(options, callback); if (options.data) { if(options.data.length <= 0) { return callback({Error: "Empty Buffer"}); } zlib.gzip(options.data, function(err, compressedObject) { if (err) return callback({error: err}); options.data = compressedObject; if (!options.headers) options.headers = {}; options.headers['Content-Encoding'] = 'gzip'; return self.putObject(options, callback); }); } else { //TODO: pipe to stream } }, copyObjectWithHeaders : function(options, callback) { if(!this.core.processArgs({ required : ['sourceObject','sourceContainer','destinationObject','destinationContainer'] }, arguments)) { return callback({error:"Bad Arguments"}); } var self = this; self.getObjectMeta({ container : options.sourceContainer, object : options.sourceObject }, function(err, reply) { if (err) return callback({ Message: "failed to get object meta", Error: err }); var headers = _.extend({}, _.omit(reply, ['last-modified', 'etag', 'x-timestamp', 'x-trans-id']), options.headers || {}); self.copyObject({ headers : headers, sourceObject : options.sourceObject, sourceContainer : options.sourceContainer, destinationObject : options.destinationObject, destinationContainer : options.destinationContainer }, function(err, reply) { if (err) return callback({ Message: "failed to copy object", Error: err }); return callback(null, reply); }); }); }, emptyContainer : function(options, callback) { if(!this.core.processArgs({ default : "container" }, arguments)) { return callback({error:"Bad Arguments"}); } var self = this; (function cleanObjects() { self.listObjects(options.container, function(err, reply) { if(err) { return callback(err); } if((!reply.length) || reply.length <= 0) { return callback(null, {message:"Container Empty"}); } var objList = reply; (function popDelete(fObj){ if (!fObj) return cleanObjects(); self.deleteObject({ object : fObj.name, container : options.container }, function(err, reply) { if(err) { return callback(err); } else if(objList.length > 0) { return popDelete(objList.pop());} else { return cleanObjects(); } }); })(objList.pop()); }); })(); }, syncDir : function(options, callback) { if(!this.core.processArgs({ required : ['container', 'directory'] }, arguments)) { return callback({error:"Bad Arguments"}); } var emitter = new events.EventEmitter(); var dir = options.directory; var container = options.container; var self = this; dirWalk.parallel(dir, function(err, files){ if(err) return callback(err); //copy all the files into the cloud async.eachLimit(files, 15, function(file, cb){ //Iterator Function var remote = file.replace(dir,"").replace(/^\//,""); fs.readFile(file, function(err,data){ if(err) { return cb(err); } var reqObj = { container : container, object : remote, data : data, compress : true, headers : { "Access-Control-Allow-Origin" : "*" } }; self.putCompressedObject(reqObj, function(err, reply) { if(err) return cb(err); emitter.emit('sync', { containter : container, local : file, remote : remote }); return cb(); }); }); }, function(err) { //Finished Function if(err) return callback(err); emitter.emit('done'); return callback(null,files); } ); }); return emitter; } };
<?php /** * @copyright Copyright (C) 2015-2019 AIZAWA Hina * @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT * @author AIZAWA Hina <hina@fetus.jp> */ declare(strict_types=1); namespace app\assets; use jp3cki\yii2\flot\FlotAsset; use jp3cki\yii2\flot\FlotTimeAsset; use yii\web\AssetBundle; use yii\web\JqueryAsset; class EntireAgentAsset extends AssetBundle { public $sourcePath = '@app/resources/.compiled/stat.ink'; public $js = [ 'agent.js', ]; public $depends = [ ColorSchemeAsset::class, FlotAsset::class, FlotTimeAsset::class, JqueryAsset::class, ]; }
// SPDX-License-Identifier: GPL-2.0-only // Copyright (c) 2020 Intel Corporation /* * sof_sdw_hdmi - Helpers to handle HDMI from generic machine driver */ #include <linux/device.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/list.h> #include <sound/soc.h> #include <sound/soc-acpi.h> #include <sound/jack.h> #include "sof_sdw_common.h" #include "hda_dsp_common.h" struct hdmi_pcm { struct list_head head; struct snd_soc_dai *codec_dai; int device; }; int sof_sdw_hdmi_init(struct snd_soc_pcm_runtime *rtd) { struct mc_private *ctx = snd_soc_card_get_drvdata(rtd->card); struct snd_soc_dai *dai = asoc_rtd_to_codec(rtd, 0); struct hdmi_pcm *pcm; pcm = devm_kzalloc(rtd->card->dev, sizeof(*pcm), GFP_KERNEL); if (!pcm) return -ENOMEM; /* dai_link id is 1:1 mapped to the PCM device */ pcm->device = rtd->dai_link->id; pcm->codec_dai = dai; list_add_tail(&pcm->head, &ctx->hdmi_pcm_list); return 0; } #define NAME_SIZE 32 int sof_sdw_hdmi_card_late_probe(struct snd_soc_card *card) { struct mc_private *ctx = snd_soc_card_get_drvdata(card); struct hdmi_pcm *pcm; struct snd_soc_component *component = NULL; if (!ctx->idisp_codec) return 0; if (list_empty(&ctx->hdmi_pcm_list)) return -EINVAL; pcm = list_first_entry(&ctx->hdmi_pcm_list, struct hdmi_pcm, head); component = pcm->codec_dai->component; return hda_dsp_hdmi_build_controls(card, component); }
<!DOCTYPE html> <!-- Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ --> <html> <body> <details open> <summary>Summary 2</summary> <summary>Summary 1</summary> <p>This is the details 1.</p> </details> <details> <p>This is the details 2.</p> </details> </body> </html>
/* * Copyright (C) 2006 Michael Brown <mbrown@fensystems.co.uk>. * * 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 any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * You can also choose to distribute this program under the terms of * the Unmodified Binary Distribution Licence (as given in the file * COPYING.UBDL), provided that you have satisfied its requirements. */ FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); #include <stddef.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <assert.h> #include <ipxe/crypto.h> #include <ipxe/chap.h> /** @file * * CHAP protocol * */ /** * Initialise CHAP challenge/response * * @v chap CHAP challenge/response * @v digest Digest algorithm to use * @ret rc Return status code * * Initialises a CHAP challenge/response structure. This routine * allocates memory, and so may fail. The allocated memory must * eventually be freed by a call to chap_finish(). */ int chap_init ( struct chap_response *chap, struct digest_algorithm *digest ) { size_t state_len; void *state; assert ( chap->digest == NULL ); assert ( chap->digest_context == NULL ); assert ( chap->response == NULL ); DBG ( "CHAP %p initialising with %s digest\n", chap, digest->name ); state_len = ( digest->ctxsize + digest->digestsize ); state = malloc ( state_len ); if ( ! state ) { DBG ( "CHAP %p could not allocate %zd bytes for state\n", chap, state_len ); return -ENOMEM; } chap->digest = digest; chap->digest_context = state; chap->response = ( state + digest->ctxsize ); chap->response_len = digest->digestsize; digest_init ( chap->digest, chap->digest_context ); return 0; } /** * Add data to the CHAP challenge * * @v chap CHAP response * @v data Data to add * @v len Length of data to add */ void chap_update ( struct chap_response *chap, const void *data, size_t len ) { assert ( chap->digest != NULL ); assert ( chap->digest_context != NULL ); if ( ! chap->digest ) return; digest_update ( chap->digest, chap->digest_context, data, len ); } /** * Respond to the CHAP challenge * * @v chap CHAP response * * Calculates the final CHAP response value, and places it in @c * chap->response, with a length of @c chap->response_len. */ void chap_respond ( struct chap_response *chap ) { assert ( chap->digest != NULL ); assert ( chap->digest_context != NULL ); assert ( chap->response != NULL ); DBG ( "CHAP %p responding to challenge\n", chap ); if ( ! chap->digest ) return; digest_final ( chap->digest, chap->digest_context, chap->response ); } /** * Free resources used by a CHAP response * * @v chap CHAP response */ void chap_finish ( struct chap_response *chap ) { void *state = chap->digest_context; DBG ( "CHAP %p finished\n", chap ); free ( state ); memset ( chap, 0, sizeof ( *chap ) ); }
#ifndef CAFFE_MULTIBOX_LOSS_LAYER_HPP_ #define CAFFE_MULTIBOX_LOSS_LAYER_HPP_ #include <map> #include <utility> #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/bbox_util.hpp" #include "caffe/layers/loss_layer.hpp" namespace caffe { /** * @brief Perform MultiBox operations. Including the following: * * - decode the predictions. * - perform matching between priors/predictions and ground truth. * - use matched boxes and confidences to compute loss. * */ template <typename Dtype> class MultiBoxLossLayer : public LossLayer<Dtype> { public: explicit MultiBoxLossLayer(const LayerParameter& param) : LossLayer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "MultiBoxLoss"; } // bottom[0] stores the location predictions. // bottom[1] stores the confidence predictions. // bottom[2] stores the prior bounding boxes. // bottom[3] stores the ground truth bounding boxes. virtual inline int ExactNumBottomBlobs() const { return 4; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); // The internal localization loss layer. shared_ptr<Layer<Dtype> > loc_loss_layer_; LocLossType loc_loss_type_; float loc_weight_; // bottom vector holder used in Forward function. vector<Blob<Dtype>*> loc_bottom_vec_; // top vector holder used in Forward function. vector<Blob<Dtype>*> loc_top_vec_; // blob which stores the matched location prediction. Blob<Dtype> loc_pred_; // blob which stores the corresponding matched ground truth. Blob<Dtype> loc_gt_; // localization loss. Blob<Dtype> loc_loss_; // The internal confidence loss layer. shared_ptr<Layer<Dtype> > conf_loss_layer_; ConfLossType conf_loss_type_; // bottom vector holder used in Forward function. vector<Blob<Dtype>*> conf_bottom_vec_; // top vector holder used in Forward function. vector<Blob<Dtype>*> conf_top_vec_; // blob which stores the confidence prediction. Blob<Dtype> conf_pred_; // blob which stores the corresponding ground truth label. Blob<Dtype> conf_gt_; // confidence loss. Blob<Dtype> conf_loss_; MultiBoxLossParameter multibox_loss_param_; int num_classes_; bool share_location_; MatchType match_type_; float overlap_threshold_; bool use_prior_for_matching_; int background_label_id_; bool use_difficult_gt_; bool do_neg_mining_; float neg_pos_ratio_; float neg_overlap_; CodeType code_type_; bool encode_variance_in_target_; bool map_object_to_agnostic_; bool ignore_cross_boundary_bbox_; bool bp_inside_; MiningType mining_type_; int loc_classes_; int num_gt_; int num_; int num_priors_; int num_matches_; int num_conf_; vector<map<int, vector<int> > > all_match_indices_; vector<vector<int> > all_neg_indices_; // How to normalize the loss. LossParameter_NormalizationMode normalization_; }; } // namespace caffe #endif // CAFFE_MULTIBOX_LOSS_LAYER_HPP_
<?php namespace Guzzle\Service\Description; use Guzzle\Common\Collection; use Guzzle\Common\Inspector; /** * Data object holding the information of an API command * * @author Michael Dowling <michael@guzzlephp.org> */ class ApiCommand { /** * @var array Arguments */ protected $args = array(); /** * @var array Configuration data */ protected $config = array(); /** * Constructor * * @param array $config Array of configuration data using the following keys * string name Name of the command * tring doc Method documentation * string method HTTP method of the command * string path (optional) Path routing information of the command to include in the path * string min_args (optional) The minimum number of required args * bool can_batch (optional) Can the command be sent in a batch request * string class (optional) Concrete class that implements this command * array args Associative array of arguments for the command with each * argument containing the following keys: * * name - Argument name * type - Type of variable (boolean, integer, string, array, class name, etc...) * required - Whether or not the argument is required * default - Default value of the argument * doc - Documentation for the argument * min_length - Minimum argument length * max_length - Maximum argument length * location - One of query, path, header, or body * static - Whether or not the argument can be changed from this value * prepend - Text to prepend when adding this value to a location * append - Text to append when adding to a location */ public function __construct(array $config) { $this->config = $config; $this->config['name'] = isset($config['name']) ? trim($config['name']) : ''; $this->config['doc'] = isset($config['doc']) ? trim($config['doc']) : ''; $this->config['method'] = isset($config['method']) ? trim($config['method']) : ''; $this->config['min_args'] = isset($config['min_args']) ? min(100, max(0, $config['min_args'])) : 0; $this->config['can_batch'] = isset($config['can_batch']) ? $config['can_batch'] : ''; $this->config['path'] = isset($config['path']) ? trim($config['path']) : ''; $this->config['class'] = isset($config['class']) ? trim($config['class']) : 'Guzzle\\Service\\Command\\ClosureCommand'; // Build the argument array if (isset($config['args']) && is_array($config['args'])) { $this->args = array(); foreach ($config['args'] as $argName => $arg) { if ($arg instanceof Collection) { $this->args[$argName] = $arg; } else { $this->args[$argName] = new Collection($arg); } } } } /** * Get the arguments of the command * * @return array */ public function getArgs() { return $this->args; } /** * Get a single argument of the command * * @param string $argument Argument to retrieve * * @return Collection|null */ public function getArg($arg) { foreach ($this->args as $name => $a) { if ($name == $arg) { return $a; } } return null; } /** * Get the HTTP method of the command * * @return string */ public function getMethod() { return $this->config['method']; } /** * Get the concrete command class that implements this command * * @return string */ public function getConcreteClass() { return $this->config['class']; } /** * Get the name of the command * * @return string */ public function getName() { return $this->config['name']; } /** * Get the documentation for the command * * @return string */ public function getDoc() { return $this->config['doc']; } /** * Get the minimum number of required arguments * * @return int */ public function getMinArgs() { return $this->config['min_args']; } /** * Get the path routing information to append to the path of the generated * request * * @return string */ public function getPath() { return $this->config['path']; } /** * Check if the command can be sent in a batch request * * @return bool */ public function canBatch() { return $this->config['can_batch']; } /** * Validate that the supplied configuration options satisfy the constraints * of the command * * @param Collection $option Configuration options * * @return bool|array Returns TRUE on success or an array of error messages * on error */ public function validate(Collection $config) { $errors = array(); // Validate that the right number of args has been supplied if ($this->config['min_args'] && count($config) < $this->config['min_args']) { $errors[] = $this->config['name'] . ' requires at least ' . $this->config['min_args'] . ' arguments'; } $e = Inspector::getInstance()->validateConfig($this->args, $config, false); if (is_array($e)) { $errors = array_merge($errors, $e); } return count($errors) == 0 ? true : $errors; } }
from sys import argv script, filename = argv txt = open(filename) print "Here's your file %r:" %filename print txt.read() print "Type the filename again:" file_again = raw_input(">") txt_again = open(file_again) print txt_again.read()
/* * Copyright (c) 2017 Jean-Paul Etienne <fractalclone@gmail.com> * Copyright (c) 2017 Palmer Dabbelt <palmer@dabbelt.com> * * SPDX-License-Identifier: Apache-2.0 */ #include <init.h> #include "prci.h" /* Selects the 16MHz oscilator on the HiFive1 board, which provides a clock * that's accurate enough to actually drive serial ports off of. */ static int hifive1_clock_init(struct device *dev) { ARG_UNUSED(dev); PRCI_REG(PRCI_PLLCFG) = PLL_REFSEL(1) | PLL_BYPASS(1); PRCI_REG(PRCI_PLLDIV) = (PLL_FINAL_DIV_BY_1(1) | PLL_FINAL_DIV(0)); PRCI_REG(PRCI_PLLCFG) |= PLL_SEL(1); PRCI_REG(PRCI_HFROSCCFG) &= ~ROSC_EN(1); return 0; } SYS_INIT(hifive1_clock_init, PRE_KERNEL_1, CONFIG_PINMUX_INIT_PRIORITY);
from hwt.hdl.constants import READ, WRITE from hwtLib.abstract.sim_ram import SimRam from hwtLib.cesnet.mi32.intf import Mi32 from pyMathBitPrecise.bit_utils import mask from hwtSimApi.triggers import WaitWriteOnly class Mi32SimRam(SimRam): def __init__(self, mi32: Mi32, parent=None): super(Mi32SimRam, self).__init__(mi32.DATA_WIDTH // 8, parent=parent) self.intf = mi32 self.clk = mi32._getAssociatedClk() self._word_bytes = mi32.DATA_WIDTH // 8 self._word_mask = mask(self._word_bytes) self._registerOnClock() def _registerOnClock(self): self.clk._sigInside.wait(self.checkRequests()) def checkRequests(self): """ Check if any request has appeared on interfaces """ yield WaitWriteOnly() req = self.intf._ag.requests if req: self.on_req(req) self._registerOnClock() def on_read(self, addr): addr = int(addr) if addr % self._word_bytes != 0: raise NotImplementedError("Unaligned read") d = self.data[int(addr) // self._word_bytes] self.intf._ag.r_data.append(d) def on_write(self, addr, val, byteen): addr = int(addr) if addr % self._word_bytes != 0: raise NotImplementedError("Unaligned write", addr) if int(byteen) == self._word_mask: self.data[addr // self._word_bytes] = val else: raise NotImplementedError("Masked write") def on_req(self, req): mode, addr, val, byteen = req.popleft() if mode == READ: self.on_read(addr) else: assert mode == WRITE self.on_write(addr, val, byteen)
# nginx-hosts Hosts setup for my nginx server.
require 'active_support/core_ext' module HasStrongPolicy::ControllerHelper def self.included(base) base.extend ClassMethods end module ClassMethods def has_strong_policy(options = {}) include HasStrongPolicy::ControllerHelper::HasHasStrongPolicy @_policy_class = options[:using] end end module HasHasStrongPolicy def self.included(base) base.extend ClassMethods end def policy_params self.class.policy_class.new(params).apply end module ClassMethods def policy_class return @_policy_class if @_policy_class name = self.name.gsub(/Controller/, '') + 'ParamsPolicy' @_policy_class = name.constantize end end end end
/* * Copyright (C) 2015 Freie Universität Berlin * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. * */ /* * @ingroup sys_auto_init_saul * @{ * * @file * @brief Auto initialization of ISL29020 light sensors * * @author Hauke Petersen <hauke.petersen@fu-berlin.de> * * @} */ #ifdef MODULE_ISL29020 #include "assert.h" #include "log.h" #include "saul_reg.h" #include "isl29020.h" #include "isl29020_params.h" /** * @brief Define the number of configured sensors */ #define ISL29020_NUM (sizeof(isl29020_params) / sizeof(isl29020_params[0])) /** * @brief Allocate memory for the device descriptors */ static isl29020_t isl29020_devs[ISL29020_NUM]; /** * @brief Memory for the SAUL registry entries */ static saul_reg_t saul_entries[ISL29020_NUM]; /** * @brief Define the number of saul info */ #define ISL29020_INFO_NUM (sizeof(isl29020_saul_info) / sizeof(isl29020_saul_info[0])) /** * @brief Reference the driver struct */ extern saul_driver_t isl29020_saul_driver; void auto_init_isl29020(void) { assert(ISL29020_NUM == ISL29020_INFO_NUM); for (unsigned int i = 0; i < ISL29020_NUM; i++) { LOG_DEBUG("[auto_init_saul] initializing isl29020 #%u\n", i); int res = isl29020_init(&isl29020_devs[i], &isl29020_params[i]); if (res < 0) { LOG_ERROR("[auto_init_saul] error initializing isl29020 #%u\n", i); continue; } saul_entries[i].dev = &(isl29020_devs[i]); saul_entries[i].name = isl29020_saul_info[i].name; saul_entries[i].driver = &isl29020_saul_driver; saul_reg_add(&(saul_entries[i])); } } #else typedef int dont_be_pedantic; #endif /* MODULE_ISL29020 */
#!/usr/bin/env python3 import itertools def filename(comb_list): return '_'.join(map(str, comb_list)) + '_all.mat' if __name__ == '__main__': nb_img = 10 all_combs = []; root_dir = "/work/mpizenbe/client/icugleo/src" root_results = "/work/mpizenbe/icugleo_results" dataset = "axel" scribbles_set = ["100", "101", "102", "103", "104", "106", "200", "201", "202", "203", "204", "205", "206", "207"] for i in range(1,nb_img+1): all_combs.append(itertools.combinations(range(1,nb_img+1), i)) all_combs = list(itertools.chain.from_iterable(all_combs)) with open("tasks_list.sh", 'w') as f: for scribble_set in scribbles_set: for comb in all_combs: comb = list(comb) command = './run.sh "../datasets/{}" "{}" "{}" "true" && cd ..'.format(dataset, scribble_set, comb) result_file = '$(pwd)/datasets/{}/results/coseg/{}/{}'.format(dataset, scribble_set, filename(comb)) line = 'cd ' + root_dir + ' && ' + command + ' && echo ' + result_file f.write(line + '\n') with open("results_paths.txt", 'w') as f: for scribble_set in scribbles_set: for comb in all_combs: comb = list(comb) results_file = '{}/{}/coseg/{}/{}'.format(root_results, dataset, scribble_set, filename(comb)) f.write(results_file + '\n')
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.NetworkInformation; using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.PythonTools; using Microsoft.PythonTools.Debugger; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Project; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools.Project; using Microsoft.Win32; namespace Microsoft.IronPythonTools.Debugger { class IronPythonLauncher : IProjectLauncher { private static Process _chironProcess; private static string _chironDir; private static int _chironPort; private static readonly Guid _cpyInterpreterGuid = new Guid("{2AF0F10D-7135-4994-9156-5D01C9C11B7E}"); private static readonly Guid _cpy64InterpreterGuid = new Guid("{9A7A9026-48C1-4688-9D5D-E5699D47D074}"); private readonly IPythonProject _project; private readonly PythonToolsService _pyService; private readonly IServiceProvider _serviceProvider; public IronPythonLauncher(IServiceProvider serviceProvider, PythonToolsService pyService, IPythonProject project) { _serviceProvider = serviceProvider; _pyService = pyService; _project = project; } #region IPythonLauncher Members private static readonly Lazy<string> NoIronPythonHelpPage = new Lazy<string>(() => { try { var path = Path.GetDirectoryName(typeof(IronPythonLauncher).Assembly.Location); return Path.Combine(path, "NoIronPython.html"); } catch (ArgumentException) { } catch (NotSupportedException) { } return null; }); public int LaunchProject(bool debug) { LaunchConfiguration config; try { config = _project.GetLaunchConfigurationOrThrow(); } catch (NoInterpretersException) { throw new NoInterpretersException(null, NoIronPythonHelpPage.Value); } return Launch(config, debug); } public int LaunchFile(string file, bool debug) { LaunchConfiguration config; try { config = _project.GetLaunchConfigurationOrThrow(); } catch (NoInterpretersException) { throw new NoInterpretersException(null, NoIronPythonHelpPage.Value); } return Launch(config, debug); } private int Launch(LaunchConfiguration config, bool debug) { //if (factory.Id == _cpyInterpreterGuid || factory.Id == _cpy64InterpreterGuid) { // MessageBox.Show( // "The project is currently set to use the .NET debugger for IronPython debugging but the project is configured to start with a CPython interpreter.\r\n\r\nTo fix this change the debugger type in project properties->Debug->Launch mode.\r\nIf IronPython is not an available interpreter you may need to download it from http://ironpython.codeplex.com.", // "Visual Studio"); // return VSConstants.S_OK; //} string extension = Path.GetExtension(config.ScriptName); if (string.Equals(extension, ".html", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".htm", StringComparison.OrdinalIgnoreCase)) { try { StartSilverlightApp(config, debug); } catch (ChironNotFoundException ex) { MessageBox.Show(ex.Message, Strings.ProductTitle); } return VSConstants.S_OK; } try { if (debug) { if (string.IsNullOrEmpty(config.InterpreterArguments)) { config.InterpreterArguments = "-X:Debug"; } else if (config.InterpreterArguments.IndexOf("-X:Debug", StringComparison.InvariantCultureIgnoreCase) < 0) { config.InterpreterArguments = "-X:Debug " + config.InterpreterArguments; } var debugStdLib = _project.GetProperty(IronPythonLauncherOptions.DebugStandardLibrarySetting); bool debugStdLibResult; if (!bool.TryParse(debugStdLib, out debugStdLibResult) || !debugStdLibResult) { string interpDir = config.Interpreter.PrefixPath; config.InterpreterArguments += " -X:NoDebug \"" + System.Text.RegularExpressions.Regex.Escape(Path.Combine(interpDir, "Lib\\")) + ".*\""; } using (var dti = DebugLaunchHelper.CreateDebugTargetInfo(_serviceProvider, config)) { // Set the CLR debugger dti.Info.clsidCustom = VSConstants.CLSID_ComPlusOnlyDebugEngine; dti.Info.grfLaunch = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd; // Clear the CLSID list while launching, then restore it // so Dispose() can free it. var clsidList = dti.Info.pClsidList; dti.Info.pClsidList = IntPtr.Zero; try { dti.Launch(); } finally { dti.Info.pClsidList = clsidList; } } } else { var psi = DebugLaunchHelper.CreateProcessStartInfo(_serviceProvider, config); Process.Start(psi).Dispose(); } } catch (FileNotFoundException) { } return VSConstants.S_OK; } #endregion private static Guid? guidSilverlightDebug = new Guid("{032F4B8C-7045-4B24-ACCF-D08C9DA108FE}"); public void StartSilverlightApp(LaunchConfiguration config, bool debug) { var root = Path.GetFullPath(config.WorkingDirectory).TrimEnd('\\'); var file = Path.Combine(root, config.ScriptName); int port = EnsureChiron(root); var url = string.Format( "http://localhost:{0}/{1}", port, (file.StartsWith(root + "\\") ? file.Substring(root.Length + 1) : file.TrimStart('\\')).Replace('\\', '/') ); StartInBrowser(url, debug ? guidSilverlightDebug : null); } public void StartInBrowser(string url, Guid? debugEngine) { if (debugEngine.HasValue) { // launch via VS debugger, it'll take care of figuring out the browsers VsDebugTargetInfo dbgInfo = new VsDebugTargetInfo(); dbgInfo.dlo = (DEBUG_LAUNCH_OPERATION)_DEBUG_LAUNCH_OPERATION3.DLO_LaunchBrowser; dbgInfo.bstrExe = url; dbgInfo.clsidCustom = debugEngine.Value; dbgInfo.grfLaunch = (uint)__VSDBGLAUNCHFLAGS.DBGLAUNCH_StopDebuggingOnEnd | (uint)__VSDBGLAUNCHFLAGS4.DBGLAUNCH_UseDefaultBrowser; dbgInfo.cbSize = (uint)Marshal.SizeOf(dbgInfo); VsShellUtilities.LaunchDebugger(_serviceProvider, dbgInfo); } else { // run the users default browser var handler = GetBrowserHandlerProgId(); var browserCmd = (string)Registry.ClassesRoot.OpenSubKey(handler).OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command").GetValue(""); if (browserCmd.IndexOf("%1") != -1) { browserCmd = browserCmd.Replace("%1", url); } else { browserCmd = browserCmd + " " + url; } bool inQuote = false; string cmdLine = null; for (int i = 0; i < browserCmd.Length; i++) { if (browserCmd[i] == '"') { inQuote = !inQuote; } if (browserCmd[i] == ' ' && !inQuote) { cmdLine = browserCmd.Substring(0, i); break; } } if (cmdLine == null) { cmdLine = browserCmd; } Process.Start(cmdLine, browserCmd.Substring(cmdLine.Length)); } } private static string GetBrowserHandlerProgId() { try { return (string)Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Explorer").OpenSubKey("FileExts").OpenSubKey(".html").OpenSubKey("UserChoice").GetValue("Progid"); } catch { return (string)Registry.ClassesRoot.OpenSubKey(".html").GetValue(""); } } private int EnsureChiron(string/*!*/ webSiteRoot) { Debug.Assert(!webSiteRoot.EndsWith("\\")); if (_chironDir != webSiteRoot && _chironProcess != null && !_chironProcess.HasExited) { try { _chironProcess.Kill(); } catch { // process already exited } _chironProcess = null; } if (_chironProcess == null || _chironProcess.HasExited) { // start Chiron var chironPath = ChironPath; // Get a free port _chironPort = GetFreePort(); // TODO: race condition - the port might be taked by the time Chiron attempts to open it // TODO: we should wait for Chiron before launching the browser string commandLine = "/w:" + _chironPort + " /notification /d:"; if (webSiteRoot.IndexOf(' ') != -1) { commandLine += "\"" + webSiteRoot + "\""; } else { commandLine += webSiteRoot; } ProcessStartInfo startInfo = new ProcessStartInfo(chironPath, commandLine); startInfo.CreateNoWindow = true; startInfo.UseShellExecute = false; _chironDir = webSiteRoot; _chironProcess = Process.Start(startInfo); } return _chironPort; } private static int GetFreePort() { return Enumerable.Range(new Random().Next(1200, 2000), 60000).Except( from connection in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections() select connection.LocalEndPoint.Port ).First(); } public string ChironPath { get { string result = GetPythonInstallDir(); if (result != null) { result = Path.Combine(result, @"Silverlight\bin\Chiron.exe"); if (File.Exists(result)) { return result; } } result = Path.Combine(Path.GetDirectoryName(typeof(IronPythonLauncher).Assembly.Location), "Chiron.exe"); if (File.Exists(result)) { return result; } throw new ChironNotFoundException(); } } internal static string GetPythonInstallDir() { using (var ipy = Registry.LocalMachine.OpenSubKey("SOFTWARE\\IronPython")) { if (ipy != null) { using (var twoSeven = ipy.OpenSubKey("2.7")) { if (twoSeven != null) { using (var installPath = twoSeven.OpenSubKey("InstallPath")) { var path = installPath.GetValue("") as string; if (path != null) { return path; } } } } } } var paths = Environment.GetEnvironmentVariable("PATH"); if (paths != null) { foreach (string dir in paths.Split(Path.PathSeparator)) { try { if (IronPythonExistsIn(dir)) { return dir; } } catch { // ignore } } } return null; } private static bool IronPythonExistsIn(string/*!*/ dir) { return File.Exists(Path.Combine(dir, "ipy.exe")); } [Serializable] class ChironNotFoundException : Exception { public ChironNotFoundException() : this(Strings.IronPythonSilverlightToolsNotFound) { } public ChironNotFoundException(string message) : base(message) { } public ChironNotFoundException(string message, Exception inner) : base(message, inner) { } protected ChironNotFoundException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } } }
# hokohoko Test hokohoko Test hokohoko Test hokohoko2
# -*- coding: utf-8 -*- """ Sahana Eden Transport Model @copyright: 2012-15 (c) Sahana Software Foundation @license: MIT 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. """ __all__ = ("S3TransportModel",) from gluon import * from gluon.storage import Storage from ..s3 import * # ============================================================================= class S3TransportModel(S3Model): """ http://eden.sahanafoundation.org/wiki/BluePrint/Transport """ names = ("transport_airport", "transport_heliport", "transport_seaport", ) def model(self): T = current.T db = current.db messages = current.messages UNKNOWN_OPT = messages.UNKNOWN_OPT settings = current.deployment_settings configure = self.configure crud_strings = current.response.s3.crud_strings define_table = self.define_table super_link = self.super_link location_id = self.gis_location_id organisation_id = self.org_organisation_id # --------------------------------------------------------------------- # Airports # storage_types = { 1: T("covered"), 2: T("uncovered"), } airport_capacity_opts = { 2: T("number of planes"), 3: T("m3") } # http://en.wikipedia.org/wiki/Runway#Surface_type_codes runway_surface_opts = {"ASP": T("Asphalt"), "BIT": T("Bitumenous asphalt or tarmac"), #"BRI": T("Bricks"), (no longer in use, covered with asphalt or concrete now) "CLA": T("Clay"), "COM": T("Composite"), "CON": T("Concrete"), "COP": T("Composite"), "COR": T("Coral (coral reef structures)"), "GRE": T("Graded or rolled earth, grass on graded earth"), "GRS": T("Grass or earth not graded or rolled"), "GVL": T("Gravel"), "ICE": T("Ice"), "LAT": T("Laterite"), "MAC": T("Macadam"), "PEM": T("Partially concrete, asphalt or bitumen-bound macadam"), "PER": T("Permanent surface, details unknown"), "PSP": T("Marsden Matting (derived from pierced/perforated steel planking)"), "SAN": T("Sand"), "SMT": T("Sommerfeld Tracking"), "SNO": T("Snow"), "U": T("Unknown surface"), } # SIGCAF has these: # http://www.humanitarianresponse.info/operations/central-african-republic/dataset/central-african-republic-aerodromes-airports-airfields # BASG, BL, BLA, BLAG, BLG, PM/BL # WFP just use Paved/Unpaved # SIGCAF classifications # We could consider using these instead? # http://en.wikipedia.org/wiki/Pavement_classification_number aircraft_size_opts = {"MH1521": "MH.1521", # 1 ton 6-seater monoplane: http://en.wikipedia.org/wiki/Max_Holste_Broussard#Specifications_.28MH.1521M.29 "PA31": "PA-31", # 1.3 tons twin prop http://en.wikipedia.org/wiki/Piper_PA-31_Navajo#Specifications_.28PA-31_Navajo.29 "3TN": T("3 Tons"), "DC3": "DC-3", # 4 tons http://en.wikipedia.org/wiki/Douglas_DC-3#Specifications_.28DC-3A.29 "SE210": "SE 210", # 8 tons http://en.wikipedia.org/wiki/Sud_Aviation_Caravelle#Specifications_.28Caravelle_III.29 "DC4": "DC-4", # 10 tons http://en.wikipedia.org/wiki/Douglas_DC-4#Specifications_.28DC-4-1009.29 "13TN": T("13 Tons"), "C160": "C-160", # 17 tons http://en.wikipedia.org/wiki/Transall_C-160#Specifications_.28C-160.29 "Larger": T("Larger"), } # Numbers are also in the XSL humanitarian_use_opts = {1: T("No"), 2: T("Upon request"), 3: T("Connection"), 4: T("Hub"), 9: T("Closed"), } if settings.get_transport_airport_code_unique(): code_requires = IS_EMPTY_OR([IS_LENGTH(10), IS_NOT_IN_DB(db, "transport_airport.code"), ]) else: code_requires = IS_EMPTY_OR(IS_LENGTH(10)) tablename = "transport_airport" define_table(tablename, #super_link("doc_id", "doc_entity"), #super_link("pe_id", "pr_pentity"), super_link("site_id", "org_site"), Field("name", notnull=True, length = 64, # Mayon Compatibility label = T("Name"), ), # Code is part of the SE Field("code", label = T("Code"), length = 10, # Mayon Compatibility requires = code_requires, # Enable in Templates as-required readable = False, writable = False, ), # Other codes can be added as tags if-required, but these 2 are so common that they are worth putting directly in the table Field("icao", length=4, label = T("ICAO"), requires = IS_EMPTY_OR(IS_NOT_IN_DB(db, "transport_airport.icao")), ), Field("iata", length=3, label = T("IATA"), requires = IS_EMPTY_OR(IS_NOT_IN_DB(db, "transport_airport.iata")), ), # @ToDo: Expose Elevation & Lat/Lon to Widget location_id(), # We should be more specific: # http://en.wikipedia.org/wiki/Runway#Declared_distances Field("runway_length", "integer", label = T("Runway Length (m)"), ), Field("runway_width", "integer", label = T("Runway Width (m)"), ), Field("runway_surface", default = "U", label = T("Runway Surface"), represent = lambda opt: \ runway_surface_opts.get(opt, UNKNOWN_OPT), requires = IS_IN_SET(runway_surface_opts), ), Field("aircraft_max_size", label = T("Aircraft Maximum Size"), represent = lambda opt: \ aircraft_size_opts.get(opt, UNKNOWN_OPT), requires = IS_EMPTY_OR( IS_IN_SET(aircraft_size_opts) ), ), Field("humanitarian_use", "integer", label = T("Humanitarian Use"), represent = lambda opt: \ humanitarian_use_opts.get(opt, UNKNOWN_OPT), requires = IS_EMPTY_OR( IS_IN_SET(humanitarian_use_opts) ), ), organisation_id(), Field("restrictions", "text", label = T("Restrictions"), # Enable in Templates as-required readable = False, writable = False, ), Field("ils", "boolean", label = T("Instrument Landing System"), represent=lambda bool: \ (bool and [T("Yes")] or [T("No")])[0], # Enable in Templates as-required readable = False, writable = False, ), Field("lighting", "boolean", label = T("Lighting"), represent = lambda bool: \ (bool and [T("Yes")] or [T("No")])[0], # Enable in Templates as-required readable = False, writable = False, ), Field("immigration_customs_capabilities", "text", label = T("Immigration and Customs Capabilities"), # Enable in Templates as-required readable = False, writable = False, ), Field("security_desc", "text", label = T("Security Description"), comment = DIV(_class="tooltip", _title="%s|%s" % (T("Security Description"), T("Description of perimeter fencing, security guards, security lighting."))), # Enable in Templates as-required readable = False, writable = False, ), # @ToDo: put storage type inline Field("storage_capacity", "double", label = T("Storage Capacity (m3)"), # Enable in Templates as-required readable = False, writable = False, ), Field("storage_type", "integer", label = T("Storage Type"), represent = lambda opt: \ storage_types.get(opt, UNKNOWN_OPT), requires = IS_EMPTY_OR( IS_IN_SET(storage_types) ), # Enable in Templates as-required readable = False, writable = False, ), # @ToDo: put units inline Field("parking_tarmac_space", "double", label = T("Parking/Tarmac Space Capacity"), # Enable in Templates as-required readable = False, writable = False, ), Field("capacity", "integer", default = 1, label = T("Parking/Tarmac Space Units"), represent = lambda opt: \ airport_capacity_opts.get(opt, UNKNOWN_OPT), requires = IS_EMPTY_OR( IS_IN_SET(airport_capacity_opts) ), # Enable in Templates as-required readable = False, writable = False, ), Field("helipad_info", "text", label = T("Helipad Information"), # Enable in Templates as-required readable = False, writable = False, ), self.pr_person_id( label = T("Information Source"), # Enable in Templates as-required readable = False, writable = False, ), Field("obsolete", "boolean", default = False, label = T("Obsolete"), represent = lambda bool: \ (bool and [T("Obsolete")] or [current.messages["NONE"]])[0], readable = False, writable = False, ), s3_comments(), *s3_meta_fields()) # CRUD strings crud_strings[tablename] = Storage( label_create=T("Create Airport"), title_display=T("Airport Details"), title_list=T("Airports"), title_update=T("Edit Airport"), title_upload=T("Import Airports"), label_list_button=T("List Airports"), label_delete_button=T("Delete Airport"), msg_record_created=T("Airport added"), msg_record_modified=T("Airport updated"), msg_record_deleted=T("Airport deleted"), msg_list_empty=T("No Airports currently registered")) configure(tablename, list_fields = ["name", "humanitarian_use", "organisation_id", "location_id$lat", "location_id$lon", "location_id$elevation", "runway_length", "runway_width", "runway_surface", "aircraft_max_size", ], #onaccept = self.transport_airport_onaccept, #super_entity = ("doc_entity", "pr_pentity", "org_site"), super_entity = "org_site", ) # --------------------------------------------------------------------- # Heliports # if settings.get_transport_heliport_code_unique(): code_requires = IS_EMPTY_OR([IS_LENGTH(10), IS_NOT_IN_DB(db, "transport_heliport.code"), ]) else: code_requires = IS_EMPTY_OR(IS_LENGTH(10)) tablename = "transport_heliport" define_table(tablename, #super_link("doc_id", "doc_entity"), #super_link("pe_id", "pr_pentity"), super_link("site_id", "org_site"), Field("name", notnull=True, length = 64, # Mayon Compatibility label = T("Name"), ), Field("code", label = T("Code"), length = 10, # Mayon Compatibility requires = code_requires, # Deployments that don't want site codes can hide them #readable = False, #writable = False, ), organisation_id(), location_id(), Field("obsolete", "boolean", default = False, label = T("Obsolete"), represent = lambda opt: \ (opt and [T("Obsolete")] or [current.messages["NONE"]])[0], readable = False, writable = False, ), s3_comments(), *s3_meta_fields()) # CRUD strings crud_strings[tablename] = Storage( label_create=T("Create Heliport"), title_display=T("Heliport Details"), title_list=T("Heliports"), title_update=T("Edit Heliport"), title_upload=T("Import Heliports"), label_list_button=T("List Heliports"), label_delete_button=T("Delete Heliport"), msg_record_created=T("Heliport added"), msg_record_modified=T("Heliport updated"), msg_record_deleted=T("Heliport deleted"), msg_list_empty=T("No Heliports currently registered")) configure(tablename, #onaccept = self.transport_heliport_onaccept, #super_entity = ("doc_entity", "pr_pentity", "org_site"), super_entity = "org_site", ) # --------------------------------------------------------------------- # Seaports # ownership_opts = { 1: T("Public"), 2: T("Private") } unit_opts = { 1: T("ft"), 2: T("m") } if settings.get_transport_seaport_code_unique(): code_requires = IS_EMPTY_OR([IS_LENGTH(10), IS_NOT_IN_DB(db, "transport_seaport.code"), ]) else: code_requires = IS_EMPTY_OR(IS_LENGTH(10)) tablename = "transport_seaport" define_table(tablename, #super_link("doc_id", "doc_entity"), #super_link("pe_id", "pr_pentity"), super_link("site_id", "org_site"), Field("name", notnull=True, length = 64, # Mayon Compatibility label = T("Name"), ), Field("code", label = T("Code"), length = 10, # Mayon Compatibility requires = code_requires, # Deployments that don't want site codes can hide them #readable = False, #writable = False, ), Field("ownership_type", "integer", default = 1, label = T("Ownership"), represent = lambda opt: \ ownership_opts.get(opt, UNKNOWN_OPT), requires = IS_IN_SET(ownership_opts, zero=None), ), Field("max_height", "double", label = T("Max Height"), ), Field("max_height_units", "integer", default = 1, label = T("Units"), represent = lambda opt: \ unit_opts.get(opt, UNKNOWN_OPT), requires = IS_IN_SET(unit_opts, zero=None), ), Field("roll_on_off", "boolean", default = False, represent = lambda opt: \ (opt and [T("Yes")] or [T("No")])[0], label = T("Roll On Roll Off Berth"), ), Field("cargo_pier_depth", "double", label = T("Cargo Pier Depth"), ), Field("cargo_pier_depth_units", "integer", default = 1, label = T("Units"), represent = lambda opt: \ unit_opts.get(opt, UNKNOWN_OPT), requires = IS_IN_SET(unit_opts, zero=None), ), Field("oil_terminal_depth", "double", label = T("Oil Terminal Depth"), ), Field("oil_terminal_depth_units", "integer", default = 1, label = T("Units"), represent = lambda opt: \ unit_opts.get(opt, UNKNOWN_OPT), requires = IS_IN_SET(unit_opts, zero=None), ), Field("dry_dock", "boolean", default = False, label = T("Dry Dock"), represent = lambda opt: \ (opt and [T("Yes")] or [T("No")])[0], ), Field("vessel_max_length", "double", label = T("Vessel Max Length"), ), Field("vessel_max_length_units", "integer", default = 1, label = T("Units"), represent = lambda opt: \ unit_opts.get(opt, UNKNOWN_OPT), requires = IS_IN_SET(unit_opts, zero=None), ), Field("repairs", "text", label = T("Repairs"), ), Field ("shelter", "text", label = T("Shelter"), ), Field("warehouse_capacity", "double", label = T("Warehousing Storage Capacity"), ), Field("secure_storage_capacity", "double", label = T("Secure Storage Capacity"), ), Field("customs_warehouse_capacity", "double", label = T("Customs Warehousing Storage Capacity"), ), Field("tugs", "integer", label = T("Number of Tugboats"), ), Field("tug_capacity", "double", label = T("Tugboat Capacity"), ), Field("barges", "integer", label = T("Number of Barges"), ), Field("barge_capacity", "double", label = T("Barge Capacity"), ), Field("loading_equipment", "text", label = T("Loading Equipment"), ), Field("customs_capacity", "text", label = T("Customs Capacity"), ), Field("security", "text", label = T("Security"), ), Field("high_tide_depth", "double", label = T("High Tide Depth"), ), Field("high_tide_depth_units", "integer", default = 1, label = T("Units"), represent = lambda opt: \ unit_opts.get(opt, UNKNOWN_OPT), requires = IS_IN_SET(unit_opts, zero=None), ), Field("low_tide_depth", "double", label = T("Low Tide Depth"), ), Field("low_tide_depth_units", "integer", default = 1, label = T("Units"), represent = lambda opt: \ unit_opts.get(opt, UNKNOWN_OPT), requires = IS_IN_SET(unit_opts, zero=None), ), Field("flood_depth", "double", label = T("Flood Depth"), ), Field("flood_depth_units", "integer", default = 1, label = T("Units"), represent = lambda opt: \ unit_opts.get(opt, UNKNOWN_OPT), requires = IS_IN_SET(unit_opts, zero=None), ), organisation_id(), location_id(), Field("obsolete", "boolean", default = False, label = T("Obsolete"), represent = lambda opt: \ (opt and [T("Closed")] or [T("Operational")])[0], ), s3_comments(), *s3_meta_fields()) # CRUD strings crud_strings[tablename] = Storage( label_create=T("Create Seaport"), title_display=T("Seaport Details"), title_list=T("Seaports"), title_update=T("Edit Seaport"), title_upload=T("Import Seaports"), label_list_button=T("List Seaports"), label_delete_button=T("Delete Seaport"), msg_record_created=T("Seaport added"), msg_record_modified=T("Seaport updated"), msg_record_deleted=T("Seaport deleted"), msg_list_empty=T("No Seaports currently registered")) configure(tablename, #onaccept = self.transport_seaport_onaccept, #super_entity = ("doc_entity", "pr_pentity", "org_site"), super_entity = "org_site", ) # --------------------------------------------------------------------- # Pass names back to global scope (s3.*) # return dict() # ------------------------------------------------------------------------- @staticmethod def transport_airport_onaccept(form): """ Update Affiliation, record ownership and component ownership """ # If made into a pe_id: #current.s3db.org_update_affiliations("transport_airport", form.vars) return # ------------------------------------------------------------------------- @staticmethod def transport_heliport_onaccept(form): """ Update Affiliation, record ownership and component ownership """ # If made into a pe_id: #current.s3db.org_update_affiliations("transport_heliport", form.vars) return # ------------------------------------------------------------------------- @staticmethod def transport_seaport_onaccept(form): """ Update Affiliation, record ownership and component ownership """ # If made into a pe_id: #current.s3db.org_update_affiliations("transport_seaport", form.vars) return # END =========================================================================
using Newtonsoft.Json; using SeafClient.Converters; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SeafClient.Requests.UserAccountInfo { public class UserAvatarRequest : SessionRequest<UserAvatar> { /// <summary> /// The username to get the avatar for /// </summary> public string Username { get; set; } /// <summary> /// The size to which the avatar should be resized /// </summary> public int Size { get; set; } public override string CommandUri { get { return String.Format("api2/avatars/user/{0}/resized/{1:d}/", Username, Size); } } public UserAvatarRequest(string authToken, string username, int size) : base(authToken) { Username = username; Size = size; } } /// <summary> /// Describes the avatar image of a user /// </summary> public class UserAvatar { public string Url { get; set; } [JsonProperty("is_default")] public bool IsDefault { get; set; } [JsonProperty("mtime"), JsonConverter(typeof(SeafTimestampConverter))] public DateTime Timestamp { get; set; } } }
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.rs.image; import java.lang.Math; import android.renderscript.Allocation; import android.renderscript.Element; import android.renderscript.Matrix4f; import android.renderscript.RenderScript; import android.renderscript.Script; import android.renderscript.ScriptC; import android.renderscript.ScriptGroup; import android.renderscript.ScriptIntrinsic3DLUT; import android.renderscript.ScriptIntrinsicColorMatrix; import android.renderscript.Type; import android.util.Log; public class ColorCube extends TestBase { private Allocation mCube; private ScriptC_colorcube mScript; private ScriptIntrinsic3DLUT mIntrinsic; private boolean mUseIntrinsic; public ColorCube(boolean useIntrinsic) { mUseIntrinsic = useIntrinsic; } private void initCube() { final int sx = 32; final int sy = 32; final int sz = 16; Type.Builder tb = new Type.Builder(mRS, Element.U8_4(mRS)); tb.setX(sx); tb.setY(sy); tb.setZ(sz); Type t = tb.create(); mCube = Allocation.createTyped(mRS, t); int dat[] = new int[sx * sy * sz]; for (int z = 0; z < sz; z++) { for (int y = 0; y < sy; y++) { for (int x = 0; x < sx; x++ ) { int v = 0xff000000; v |= (0xff * x / (sx - 1)); v |= (0xff * y / (sy - 1)) << 8; v |= (0xff * z / (sz - 1)) << 16; dat[z*sy*sx + y*sx + x] = v; } } } mCube.copyFromUnchecked(dat); } public void createTest(android.content.res.Resources res) { mScript = new ScriptC_colorcube(mRS, res, R.raw.colorcube); mIntrinsic = ScriptIntrinsic3DLUT.create(mRS, Element.U8_4(mRS)); initCube(); mScript.invoke_setCube(mCube); mIntrinsic.setLUT(mCube); } public void runTest() { if (mUseIntrinsic) { mIntrinsic.forEach(mInPixelsAllocation, mOutPixelsAllocation); } else { mScript.forEach_root(mInPixelsAllocation, mOutPixelsAllocation); } } }
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.kie.server.services.impl; public class KieServerLocator { private static final KieServerImpl INSTANCE = new KieServerImpl(); private KieServerLocator() { } public static KieServerImpl getInstance() { return INSTANCE; } }
----------------------------------------------------------------------------------------------------------------------- -- inspect.lua - v1.1 (2011-01) -- Enrique García Cota - enrique.garcia.cota [AT] gmail [DOT] com -- human-readable representations of tables. -- inspired by http://lua-users.org/wiki/TableSerialization ----------------------------------------------------------------------------------------------------------------------- -- Apostrophizes the string if it has quotes, but not aphostrophes -- Otherwise, it returns a regular quoted string local function smartQuote(str) if string.match( string.gsub(str,"[^'\"]",""), '^"+$' ) then return "'" .. str .. "'" end return string.format("%q", str ) end local controlCharsTranslation = { ["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v", ["\\"] = "\\\\" } local function unescapeChar(c) return controlCharsTranslation[c] end local function unescape(str) local result, _ = string.gsub( str, "(%c)", unescapeChar ) return result end local function isIdentifier(str) return string.match( str, "^[_%a][_%a%d]*$" ) end local function isArrayKey(k, length) return type(k)=='number' and 1 <= k and k <= length end local function isDictionaryKey(k, length) return not isArrayKey(k, length) end local sortOrdersByType = { ['number'] = 1, ['boolean'] = 2, ['string'] = 3, ['table'] = 4, ['function'] = 5, ['userdata'] = 6, ['thread'] = 7 } function sortKeys(a,b) local ta, tb = type(a), type(b) if ta ~= tb then return sortOrdersByType[ta] < sortOrdersByType[tb] end if ta == 'string' or ta == 'number' then return a < b end return false end local function getDictionaryKeys(t) local length = #t local keys = {} for k,_ in pairs(t) do if isDictionaryKey(k, length) then table.insert(keys,k) end end table.sort(keys, sortKeys) return keys end local Inspector = {} function Inspector:new(v, depth) local inspector = { buffer = {}, depth = depth, level = 0, counters = { ['function'] = 0, ['userdata'] = 0, ['thread'] = 0, ['table'] = 0 }, pools = { ['function'] = setmetatable({}, {__mode = "kv"}), ['userdata'] = setmetatable({}, {__mode = "kv"}), ['thread'] = setmetatable({}, {__mode = "kv"}), ['table'] = setmetatable({}, {__mode = "kv"}) } } setmetatable( inspector, { __index = Inspector, __tostring = function(instance) return table.concat(instance.buffer) end } ) return inspector:putValue(v) end function Inspector:puts(...) local args = {...} for i=1, #args do table.insert(self.buffer, tostring(args[i])) end return self end function Inspector:tabify() --self:puts("\n", string.rep(" ", self.level)) return self end function Inspector:tabify_indent() self:puts("\n", string.rep(" ", self.level)) return self end function Inspector:up() self.level = self.level - 1 end function Inspector:down() self.level = self.level + 1 end function Inspector:putComma(comma) if comma then self:puts(', ') end return true end function Inspector:putTable(t) if self:alreadySeen(t) then self:puts('<table ', self:getOrCreateCounter(t), '>') elseif self.level >= self.depth then self:puts('{...}') else --self:puts('<',self:getOrCreateCounter(t),'>{') local length = #t local mt = getmetatable(t) local __tostring = type(mt) == 'table' and mt.__tostring local string = type(__tostring) == 'function' and __tostring(t) if type(string) == 'string' and #string > 0 then self:puts(unescape(string)) --self:puts(' -- ', unescape(string)) if length >= 1 then self:tabify() end -- tabify the array values return self end self:puts('{') self:down() local comma = false for i=1, length do comma = self:putComma(comma) --self:puts(' '):putValue(t[i]) self:putValue(t[i]) end local dictKeys = getDictionaryKeys(t) local MULTILINE_KEY_COUNT = 10 local multilined = #dictKeys > MULTILINE_KEY_COUNT if not multilined then for k,v in pairs(t) do if "table" == type(v) then multilined = true break end end end for idx,k in ipairs(dictKeys) do comma = self:putComma(comma) if multilined then if 1 == idx then self:puts(" ") else self:tabify_indent() end end self:tabify():putKey(k):puts(' = '):putValue(t[k]) end --if multilined then -- self:puts(" ") --end if mt then comma = self:putComma(comma) self:tabify():puts('<metatable> = '):putValue(mt) end self:up() if #dictKeys > 0 or mt then -- dictionary table. Justify closing } self:tabify() elseif length > 0 then -- array tables have one extra space before closing } --self:puts(' ') end self:puts('}') end return self end function Inspector:alreadySeen(v) local tv = type(v) return self.pools[tv][v] ~= nil end function Inspector:getOrCreateCounter(v) local tv = type(v) local current = self.pools[tv][v] if not current then current = self.counters[tv] + 1 self.counters[tv] = current self.pools[tv][v] = current end return current end function Inspector:putValue(v) local tv = type(v) if tv == 'string' then self:puts(smartQuote(unescape(v))) elseif tv == 'number' or tv == 'boolean' or tv == 'nil' then self:puts(tostring(v)) elseif tv == 'table' then self:putTable(v) else self:puts('<',tv,' ',self:getOrCreateCounter(v),'>') end return self end function Inspector:putKey(k) if type(k) == "string" and isIdentifier(k) then return self:puts(k) end return self:puts( "[" ):putValue(k):puts("]") end local function inspect(t, depth) depth = depth or 4 return tostring(Inspector:new(t, depth)) end return inspect
# Hibbertia benthamii F.Muell. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Candollea glomerosa Benth. ### Remarks null
/* * Cloud Foundry Services Connector * Copyright (c) 2014 ActiveState Software Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var Logule = require('logule'); module.exports.requestLogger = function (opts) { var log = Logule.init(module, opts.prefix); return function (req, res, next) { res.on('finish', function () { log.info(req.connection.remoteAddress + ' - ' + res.statusCode + ' - ' + req.method + ' - '+ req.url); }); res.on('error', function (err) { log.info('Error processing request: ' + err + ' '+ req.connection.remoteAddress + ' - ' + res.statusCode + ' - ' + req.url); }); next(); }; }; module.exports.validateAPIVersion = function (version) { var log = Logule.init(module); var header = 'x-broker-api-version'; return function (req, res, next) { if (!req.headers[header]) { log.warn(header + ' is missing from the request'); } else { var pattern = new RegExp('^' + version.major + '\\.\\d+$'); if (!req.headers[header].match(pattern)) { log.warn('Incompatible services API version: ' + req.headers[header]); res.status(412); res.end(); } } next(); }; };
################################################################ # Raspberry Pi Driver for Adafruit HTU21D-F # Go buy one at https://www.adafruit.com/products/1899 # written by D. Alex Gray dalexgray@mac.com # Thanks to egutting at the adafruit.com forums # Thanks to joan on the raspberrypi.org forums # This requires the pigpio library # Get pigpio at http://abyz.co.uk/rpi/pigpio/index.html # No warranty offered or implied. God help you if you use this. ################################################################ import time import pigpio import math pi = pigpio.pi() # HTU21D-F Address addr = 0x40 # i2c bus, if you have a Raspberry Pi Rev A, change this to 0 bus = 1 # HTU21D-F Commands rdtemp = 0xE3 rdhumi = 0xE5 wtreg = 0xE6 rdreg = 0xE7 reset = 0xFE def htu_reset(): handle = pi.i2c_open(bus, addr) # open i2c bus pi.i2c_write_byte(handle, reset) # send reset command pi.i2c_close(handle) # close i2c bus time.sleep(0.2) # reset takes 15ms so let's give it some time def read_temperature(): handle = pi.i2c_open(bus, addr) # open i2c bus pi.i2c_write_byte(handle, rdtemp) # send read temp command time.sleep(0.055) # readings take up to 50ms, lets give it some time (count, byteArray) = pi.i2c_read_device(handle, 3) # vacuum up those bytes pi.i2c_close(handle) # close the i2c bus t1 = byteArray[0] # most significant byte msb t2 = byteArray[1] # least significant byte lsb temp_reading = (t1 * 256) + t2 # combine both bytes into one big integer temp_reading = math.fabs(temp_reading) # I'm an idiot and can't figure out any other way to make it a float temperature = ((temp_reading / 65536) * 175.72 ) - 46.85 # formula from datasheet return temperature def read_humidity(temperature=False): handle = pi.i2c_open(bus, addr) # open i2c bus pi.i2c_write_byte(handle, rdhumi) # send read humi command time.sleep(0.055) # readings take up to 50ms, lets give it some time (count, byteArray) = pi.i2c_read_device(handle, 3) # vacuum up those bytes pi.i2c_close(handle) # close the i2c bus h1 = byteArray[0] # most significant byte msb h2 = byteArray[1] # least significant byte lsb humi_reading = (h1 * 256) + h2 # combine both bytes into one big integer humi_reading = math.fabs(humi_reading) # I'm an idiot and can't figure out any other way to make it a float uncomp_humidity = ((humi_reading / 65536) * 125 ) - 6 # formula from datasheet # to get the compensated humidity we need to read the temperature if not temperature: temperature = read_temperature() humidity = ((25 - temperature) * -0.15) + uncomp_humidity return humidity
/* * This file is part of rasdaman community. * * Rasdaman community is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Rasdaman community 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 rasdaman community. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2009 Peter Baumann / rasdaman GmbH. * * For more information please see <http://www.rasdaman.org> * or contact Peter Baumann via <baumann@rasdaman.com>. */ #ifndef _INLINETILE_HH_ #define _INLINETILE_HH_ // -*-C++-*- (for Emacs) /************************************************************* * * * PURPOSE: * The inlinetile class is used to store small tiles efficiently. * Potentially many inlinetiles are grouped together in a blob and * stored in the database. highly dependend on DBTCIndex. * * * COMMENTS: * ************************************************************/ class OId; class r_Error; #include "raslib/mddtypes.hh" #include "tileid.hh" #include "blobtile.hh" //@ManMemo: Module: {\bf relblobif}. /*@Doc: InlineTile is the persistent class for storing the contents of MDD tiles in the database. it can be stored as a blobtile or inlined: in inlined mode multiple inlinetiles are stored as one blob in the database. memory management and modification management is critical. there are special functions in objectbroker to retrieve inlinetiles. they can only be inlined by a dbtcindex. */ /** * \ingroup Relblobifs */ class InlineTile : public BLOBTile { public: //@Man: constructors //@{ InlineTile(const OId& id, char*& thecells); /*@Doc: construct a new inline tile with the oid of the dbtilecontainerindex and the array which holds the contents of the tile. thecells will be automagically forwarded to the beginning of the next inline tile. */ InlineTile(r_Data_Format dataformat = r_Array); /*@Doc: constructs a new empty InlineTile and gets an id for it. */ InlineTile(const OId& BlobId) throw (r_Error); /*@Doc: constructs a InlineTile out of the database */ InlineTile(r_Bytes newSize, char c = 0, r_Data_Format dataformat = r_Array); /*@Doc: constructs a new InlineTile of size newSize filled with c. */ InlineTile(r_Bytes newSize, r_Bytes patSize, const char* pat, r_Data_Format dataformat = r_Array); /*@Doc: Constructs a new InlineTile of size newSize filled with the repeated char array pat of size patSize. If after filling some chars are left, they are filled with 0 */ /*@ManMemo: constructs a new InlineTile with the char array newCells with newSize elements as contents. */ InlineTile(r_Bytes newSize, const char* newCells, r_Data_Format dataformat = r_Array); /*@Doc: constructs a new InlineTile of size newSize filled with the contents of newCells. */ //@} virtual void destroy(); /*@Doc: may not destroy the object because it is inlined and therefore depending on its parent index. */ const OId& getIndexOId() const; /*@Doc: returns the oid of the index which contains the inlined tile. if the tile is outlined then this oid is invalid. */ void setIndexOId(const OId& oid); /*@Doc: make the inlinetile use this index as its parent and storage structure. */ r_Bytes getStorageSize() const; /*@Doc: returns the size this tile will consume in as an inlined array. */ virtual char* insertInMemBlock(char* test); /*@Doc: inserts the Blob into the char. the returned pointer is after the end of this tiles data. */ virtual void setModified() throw(r_Error); /*@Doc: does not only set itself modified but also informs its parent of changes. */ virtual bool isCached() const; /*@Doc: returns true if it is inlined. */ virtual void inlineTile(const OId& ixOId); /*@Doc: do everything so that this tile is inlined and uses ixOId as its index parent. it will not check if this tile is already inlined. */ virtual void outlineTile(); /*@Doc: does everything necessary to act as a blobtile: remove it from the index parent. */ virtual bool isInlined() const; /*@Doc: checks if it has a valid index parent. */ virtual ~InlineTile(); /*@Doc: no functionality. if it is inlined the dbtcindex will take care of storing it. if it is not inlined the blobtile functionality will take over. */ virtual void printStatus(unsigned int level = 0, std::ostream& stream = std::cout) const; protected: OId myIndexOId; /*@Doc: when this inlinetile is in inlined mode the myIndexOId points to the parent index. if this oid is invalid the inlinetile is not in inline mode. */ }; #endif
(function () { angular .module("jgaDirective", []) .directive("jgaSortable", sortableDir) .directive("fileInput", ['$parse', fileInput]); function sortableDir($http) { function linkFunc(scope, element, attributes) { var startIndex = -1; var stopIndex = -1; element.sortable({ axis: 'y', start: function(event, ui){ startIndex=ui.item.index(); }, stop: function(event, ui){ stopIndex=ui.item.index(); scope.callbackFn({initial: startIndex,final: stopIndex}); } }); } return { scope: { callbackFn: '&' }, link: linkFunc }; } function fileInput($parse) { function linkFunc(scope, element, attributes) { element.bind('change', function () { $parse(attributes.fileInput) .assign(scope, element[0].files) scope.$apply(); }) } return { restrict: 'A', link: linkFunc } } })();
/** * Copyright (c) 2015 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.trustedanalytics.cloud.cc.api.customizations; import feign.Response; import java.util.function.BiFunction; import java.util.function.Predicate; /** * Error decoder handler is responsible for testing whether it can be applied to response with * particular http status code and transforming it to exception object. */ public interface ErrorDecoderHandler extends BiFunction<String, Response, Exception>, Predicate<Response> { }
/* * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. 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 AJAX.ORG B.V. 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. */ ace.define('ace/theme/monokai', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-monokai"; exports.cssText = ".ace-monokai .ace_gutter {\ background: #2F3129;\ color: #8F908A\ }\ .ace-monokai .ace_print-margin {\ width: 1px;\ background: #555651\ }\ .ace-monokai {\ background-color: #272822;\ color: #F8F8F2\ }\ .ace-monokai .ace_cursor {\ color: #F8F8F0\ }\ .ace-monokai .ace_marker-layer .ace_selection {\ background: #49483E\ }\ .ace-monokai.ace_multiselect .ace_selection.ace_start {\ box-shadow: 0 0 3px 0px #272822;\ border-radius: 2px\ }\ .ace-monokai .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0)\ }\ .ace-monokai .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #49483E\ }\ .ace-monokai .ace_marker-layer .ace_active-line {\ background: #202020\ }\ .ace-monokai .ace_gutter-active-line {\ background-color: #272727\ }\ .ace-monokai .ace_marker-layer .ace_selected-word {\ border: 1px solid #49483E\ }\ .ace-monokai .ace_invisible {\ color: #52524d\ }\ .ace-monokai .ace_entity.ace_name.ace_tag,\ .ace-monokai .ace_keyword,\ .ace-monokai .ace_meta.ace_tag,\ .ace-monokai .ace_storage {\ color: #F92672\ }\ .ace-monokai .ace_punctuation,\ .ace-monokai .ace_punctuation.ace_tag {\ color: #fff\ }\ .ace-monokai .ace_constant.ace_character,\ .ace-monokai .ace_constant.ace_language,\ .ace-monokai .ace_constant.ace_numeric,\ .ace-monokai .ace_constant.ace_other {\ color: #AE81FF\ }\ .ace-monokai .ace_invalid {\ color: #F8F8F0;\ background-color: #F92672\ }\ .ace-monokai .ace_invalid.ace_deprecated {\ color: #F8F8F0;\ background-color: #AE81FF\ }\ .ace-monokai .ace_support.ace_constant,\ .ace-monokai .ace_support.ace_function {\ color: #66D9EF\ }\ .ace-monokai .ace_fold {\ background-color: #A6E22E;\ border-color: #F8F8F2\ }\ .ace-monokai .ace_storage.ace_type,\ .ace-monokai .ace_support.ace_class,\ .ace-monokai .ace_support.ace_type {\ font-style: italic;\ color: #66D9EF\ }\ .ace-monokai .ace_entity.ace_name.ace_function,\ .ace-monokai .ace_entity.ace_other,\ .ace-monokai .ace_entity.ace_other.ace_attribute-name,\ .ace-monokai .ace_variable {\ color: #A6E22E\ }\ .ace-monokai .ace_variable.ace_parameter {\ font-style: italic;\ color: #FD971F\ }\ .ace-monokai .ace_string {\ color: #E6DB74\ }\ .ace-monokai .ace_comment {\ color: #75715E\ }\ .ace-monokai .ace_indent-guide {\ background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWPQ0FD0ZXBzd/wPAAjVAoxeSgNeAAAAAElFTkSuQmCC) right repeat-y\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
<!doctype html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]--> <head> <meta charset="utf-8"> <title>ch4 - 娇蕊 &#8211; 沥川</title> <meta name="description" content="ch4大作业-《红玫瑰与白玫瑰》读书笔记."> <meta name="keywords" content="Writer004"> <!-- Twitter Cards --> <meta name="twitter:title" content="ch4 - 娇蕊"> <meta name="twitter:description" content="ch4大作业-《红玫瑰与白玫瑰》读书笔记."> <meta name="twitter:card" content="summary"> <meta name="twitter:image" content="https://Hugo1030.github.io/images/site-logo.png"> <!-- Open Graph --> <meta property="og:locale" content="中国"> <meta property="og:type" content="article"> <meta property="og:title" content="ch4 - 娇蕊"> <meta property="og:description" content="ch4大作业-《红玫瑰与白玫瑰》读书笔记."> <meta property="og:url" content="https://Hugo1030.github.io/articles/redrose-and-whiterose/"> <meta property="og:site_name" content="沥川"> <link rel="canonical" href="https://Hugo1030.github.io/articles/redrose-and-whiterose/"> <link href="https://Hugo1030.github.io/feed.xml" type="application/atom+xml" rel="alternate" title="沥川 Feed"> <!-- https://t.co/dKP3o1e --> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- For all browsers --> <link rel="stylesheet" href="https://Hugo1030.github.io/assets/css/main.css"> <!-- Webfonts --> <script src="https://use.edgefonts.net/source-sans-pro:n2,i2,n3,i3,n4,i4,n6,i6,n7,i7,n9,i9;source-code-pro:n4,n7;volkhov.js"></script> <meta http-equiv="cleartype" content="on"> <!-- HTML5 Shiv and Media Query Support --> <!--[if lt IE 9]> <script src="https://Hugo1030.github.io/assets/js/vendor/html5shiv.min.js"></script> <script src="https://Hugo1030.github.io/assets/js/vendor/respond.min.js"></script> <![endif]--> <!-- Modernizr --> <script src="https://Hugo1030.github.io/assets/js/vendor/modernizr-2.7.1.custom.min.js"></script> <!-- MathJax --> <script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <!-- Icons --> <!-- 16x16 --> <link rel="shortcut icon" href="https://Hugo1030.github.io/favicon.ico"> <!-- 32x32 --> <link rel="shortcut icon" href="https://Hugo1030.github.io/favicon.png"> <!-- 57x57 (precomposed) for iPhone 3GS, pre-2011 iPod Touch and older Android devices --> <link rel="apple-touch-icon-precomposed" href="https://Hugo1030.github.io/images/apple-touch-icon-precomposed.png"> <!-- 72x72 (precomposed) for 1st generation iPad, iPad 2 and iPad mini --> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://Hugo1030.github.io/images/apple-touch-icon-72x72-precomposed.png"> <!-- 114x114 (precomposed) for iPhone 4, 4S, 5 and post-2011 iPod Touch --> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://Hugo1030.github.io/images/apple-touch-icon-114x114-precomposed.png"> <!-- 144x144 (precomposed) for iPad 3rd and 4th generation --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://Hugo1030.github.io/images/apple-touch-icon-144x144-precomposed.png"> </head> <body id="post"> <div class="navigation-wrapper"> <nav role="navigation" id="site-nav" class="animated drop"> <ul> <li><a href="https://Hugo1030.github.io/about/" >关于</a></li> <li><a href="https://Hugo1030.github.io/articles/" >随笔</a></li> <li><a href="https://Hugo1030.github.io/note/" >笔记</a></li> <li><a href="https://Hugo1030.github.io/tech/" >技术</a></li> <li><a href="https://Hugo1030.github.io/invest/" >投资</a></li> <li><a href="https://Hugo1030.github.io/wiki/" >维基</a></li> <li><a href="https://Hugo1030.github.io/search/" >搜索</a></li> </ul> </nav> </div><!-- /.navigation-wrapper --> <!--[if lt IE 9]><div class="upgrade"><strong><a href="http://whatbrowser.org/">Your browser is quite old!</strong> Why not upgrade to a different browser to better enjoy this site?</a></div><![endif]--> <header class="masthead"> <div class="wrap"> <a href="https://Hugo1030.github.io/" class="site-logo" rel="home" title="沥川"><img src="https://Hugo1030.github.io/images/site-logo.png" width="200" height="200" alt="沥川 logo" class="animated fadeInDown"></a> <h1 class="site-title animated fadeIn"><a href="https://Hugo1030.github.io/">沥川</a></h1> <h2 class="site-description animated fadeIn" itemprop="description">士不可不弘毅</h2> </div> </header><!-- /.masthead --> <div class="js-menu-screen menu-screen"></div> <div id="main" role="main"> <article class="hentry"> <div class="entry-wrapper"> <header class="entry-header"> <ul class="entry-tags"> <li><a href="https://Hugo1030.github.io/tags/#Writer004" title="Pages tagged Writer004">Writer004</a></li> </ul> <h1 class="entry-title">ch4 - 娇蕊</h1> </header> <footer class="entry-meta"> <img src="https://Hugo1030.github.io/images/bio-photo-2.jpg" class="bio-photo" alt="沥川 bio photo"></a> <span class="author vcard">By <span class="fn">沥川</span></span> <span class="entry-date date published"><time datetime="2017-05-30T00:00:00+08:00"><i class="fa fa-calendar-o"></i> May 30, 2017</time></span> </footer> <div class="entry-content"> <p>女人年纪轻,长得好看的时候,无论到社会上做什么事,碰到的总是男人。可是到后来,除了男人之外总还有别的…</p> <h2 id="section">01</h2> <p>伦敦永远弥漫着缠绵的雾,像只只小嘴,将人里里外外吮吸个遍,衣服就是个摆设,挡不住雾的热情。远方传来机器轰鸣,空气中有股子煤渣子味儿,像男人的气味。</p> <p>娇蕊撩开窗帘,望下去。一人手拿玫瑰,站在门口张望。</p> <p>这人名叫王士洪,是在学生会活动认识的。年岁不大,脑门前的头发已经秃了。喜欢把头往后梳得整整齐齐,打上啫喱水,油光水滑,像八爪乌贼。</p> <p>起初,娇蕊不怎么敷衍他。仗着年轻漂亮,挑逗男人的本事也娴熟,大批狂蜂浪蝶围绕,枕边也从不缺乏中外俊男。</p> <p>临近回国,才发觉自己名声坏了。华人留学生圈子,想和她玩玩的大有人在,谈婚论嫁,人人避之不及。</p> <p>家里把她送出国,为的就是能嫁个好的,快毕业还没完成任务,娇蕊心里慌了。</p> <p>手忙脚乱抓了个王士洪,虽然长相欠佳,但家境殷实,父亲是上海著名海商,想以后的生活可以衣食无忧。便 故意露了些颜色,他便每天拿着玫瑰,在宿舍下面等候了…</p> <h2 id="section-1">02</h2> <p>婚后回到上海,王士洪时常出差,不在的时候,房子里空荡荡,冷冷清清。</p> <p>娇蕊觉得自己像金丝雀,被困在黄金打造的笼子里。锦衣玉食,绫罗绸缎也不过是被人喂养,赏玩。</p> <p>难得士洪回来,带回一些南洋的吃食和小玩意,他们会去看场电影,吃顿大餐,晚上做些男女之间的事,也是乏味的紧。</p> <p>娇蕊紧需要一些东西来填补内心的荒凉,这种感觉让她发慌,好像生命之花在最茂盛时刻枯萎了一般。</p> <p>趁着士洪出差的时候,她开始驰骋各大夜场。</p> <p>烫个大波浪的发,描上细长的眉,涂上艳红的唇,穿上一袭火红的裙。在五颜六色与缠绵音乐弥漫的舞场,娇蕊是最盛开的玫瑰。她扭动的时候,每个男人心中都有一团火。</p> <p>娇蕊会在舞的最沸腾,汗流浃背的时候,挑一个美丽的男人,挽着他的胳膊,去到附近的旅馆,狠狠折腾。</p> <p>短暂狂欢后,她望着屋顶美丽繁复的花纹,心底竟然更加荒凉,这些都填补不了她。</p> <p>娇蕊认为可能还不够刺激,便开始打着各种旗号去到别人家里,在女主人的床上和男主人做,依旧不满意。</p> <p>为了更刺激,勾引住在家里的教授悌米孙,后来露出点马脚给士洪看到,大发雷霆,把悌米孙赶了出去。</p> <p>娇蕊觉得,自己虽经历的男人很多,但从未真爱过,这些刺激怎么也补不了心里的洞…</p> <h2 id="section-2">03</h2> <p>一天士洪对娇蕊说,”家里要搬进来一个老同学,名叫振保,是个再正经不过的君子。在英国的时候,有富家千金倒贴,仍坐怀不乱,是个顶有自制力的人。”</p> <p>娇蕊笑道:“那到要见识见识,还没见过这么严谨的人咧!”</p> <p>黄昏的时候,娇蕊正在洗头,听到门口抬东西,也不讲究,堆着一头肥皂沫子就出来瞧。</p> <p>看见个男人,胡子刮得干干净净,头发梳得整整齐齐,身穿竖条纹深灰色西服,露出白色衬衣的三角领尖,全身没有一丝皱褶。站在那里背是挺直的,脸上戴着谦和的笑容,目光温柔宁定,像深渊一样。</p> <p>娇蕊把手从头发里抽出来,待要去他握手,看看手上有肥皂,不便伸过来,单只笑着点了个头,把手指在浴巾上揩了揩,溅了点沫子到他手背上。他不肯擦掉它,任由它自己干了。</p> <p>娇蕊一闪身躲回浴室里。</p> <p>不知为什么,娇蕊感觉自己的心不再是死的了,身上每个细胞都在颤抖,胃有点不舒服,想要作呕。这是怎么了,她问自己,这是很没道理的…</p> <h2 id="section-3">04</h2> <p>娇蕊每天坐在那里等他回来,听着电梯工东工东开上来,开过那层楼,一直开上去,她就像把一颗心提了上去,放不下来。有时候,还没开到这层就停住了,她又像在半中间断了气。</p> <p>有时把振保的大衣拿到房间里,钩在墙上一张油画的画框上,她会坐在图画下的沙发上,擦亮火柴,点上一段他吸残的烟,看着它烧,缓缓烧到她手指上,烫着了手,她抛掉了,把手送到嘴前吹一吹,仿佛很满意。</p> <p>这样的爱,在娇蕊是生平第一次。她自己也不知道为什么单单爱上了振保。常常她向他凝视,眼色里有柔情,又有轻微的嘲笑。也嘲笑他,也嘲笑她自己。</p> <p>婴儿的头脑与成熟的妇人是最具诱惑力的组合,振保很快便被完全征服。</p> <p>后来娇蕊给王士洪去了封航空信,把一切都告诉了他,要他给她自由。</p> <p>却没想到振保会对她说:“不告诉我就写信给他,那是你错了……”</p> <p>振保逃了,娇蕊却依旧坚持离了婚,后来娇蕊也经历过一些男人,可从振保起,她学会了怎样爱,认真的…</p> <p>她觉得爱到底是好的,虽然吃了苦,以后还是要爱的…</p> </div><!-- /.entry-content --> </div><!-- /.entry-wrapper --> <nav class="pagination" role="navigation"> <a href="https://Hugo1030.github.io/articles/the-list-of-write/" class="btn" title="ch3 - 写作清单">向前</a> <a href="https://Hugo1030.github.io/articles/poem/" class="btn" title="ch5 - 月下洞庭">向后</a> </nav><!-- /.pagination --> </article> </div><!-- /#main --> <div class="footer-wrapper"> <footer role="contentinfo" class="entry-wrapper"> <span>&copy; 2017 沥川. Powered by <a href="http://jekyllrb.com" rel="nofollow">Jekyll</a> using the <a href="https://mademistakes.com/work/so-simple-jekyll-theme/" rel="nofollow">So Simple Theme</a>.</span> <div class="social-icons"> <a href="https://github.com/hugo1030" title="沥川 on Github" target="_blank"><i class="fa fa-github-square fa-2x"></i></a> <a href="https://Hugo1030.github.io/feed.xml" title="Atom/RSS feed"><i class="fa fa-rss-square fa-2x"></i></a> </div><!-- /.social-icons --> </footer> </div><!-- /.footer-wrapper --> <script type="text/javascript"> var BASE_URL = 'https://Hugo1030.github.io'; </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="https://Hugo1030.github.io/assets/js/vendor/jquery-1.9.1.min.js"><\/script>')</script> <script src="https://Hugo1030.github.io/assets/js/scripts.min.js"></script> </body> </html>
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>QNX</title> <link rel="stylesheet" href="gettingStarted.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Berkeley DB Installation and Build Guide" /> <link rel="up" href="build_unix.html" title="Chapter 7.  Building Berkeley DB for UNIX/POSIX" /> <link rel="prev" href="build_unix_macosx.html" title="Mac OS X" /> <link rel="next" href="build_unix_sco.html" title="SCO" /> </head> <body> <div xmlns="" class="navheader"> <div class="libver"> <p>Library Version 12.1.6.0</p> </div> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">QNX</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="build_unix_macosx.html">Prev</a> </td> <th width="60%" align="center">Chapter 7.  Building Berkeley DB for UNIX/POSIX </th> <td width="20%" align="right"> <a accesskey="n" href="build_unix_sco.html">Next</a></td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="build_unix_qnx"></a>QNX</h2> </div> </div> </div> <div class="orderedlist"> <ol type="1"> <li> <span class="bold"> <strong>To what versions of QNX has DB been ported?</strong> </span> <p>Berkeley DB has been ported to the QNX Neutrino technology which is commonly referred to as QNX RTP (Real-Time Platform). Berkeley DB has not been ported to earlier versions of QNX, such as QNX 4.25.</p> </li> <li> <span class="bold"> <strong>Building Berkeley DB shared libraries fails.</strong> </span> <p>The <code class="filename">/bin/sh</code> utility distributed with some QNX releases drops core when running the GNU libtool script (which is used to build Berkeley DB shared libraries). There are two workarounds for this problem: First, only build static libraries. You can disable building shared libraries by specifying the configuration flag when configuring Berkeley DB.</p> <p>Second, build Berkeley DB using an alternate shell. QNX distributions include an accessories disk with additional tools. One of the included tools is the GNU bash shell, which is able to run the libtool script. To build Berkeley DB using an alternate shell, move <code class="filename">/bin/sh</code> aside, link or copy the alternate shell into that location, configure, build and install Berkeley DB, and then replace the original shell utility.</p> </li> <li> <span class="bold"> <strong>Are there any QNX filesystem issues?</strong> </span> <p>Berkeley DB generates temporary files for use in transactionally protected file system operations. Due to the filename length limit of 48 characters in the QNX filesystem, applications that are using transactions should specify a database name that is at most 43 characters.</p> </li> <li> <span class="bold"> <strong>What are the implications of QNX's requirement to use <code class="literal">shm_open</code>(2) in order to use <code class="literal">mmap</code>(2)?</strong> </span> <p>QNX requires that files mapped with <code class="literal">mmap</code>(2) be opened using <code class="literal">shm_open</code>(2). There are other places in addition to the environment shared memory regions, where Berkeley DB tries to memory map files if it can.</p> <p>The memory pool subsystem normally attempts to use <code class="literal">mmap</code>(2) even when using private memory, as indicated by the <a href="../api_reference/C/envopen.html#envopen_DB_PRIVATE" class="olink">DB_PRIVATE</a> flag to <a href="../api_reference/C/envopen.html" class="olink">DB_ENV-&gt;open()</a>. In the case of QNX, if an application is using private memory, Berkeley DB will not attempt to map the memory and will instead use the local cache.</p> </li> <li> <span class="bold"> <strong>What are the implications of QNX's mutex implementation using microkernel resources?</strong> </span> <p>On QNX, the primitives implementing mutexes consume system resources. Therefore, if an application unexpectedly fails, those resources could leak. Berkeley DB solves this problem by always allocating mutexes in the persistent shared memory regions. Then, if an application fails, running recovery or explicitly removing the database environment by calling the <a href="../api_reference/C/envremove.html" class="olink">DB_ENV-&gt;remove()</a> method will allow Berkeley DB to release those previously held mutex resources. If an application specifies the <a href="../api_reference/C/envopen.html#envopen_DB_PRIVATE" class="olink">DB_PRIVATE</a> flag (choosing not to use persistent shared memory), and then fails, mutexes allocated in that private memory may leak their underlying system resources. Therefore, the <a href="../api_reference/C/envopen.html#envopen_DB_PRIVATE" class="olink">DB_PRIVATE</a> flag should be used with caution on QNX.</p> </li> <li> <span class="bold"> <strong>The make clean command fails to execute when building the Berkeley DB SQL interface.</strong> </span> <p>Remove the build directory manually to clean up and proceed. </p> </li> </ol> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="build_unix_macosx.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="build_unix.html">Up</a> </td> <td width="40%" align="right"> <a accesskey="n" href="build_unix_sco.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">Mac OS X </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top"> SCO</td> </tr> </table> </div> </body> </html>
@media print { .page { size: landscape; -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); } svg { display: none; } #header { display: none; } #menu { display: none; } #map_tabs { display: none; } #footer { display: none; } #left_col { display: none; } #roll_right { display: none; } #roll_right>img { display: none; } #geosearchDiv { display: none; } #mapToolBar { display: none; } #container { border: none; } #map { position: absolute; left: 0px; top: 0px; } .olControlModPanZoomBar { display: none; } .olControlOverviewMap { display: none; } .olControlPanel { display: none; } .olControlMousePosition { display: none; } }
/* Copyright (c) 2014 Intel Corporation. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION 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. Authors: Lei Yang <lei.a.yang@intel.com> Fan,Weiwei <weiwix.fan@intel.com> */ try { var demodb = "demodb" + new Date().getTime(); var db = openDatabaseSync (demodb, "1.0", demodb, 1024); if (!("changeVersion" in db)) { postMessage("changeVersion not in db"); } db.changeVersion("1.0", "1.1", function(t) { t.executeSql("CREATE TABLE mytab (id_number, content_string);"); t.executeSql("INSERT INTO mytab VALUES(1, 'the frist record');"); } ); if (db.version != "1.1") { postMessage("Database.changeVersion Fail"); } else { postMessage("PASS"); } } catch (ex) { postMessage("{Exception code: " + ex.code + "}"); }
package me.model; public enum EntityState { PROD("prodaccepted"), ACC("testaccepted"); private final String state; EntityState(String state) { this.state = state; } public String getState() { return state; } }
#ifndef __X86_64_ASM_DEFNS_H__ #define __X86_64_ASM_DEFNS_H__ #include <asm/percpu.h> #ifdef CONFIG_FRAME_POINTER /* Indicate special exception stack frame by inverting the frame pointer. */ #define SETUP_EXCEPTION_FRAME_POINTER \ movq %rsp,%rbp; \ notq %rbp #else #define SETUP_EXCEPTION_FRAME_POINTER #endif #ifndef NDEBUG #define ASSERT_INTERRUPT_STATUS(x) \ pushf; \ testb $X86_EFLAGS_IF>>8,1(%rsp); \ j##x 1f; \ ud2a; \ 1: addq $8,%rsp; #else #define ASSERT_INTERRUPT_STATUS(x) #endif #define ASSERT_INTERRUPTS_ENABLED ASSERT_INTERRUPT_STATUS(nz) #define ASSERT_INTERRUPTS_DISABLED ASSERT_INTERRUPT_STATUS(z) #define SAVE_ALL \ cld; \ pushq %rdi; \ pushq %rsi; \ pushq %rdx; \ pushq %rcx; \ pushq %rax; \ pushq %r8; \ pushq %r9; \ pushq %r10; \ pushq %r11; \ pushq %rbx; \ pushq %rbp; \ SETUP_EXCEPTION_FRAME_POINTER; \ pushq %r12; \ pushq %r13; \ pushq %r14; \ pushq %r15; #define RESTORE_ALL \ popq %r15; \ popq %r14; \ popq %r13; \ popq %r12; \ popq %rbp; \ popq %rbx; \ popq %r11; \ popq %r10; \ popq %r9; \ popq %r8; \ popq %rax; \ popq %rcx; \ popq %rdx; \ popq %rsi; \ popq %rdi; #ifdef PERF_COUNTERS #define PERFC_INCR(_name,_idx,_cur) \ pushq _cur; \ movslq VCPU_processor(_cur),_cur; \ pushq %rdx; \ leaq __per_cpu_offset(%rip),%rdx; \ movq (%rdx,_cur,8),_cur; \ leaq per_cpu__perfcounters(%rip),%rdx; \ addq %rdx,_cur; \ popq %rdx; \ incl ASM_PERFC_##_name*4(_cur,_idx,4); \ popq _cur #else #define PERFC_INCR(_name,_idx,_cur) #endif /* Work around AMD erratum #88 */ #define safe_swapgs \ "mfence; swapgs;" #ifdef __sun__ #define REX64_PREFIX "rex64\\" #else #define REX64_PREFIX "rex64/" #endif #define BUILD_SMP_INTERRUPT(x,v) XBUILD_SMP_INTERRUPT(x,v) #define XBUILD_SMP_INTERRUPT(x,v) \ __asm__( \ "\n"__ALIGN_STR"\n" \ ".globl " STR(x) "\n\t" \ STR(x) ":\n\t" \ "pushq $0\n\t" \ "movl $"#v",4(%rsp)\n\t" \ STR(SAVE_ALL) \ "movq %rsp,%rdi\n\t" \ "callq "STR(smp_##x)"\n\t" \ "jmp ret_from_intr\n"); #define BUILD_COMMON_IRQ() \ __asm__( \ "\n" __ALIGN_STR"\n" \ "common_interrupt:\n\t" \ STR(SAVE_ALL) \ "movq %rsp,%rdi\n\t" \ "callq " STR(do_IRQ) "\n\t" \ "jmp ret_from_intr\n"); #define IRQ_NAME2(nr) nr##_interrupt(void) #define IRQ_NAME(nr) IRQ_NAME2(IRQ##nr) #define BUILD_IRQ(nr) \ void IRQ_NAME(nr); \ __asm__( \ "\n"__ALIGN_STR"\n" \ STR(IRQ) #nr "_interrupt:\n\t" \ "pushq $0\n\t" \ "movl $"#nr",4(%rsp)\n\t" \ "jmp common_interrupt"); #define GET_CPUINFO_FIELD(field,reg) \ movq $~(STACK_SIZE-1),reg; \ andq %rsp,reg; \ orq $(STACK_SIZE-CPUINFO_sizeof+field),reg; #define GET_CURRENT(reg) \ GET_CPUINFO_FIELD(CPUINFO_current_vcpu,reg) \ movq (reg),reg; #ifdef __ASSEMBLY__ # define _ASM_EX(p) p-. #else # define _ASM_EX(p) #p "-." #endif #endif /* __X86_64_ASM_DEFNS_H__ */
(function () { 'use strict'; angular .module('clients') .run(menuConfig); menuConfig.$inject = ['menuService']; function menuConfig(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', { title: 'Clientes', state: 'clients', type: 'dropdown', roles: ['user'] }); // Add the dropdown list item Menus.addSubMenuItem('topbar', 'clients', { title: 'Listar Clientes', state: 'clients.list' }); // Add the dropdown create item Menus.addSubMenuItem('topbar', 'clients', { title: 'Crear Clientes', state: 'clients.create', roles: ['user'] }); } })();
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // FEA co-rotational tire constructed with data from file (JSON format). // The mesh data is assumed to be provided through an Abaqus INP file. // // ============================================================================= #ifndef FEA_TIRE_H #define FEA_TIRE_H #include "chrono_vehicle/wheeled_vehicle/tire/ChFEATire.h" #include "chrono_thirdparty/rapidjson/document.h" namespace chrono { namespace vehicle { /// @addtogroup vehicle_wheeled_tire /// @{ /// ANCF tire constructed with data from file (JSON format). class CH_VEHICLE_API FEATire : public ChFEATire { public: FEATire(const std::string& filename); FEATire(const rapidjson::Document& d); ~FEATire() {} /// Get the tire radius. virtual double GetRadius() const override { return m_tire_radius; } /// Get the rim radius (inner tire radius). virtual double GetRimRadius() const override { return m_rim_radius; } /// Get the tire width. virtual double GetWidth() const override { return m_rim_width; } /// Get the default tire pressure. virtual double GetDefaultPressure() const override { return m_default_pressure; } /// Return list of internal nodes. /// These nodes define the mesh surface over which pressure loads are applied. virtual std::vector<std::shared_ptr<fea::ChNodeFEAbase>> GetInternalNodes() const override; /// Return list of nodes connected to the rim. virtual std::vector<std::shared_ptr<fea::ChNodeFEAbase>> GetConnectedNodes() const override; /// Create the FEA nodes and elements. /// The wheel rotational axis is assumed to be the Y axis. virtual void CreateMesh(const ChFrameMoving<>& wheel_frame, ///< frame of associated wheel VehicleSide side ///< left/right vehicle side ) override; private: void ProcessJSON(const rapidjson::Document& d); double m_tire_radius; double m_rim_radius; double m_rim_width; double m_default_pressure; std::shared_ptr<fea::ChContinuumElastic> m_material; std::string m_input_file; std::vector<std::vector<std::shared_ptr<fea::ChNodeFEAbase>>> m_node_sets; }; /// @} vehicle_wheeled_tire } // end namespace vehicle } // end namespace chrono #endif
'use strict'; angular.module('moreOnApp') .factory('User', function ($resource) { return $resource('/api/users/:id/:controller', { id: '@_id' }, { changePassword: { method: 'PUT', params: { controller:'password' } }, get: { method: 'GET', params: { id:'me' } } }); });
package model; import java.util.List; import controller.TurtleCommand; import controller.TurtleTrace; public interface TurtleTraceInterface { public TurtleTrace getTurtleTrace(); public void updateTurtleTrace(List<TurtleCommand> turtleCommand); }
# -*- encoding: utf-8 -*- module RSpec module Mocks module ArgumentMatchers def an_onstomp_frame(command=false, header_arr=false, body=false) OnStompFrameMatcher.new(command, header_arr, body).tap do |m| m.match_command = command != false m.match_headers = header_arr != false m.match_body = body != false end end class OnStompFrameMatcher attr_accessor :match_command, :match_body, :match_headers def initialize(com, header_arr, body) @match_command = @match_body = @match_headers = true @expected = OnStomp::Components::Frame.new(com, {}, body) header_arr = [header_arr] if header_arr.is_a?(Hash) header_arr.each do |h| @expected.headers.merge!(h) end if header_arr.is_a?(Array) end def ==(actual) actual.is_a?(@expected.class) && matches_command(actual) && matches_headers(actual) && matches_body(actual) end def matches_command actual !match_command || actual.command == @expected.command end def matches_body actual !match_body || actual.body == @expected.body end def matches_headers actual !match_headers || @expected.headers.to_hash.keys.all? { |k| @expected[k] == actual[k] } end def description frame_desc = match_command ? "#{@expected.command} frame" : "Any frame" header_desc = match_headers ? " with headers #{@expected.headers.to_hash.inspect}" : '' body_desc = match_body ? " and body '#{@expected.body}'" : '' [frame_desc, header_desc, body_desc].join end end end end end
declare interface ILatestOrdersStrings { PropertyPaneDescription: string; BasicGroupName: string; DescriptionFieldLabel: string; } declare module 'latestOrdersStrings' { const strings: ILatestOrdersStrings; export = strings; }
// --------------------------------------------------------------------- // // Copyright (C) 2001 - 2015 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include "../tests.h" #include <deal.II/base/quadrature_lib.h> #include <deal.II/base/logstream.h> #include <deal.II/lac/vector.h> #include <deal.II/grid/tria.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/dofs/dof_handler.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_system.h> #include <deal.II/fe/mapping_q1_eulerian.h> #include <deal.II/fe/fe_values.h> #include <vector> #include <fstream> #include <string> template<int dim> inline void show_values(FiniteElement<dim> &fe, const char *name) { deallog.push (name); Triangulation<dim> tr; GridGenerator::hyper_cube(tr, 2., 5.); // shift one point of the cell // somehow if (dim > 1) tr.begin_active()->vertex(dim==2 ? 3 : 5)(dim-1) += 1./std::sqrt(2.); DoFHandler<dim> dof(tr); dof.distribute_dofs(fe); // construct the MappingQ1Eulerian // object FESystem<dim> mapping_fe(FE_Q<dim>(1), dim); DoFHandler<dim> flowfield_dof_handler(tr); flowfield_dof_handler.distribute_dofs(mapping_fe); Vector<double> map_points(flowfield_dof_handler.n_dofs()); MappingQ1Eulerian<dim> mapping(map_points, flowfield_dof_handler); QGauss<dim> quadrature_formula(2); FEValues<dim> fe_values(mapping, fe, quadrature_formula, UpdateFlags(update_values | update_JxW_values | update_gradients | update_hessians)); typename DoFHandler<dim>::cell_iterator c = dof.begin(); fe_values.reinit(c); for (unsigned int k=0; k<quadrature_formula.size(); ++k) { deallog << quadrature_formula.point(k) << std::endl; deallog << "JxW: " << fe_values.JxW(k) << std::endl; for (unsigned int i=0; i<fe.dofs_per_cell; ++i) { deallog << "Values: " << fe_values.shape_value(i,k); deallog << ", Grad: " << fe_values.shape_grad(i,k); deallog << ", 2nd: " << fe_values.shape_hessian(i,k); deallog << std::endl; } } deallog.pop (); } template<int dim> void show_values() { FE_Q<dim> q1(1); show_values(q1, "Q1"); FE_Q<dim> q2(2); show_values(q2, "Q2"); } int main() { std::ofstream logfile ("output"); deallog << std::setprecision(2); deallog << std::fixed; deallog.attach(logfile); deallog.threshold_double(1.e-10); deallog.push ("1d"); show_values<1>(); deallog.pop (); deallog.push ("2d"); show_values<2>(); deallog.pop (); deallog.push ("3d"); show_values<3>(); deallog.pop (); return 0; }
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2017 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef _U2_VCFUTILSSUPPORT_H_ #define _U2_VCFUTILSSUPPORT_H_ #include <U2Core/ExternalToolRegistry.h> namespace U2 { class VcfutilsSupport : public ExternalTool { Q_OBJECT public: VcfutilsSupport(const QString &name); static const QString TOOL_NAME; }; } // U2 #endif // _U2_VCFUTILSSUPPORT_H_
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_31) on Fri Oct 23 22:05:54 AEST 2015 --> <title>Uses of Class dataStructures.SingularPair</title> <meta name="date" content="2015-10-23"> <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class dataStructures.SingularPair"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../dataStructures/SingularPair.html" title="class in dataStructures">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?dataStructures/class-use/SingularPair.html" target="_top">Frames</a></li> <li><a href="SingularPair.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class dataStructures.SingularPair" class="title">Uses of Class<br>dataStructures.SingularPair</h2> </div> <div class="classUseContainer">No usage of dataStructures.SingularPair</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../dataStructures/SingularPair.html" title="class in dataStructures">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?dataStructures/class-use/SingularPair.html" target="_top">Frames</a></li> <li><a href="SingularPair.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
/* * Copyright (c) 2010, Kingsoft Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 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. */ #ifndef SquirrelBindingsUtils_h #define SquirrelBindingsUtils_h #include "squirrel.h" struct ScriptClassMemberDecl { const SQChar *name; SQFUNCTION func; int params; const SQChar *typemask; }; struct SquirrelClassDecl { const SQChar *name; const SQChar *base; const ScriptClassMemberDecl *members; }; struct ScriptConstantDecl { const SQChar *name; SQObjectType type; union value { value(float v){ f = v; } value(int v){ i = v; } value(const SQChar *v){ s = v; } float f; int i; const SQChar *s; }val; }; struct ScriptNamespaceDecl { const SQChar *name; const ScriptClassMemberDecl *members; const ScriptConstantDecl *constants; const ScriptClassMemberDecl *delegate; }; #define _BEGIN_CLASS(classname) \ int SQUIRREL_CALL __##classname##__typeof(HSQUIRRELVM v) \ { \ sq_pushstring(v,_SC(#classname),-1); \ return 1; \ } \ struct ScriptClassMemberDecl __##classname##_members[] = { \ {_SC("_typeof"),__##classname##__typeof,1,NULL}, #define _BEGIN_NAMESPACE(xnamespace) struct ScriptClassMemberDecl __##xnamespace##_members[] = { #define _BEGIN_NAMESPACE_CONSTANTS(xnamespace) {NULL,NULL,NULL,NULL}}; \ struct ScriptConstantDecl __##xnamespace##_constants[] = { #define _BEGIN_DELEGATE(xnamespace) struct ScriptClassMemberDecl __##xnamespace##_delegate[] = { #define _DELEGATE(xnamespace) __##xnamespace##_delegate #define _END_DELEGATE(classname) {NULL,NULL,NULL,NULL}}; #define _CONSTANT(name,type,val) {_SC(#name),type,val}, #define _CONSTANT_IMPL(name,type) {_SC(#name),type,name}, #define _MEMBER_FUNCTION(classname,name,nparams,typemask) \ {_SC(#name),__##classname##_##name,nparams,typemask}, #define _END_NAMESPACE(classname,delegate) {NULL,OT_NULL,0}}; \ struct ScriptNamespaceDecl __##classname##_decl = { \ _SC(#classname), __##classname##_members,__##classname##_constants,delegate }; #define _END_CLASS(classname) {NULL,NULL,NULL,NULL}}; \ struct SquirrelClassDecl __##classname##_decl = { \ _SC(#classname), NULL, __##classname##_members }; #define _END_CLASS_INHERITANCE(classname,base) {NULL,NULL,NULL,NULL}}; \ struct SquirrelClassDecl __##classname##_decl = { \ _SC(#classname), _SC(#base), __##classname##_members }; #define _MEMBER_FUNCTION_IMPL(classname,name) \ SQInteger SQUIRREL_CALL __##classname##_##name(HSQUIRRELVM v) #define _INIT_STATIC_NAMESPACE(v,classname) SbuCreateStaticNamespace(v,&__##classname##_decl); #define _INIT_CLASS(v,classname) SbuCreateClass(v,&__##classname##_decl); #define _DECL_STATIC_NAMESPACE(xnamespace) extern struct ScriptNamespaceDecl __##xnamespace##_decl; #define _DECL_CLASS(classname) extern struct SquirrelClassDecl __##classname##_decl; #define _CHECK_SELF(cppclass,scriptclass) \ cppclass *self = NULL; \ if(SQ_FAILED(sq_getinstanceup(v,1,(SQUserPointer*)&self,(SQUserPointer)&__##scriptclass##_decl))) { \ return sq_throwerror(v,_SC("invalid instance type"));\ } #define _CHECK_INST_PARAM(pname,idx,cppclass,scriptclass) \ cppclass *pname = NULL; \ if(SQ_FAILED(sq_getinstanceup(v,idx,(SQUserPointer*)&pname,(SQUserPointer)&__##scriptclass##_decl))) { \ return sq_throwerror(v,_SC("invalid instance type"));\ } \ #define _CHECK_INST_PARAM_BREAK(pname,idx,cppclass,scriptclass) \ cppclass *pname = NULL; \ if(SQ_FAILED(sq_getinstanceup(v,idx,(SQUserPointer*)&pname,(SQUserPointer)&__##scriptclass##_decl))) { \ break; \ } \ #define _CLASS_TAG(classname) ((unsigned int)&__##classname##_decl) #define _DECL_NATIVE_CONSTRUCTION(v,classname,cppclass) \ BOOL push_##classname(v,cppclass &quat); \ SquirrelObject new_##classname(cppclass &quat); #define _IMPL_NATIVE_CONSTRUCTION(classname,cppclass) \ static int SQUIRREL_CALL classname##_release_hook(SQUserPointer p, int size) \ { \ if(p) { \ cppclass *pv = (cppclass *)p; \ delete pv; \ } \ return 0; \ } \ BOOL push_##classname(HSQUIRRELVM v,cppclass &quat) \ { \ cppclass *newquat = new cppclass; \ *newquat = quat; \ if(!SbuCreateNativeClassInstance(v,_SC(#classname),newquat,classname##_release_hook)) { \ delete newquat; \ return FALSE; \ } \ return TRUE; \ } \ SquirrelObject new_##classname(HSQUIRRELVM v,cppclass &quat) \ { \ SquirrelObject ret(v); \ if(push_##classname(v,quat)) { \ ret.AttachToStackObject(-1); \ sq_pop(v, 1); \ } \ return ret; \ } \ int construct_##classname(HSQUIRRELVM v,cppclass *p) \ { \ sq_setinstanceup(v,1,p); \ sq_setreleasehook(v,1,classname##_release_hook); \ return 1; \ } #define _RETURN_THIS(idx) HSQOBJECT returnThisObj;\ sq_getstackobj(v, idx, &returnThisObj);\ ASSERT(OT_INSTANCE == returnThisObj._type);\ sq_pushobject(v, returnThisObj);\ return 1; #define _DECLARE_REFCOUNTED_NEW(v,cppclass,classname) \ SquirrelObject new_##classname(cppclass *ptr) { \ if(SbuCreateRefCountedInstance(v,_SC(#classname),ptr)) { \ HSQOBJECT o; \ sq_getstackobj(v,-1,&o); \ SquirrelObject tmp = o; \ sq_pop(v,1); \ return tmp; \ } \ return SquirrelObject(v) ; \ } #define _RETURN_REFCOUNTED_INSTANCE(v,classname,ptr) \ if(!SbuCreateRefCountedInstance(v,_SC(#classname),ptr)) { \ return sa.ThrowError(_SC("cannot create the class instance")); \ } \ return 1; #ifdef __cplusplus extern "C" { #endif struct IUnknown; //SQUIRREL_API BOOL SQUIRREL_CALL SbuCreateStaticClass(HSQUIRRELVM v,SquirrelClassDecl *cd); SQUIRREL_API BOOL SQUIRREL_CALL SbuCreateStaticNamespace(HSQUIRRELVM v,ScriptNamespaceDecl *sn); SQUIRREL_API BOOL SQUIRREL_CALL SbuCreateClass(HSQUIRRELVM v,SquirrelClassDecl *cd); //SQUIRREL_API BOOL SQUIRREL_CALL SbuInitScriptClasses(HSQUIRRELVM v); SQUIRREL_API BOOL SQUIRREL_CALL SbuCreateNativeClassInstance(HSQUIRRELVM v,const SQChar *classname,SQUserPointer ud,SQRELEASEHOOK hook); SQUIRREL_API BOOL SQUIRREL_CALL SbuCreateRefCountedInstance(HSQUIRRELVM v,const SQChar *classname,IUnknown *pRC); //SQUIRREL_API BOOL SQUIRREL_CALL SbuCreateRefCountedInstanceChached(HSQUIRRELVM v,const SQChar *classname,IUnknown *pRC); SQUIRREL_API SQInteger SQUIRREL_CALL SbuRegisterGlobalFunc(HSQUIRRELVM v, SQFUNCTION f, const SQChar* fname); int SQUIRREL_CALL refcounted_release_hook(SQUserPointer p, int size); int SQUIRREL_CALL construct_RefCounted(HSQUIRRELVM v, IUnknown *p); SQUIRREL_API void* SQUIRREL_CALL SbuGetPagePtr(HSQUIRRELVM v); SQUIRREL_API void* SQUIRREL_CALL SbuGetKdPageHandle(HSQUIRRELVM v); SQUIRREL_API HWND SQUIRREL_CALL SbuGetHWND(HSQUIRRELVM v); #ifdef __cplusplus } /*extern "C"*/ #endif #endif // SquirrelBindingsUtils_h
<?php namespace Drupal\Module\udashboard; use Drupal\Core\DependencyInjection\ServiceProviderInterface; use MakinaCorpus\Drupal\Dashboard\DependencyInjection\Compiler\ActionProviderRegisterPass; use MakinaCorpus\Drupal\Dashboard\DependencyInjection\Compiler\PageBuilderRegisterPass; use MakinaCorpus\Drupal\Dashboard\DependencyInjection\Compiler\PortletRegisterPass; use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * Implements Drupal 8 service provider. */ class ServiceProvider implements ServiceProviderInterface { /** * {@inheritdoc} */ public function register(ContainerBuilder $container) { $container->addCompilerPass(new ActionProviderRegisterPass()); $container->addCompilerPass(new PageBuilderRegisterPass(), PassConfig::TYPE_BEFORE_REMOVING); $container->addCompilerPass(new PortletRegisterPass()); } }
 ######################################################################################### class Metrics: """Commonly used evaluation metrics""" header_template = '{:8} {:8} {:8} {:8} {:8} {:8} {:8}' line_template = '{:8.4f} {:8.4f} {:8.4f} {:8.2f} {:8.2f} {:8.0f} {:8.0f}' def __init__(self): """Initialize the empty metrics object""" # True positive used in recall calculation self.tp_std = 0.0 # True positive used in precision calculation self.tp_test = 0.0 # Number of standard objects self.n_std = 0 # Number of test objects self.n_test = 0 # Precision self.precision = 1.0 # Recall self.recall = 1.0 # F1 self.f1 = 1.0 def recalculate(self): self.precision = self.tp_test / self.n_test if self.n_test > 0 else 1.0 self.recall = self.tp_std / self.n_std if self.n_std > 0 else 1.0 if self.n_std + self.n_test == 0: self.f1 = 1.0 else: denominator = self.precision + self.recall self.f1 = ( (2 * self.precision * self.recall / denominator) if denominator > 0 else 0.0 ) isValid = lambda x: x >= 0 and x <= 1 assert(isValid(self.precision)) assert(isValid(self.recall)) assert(isValid(self.f1)) def add(self, other): self.tp_std += other.tp_std self.tp_test += other.tp_test self.n_std += other.n_std self.n_test += other.n_test self.recalculate() def toLine(self): """Returns a line for the stats table""" return Metrics.line_template.format( self.precision, self.recall, self.f1, self.tp_std, self.tp_test, self.n_std, self.n_test) @classmethod def header(cls): """Returns a header for the stats table""" return Metrics.header_template.format( 'P', 'R', 'F1', 'TP1', 'TP2', 'In Std.', 'In Test.') @classmethod def createSimple(cls, tp, n_std, n_test): """Calculate metrics with single TruePositive value""" m = cls() m.tp_std = tp m.tp_test = tp m.n_std = n_std m.n_test = n_test m.recalculate() return m @classmethod def create(cls, tp_std, tp_test, n_std, n_test): """Calculate metrics with separate TruePositive values""" m = cls() m.tp_std = tp_std m.tp_test = tp_test m.n_std = n_std m.n_test = n_test m.recalculate() return m
<html> <head> <title> </title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <link href="css/main-style.css" rel="stylesheet" type="text/css"> </head> <body> <div class="main-container"> <div class="container-small"> <nav> <ol class="cd-multi-steps text-bottom count"> <li class="visited"> <a href="#0"> Campaign Definition </a> </li> <li class="visited" > <a href="#0"> Target Groups </a> </li> <li class="visited"> <a href="#0"> Campaign Details </a> </li> <li class="visited"> <a href="#0"> Incentives </a> </li> <li class="current"> <a href="#0"> Targets </a> </li> </ol> </nav> <form class="target-form" method="post"> <p> Please define campaign goals </p> <div class="rTable1"> <div class="rTable1Row"> <div class="rTable1Head"> Target Group </div> <div class="rTable1Head"> Population </div> <div class="rTable1Head"> Responses required </div> <div class="rTable1Head"> Estimated Cost </div> </div> <div class="rTable1Row"> <div class="rTable1Cell"> TG 1 </div> <div class="rTable1Cell"> 1.2 million </div> <div class="rTable1Cell"> 800 </div> <div class="rTable1Cell"> $6400 </div> </div> <div class="rTable1Row"> <div class="rTable1Cell"> TG 1 </div> <div class="rTable1Cell"> 1.2 million </div> <div class="rTable1Cell"> 800 </div> <div class="rTable1Cell"> $6400 </div> </div> <div class="rTable1Row"> <div class="rTable1Cell"> TG 1 </div> <div class="rTable1Cell"> 1.2 million </div> <div class="rTable1Cell"> 800 </div> <div class="rTable1Cell"> $6400 </div> </div> <div class="rTable1Row"> <div class="rTable1Cell"> Total </div> <div class="rTable1Cell"> 1.2 million </div> <div class="rTable1Cell"> 800 </div> <div class="rTable1Cell"> $6400 </div> </div> </div> <div class="bottom-btn"> <a href="thank-you.html" target="_self"><input type="button" value="Launch" name="Launch"></a> </div> </form> </div> </div> </body> </html>
import sys from .. import signals from ..chainsend import lazy_send from ..compat import throw_method as _throw_method from ..primitives.linker import LinkPrimitives class ChainLink(object): r""" BaseClass for elements in a chain A chain is created by binding :py:class:`ChainLink`\ s together. This is a directional process: a binding is always made between parent and child. Each child can be the parent to another child, and vice versa. The direction dictates how data is passed along the chain: * A parent may :py:meth:`send` a data chunk to a child. * A child may pull the :py:func:`next` data chunk from the parent. Chaining is done with ``>>`` and ``<<`` operators as ``parent >> child`` and ``child << parent``. Forking and joining of chains requires a sequence of multiple elements as parent or child. .. describe:: parent >> child child << parent Bind ``child`` and ``parent``. Both directions of the statement are equivalent: if ``a`` is made a child of ``b``, then `b`` is made a parent of ``a``, and vice versa. .. describe:: parent >> (child_a, child_b, ...) parent >> [child_a, child_b, ...] parent >> {child_a, child_b, ...} Bind ``child_a``, ``child_b``, etc. as children of ``parent``. .. describe:: (parent_a, parent_b, ...) >> child [parent_a, parent_b, ...] >> child {parent_a, parent_b, ...} >> child Bind ``parent_a``, ``parent_b``, etc. as parents of ``child``. Aside from binding, every :py:class:`ChainLink` implements the `Generator-Iterator Methods`_ interface: .. method:: iter(link) Create an iterator over all data chunks that can be created. Empty results are ignored. .. method:: link.__next__() link.send(None) next(link) Create a new chunk of data. Raise :py:exc:`StopIteration` if there are no more chunks. Implicitly used by ``next(link)``. .. method:: link.send(chunk) Process a data ``chunk``, and return the result. .. note:: The ``next`` variants contrast with ``iter`` by also returning empty chunks. Use variations of ``next(iter(link))`` for an explicit iteration. .. method:: link.chainlet_send(chunk) Process a data ``chunk`` locally, and return the result. This method implements data processing in an element; subclasses must overwrite it to define how they handle data. This method should only be called to explicitly traverse elements in a chain. Client code should use ``next(link)`` and ``link.send(chunk)`` instead. .. method:: link.throw(type[, value[, traceback]]) Raises an exception of ``type`` inside the link. The link may either return a final result (including :py:const:`None`), raise :py:exc:`StopIteration` if there are no more results, or propagate any other, unhandled exception. .. method:: link.close() Close the link, cleaning up any resources.. A closed link may raise :py:exc:`RuntimeError` if data is requested via ``next`` or processed via ``send``. When used in a chain, each :py:class:`ChainLink` is distinguished by its handling of input and output. There are two attributes to signal the behaviour when chained. These specify whether the element performs a `1 -> 1`, `n -> 1`, `1 -> m` or `n -> m` processing of data. .. py:attribute:: chain_join A :py:class:`bool` indicating that the element expects the values of all preceding elements at once. That is, the `chunk` passed in via :py:meth:`send` is an *iterable* providing the return values of the previous elements. .. py:attribute:: chain_fork A :py:class:`bool` indicating that the element produces several values at once. That is, the return value is an *iterable* of data chunks, each of which should be passed on independently. To prematurely stop the traversal of a chain, `1 -> n` and `n -> m` elements should return an empty container. Any `1 -> 1` and `n -> 1` element must raise :py:exc:`StopTraversal`. .. _Generator-Iterator Methods: https://docs.python.org/3/reference/expressions.html#generator-iterator-methods """ chain_types = LinkPrimitives() #: whether this element processes several data chunks at once chain_join = False #: whether this element produces several data chunks at once chain_fork = False __slots__ = () def _link(self, parent, child): """Link the chainlinks parent to child""" return self.chain_types.link(parent, child) def __rshift__(self, child): """ self >> child :param child: following link to bind :type child: ChainLink or iterable[ChainLink] :returns: link between self and child :rtype: ChainLink, FlatChain, Bundle or Chain """ child = self.chain_types.convert(child) return self._link(self, child) def __rrshift__(self, parent): # parent >> self return self << parent def __lshift__(self, parent): """ self << parent :param parent: preceding link to bind :type parent: ChainLink or iterable[ChainLink] :returns: link between self and children :rtype: ChainLink, FlatChain, Bundle or Chain """ parent = self.chain_types.convert(parent) return self._link(parent, self) def __rlshift__(self, child): # child << self return self >> child def __iter__(self): if self.chain_fork: return self._iter_fork() return self._iter_flat() def _iter_flat(self): while True: try: yield self.chainlet_send(None) except signals.StopTraversal: continue except StopIteration: break def _iter_fork(self): while True: try: result = list(self.chainlet_send(None)) if result: yield result except (StopIteration, signals.ChainExit): break def __next__(self): return self.send(None) if sys.version_info < (3,): def next(self): return self.__next__() def send(self, value=None): """Send a single value to this element for processing""" if self.chain_fork: return self._send_fork(value) return self._send_flat(value) def _send_flat(self, value=None): try: return self.chainlet_send(value) except signals.StopTraversal: return None def _send_fork(self, value=None): return list(self.chainlet_send(value)) def dispatch(self, values): """Dispatch multiple values to this element for processing""" for result in lazy_send(self, values): yield result def chainlet_send(self, value=None): """Send a value to this element for processing""" raise NotImplementedError # overwrite in subclasses throw = _throw_method def close(self): """Close this element, freeing resources and possibly blocking further interactions""" pass def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() return False ChainLink.chain_types.base_link_type = ChainLink
<?php // Emojies & $this->shortcuts replacement logic. // // Note: In theory, it could be faster to parse :smile: in inline chain and // leave only $this->shortcuts here. But, who care... // namespace Kaoken\MarkdownIt\Plugins\Emoji; use Kaoken\MarkdownIt\MarkdownIt; use Kaoken\MarkdownIt\RulesCore\StateCore; class Replace { protected $emojies; protected $shortcuts; protected $scanRE; protected $replaceRE; /** * Replace constructor. * @param MarkdownIt $md * @param array $emojies * @param array $shortcuts * @param string $scanRE * @param string $replaceRE */ public function __construct(MarkdownIt $md, array &$emojies, array &$shortcuts, string &$scanRE, string &$replaceRE) { $this->emojies = $emojies; $this->shortcuts = $shortcuts; $this->scanRE = $scanRE; $this->replaceRE = $replaceRE; } /** * @param StateCore $state * @param string $text * @param int $level * @return array */ protected function splitTextToken(StateCore &$state, string $text, int $level): array { $last_pos = 0; $nodes = []; if(preg_match_all($this->replaceRE,$text,$m,PREG_SET_ORDER|PREG_OFFSET_CAPTURE)) { foreach ($m as &$match) { $match = $match[0]; $offset = $match[1]; // Validate emoji name if ( isset($this->shortcuts[$match[0]]) ) { // replace shortcut with full name $emoji_name = $this->shortcuts[$match[0]]; // Don't allow letters before any shortcut (as in no ":/" in http://) if ($offset > 0 && !preg_match("/\p{Z}|\p{P}|\p{Cc}/u", $text[$offset - 1] )) { continue; } // Don't allow letters after any shortcut if ($offset + strlen($match[0]) < strlen($text) && !preg_match("/\p{Z}|\p{P}|\p{Cc}/u", $text[$offset + strlen($match[0])] )) { continue; } } else { $emoji_name = substr($match[0], 1, -1); } // Add new $tokens to pending list if ($offset > $last_pos) { $token = $state->createToken('text', '', 0); $token->content = substr($text, $last_pos, $offset-$last_pos); $nodes[] = $token; } $token = $state->createToken('emoji', '', 0); $token->markup = $emoji_name; $token->content = $this->emojies[$emoji_name] ?? 'error'; $nodes[] = $token; $last_pos = $offset + strlen($match[0]); } } if ($last_pos < strlen($text)) { $token = $state->createToken('text', '', 0); $token->content = substr($text, $last_pos); $nodes[] = $token; } return $nodes; } /** * @param StateCore $state */ public function replace(StateCore &$state) { $blockTokens = &$state->tokens; $autolinkLevel = 0; for ($j = 0, $l = count($blockTokens); $j < $l; $j++) { if ($blockTokens[$j]->type !== 'inline') { continue; } $tokens = &$blockTokens[$j]->children; // We scan from the end, to keep position when new tags added. // Use reversed logic in links start/end $match for ($i = count($tokens) - 1; $i >= 0; $i--) { $token = $tokens[$i]; if ($token->type === 'link_open' || $token->type === 'link_close') { if ($token->info === 'auto') { $autolinkLevel -= $token->nesting; } } if ($token->type === 'text' && $autolinkLevel === 0 && preg_match($this->scanRE, $token->content)) { // replace current node $blockTokens[$j]->children = $tokens = $state->md->utils->arrayReplaceAt( $tokens, $i, $this->splitTextToken($state, $token->content, $token->level) ); } } } } }
/* * Copyright (C) 2016-2022 ActionTech. * based on code by MyCATCopyrightHolder Copyright (c) 2013, OpenCloudDB/MyCAT. * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher. */ package com.actiontech.dble; import com.actiontech.dble.util.ExecutorUtil; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicLong; /** * @author mycat */ public class ExecutorTestMain { public static void main(String[] args) { final AtomicLong count = new AtomicLong(0L); final ThreadPoolExecutor executor = ExecutorUtil.createFixed("TestExecutor", 5); new Thread() { @Override public void run() { for (; ; ) { long c = count.get(); try { Thread.sleep(5000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("count:" + (count.get() - c) / 5); System.out.println("active:" + executor.getActiveCount()); System.out.println("queue:" + executor.getQueue().size()); System.out.println("============================"); } } }.start(); new Thread() { @Override public void run() { for (; ; ) { executor.execute(new Runnable() { @Override public void run() { count.incrementAndGet(); } }); } } }.start(); new Thread() { @Override public void run() { for (; ; ) { executor.execute(new Runnable() { @Override public void run() { count.incrementAndGet(); } }); } } }.start(); } }
import { JSDOM } from 'jsdom'; import config from '../config'; import { intersperse } from '../prelude/array'; import { MfmForest, MfmTree } from './prelude'; import { IMentionedRemoteUsers } from '../models/entities/note'; import { wellKnownServices } from '../well-known-services'; export function toHtml(tokens: MfmForest | null, mentionedRemoteUsers: IMentionedRemoteUsers = []) { if (tokens == null) { return null; } const { window } = new JSDOM(''); const doc = window.document; function appendChildren(children: MfmForest, targetElement: any): void { for (const child of children.map(t => handlers[t.node.type](t))) targetElement.appendChild(child); } const handlers: { [key: string]: (token: MfmTree) => any } = { bold(token) { const el = doc.createElement('b'); appendChildren(token.children, el); return el; }, small(token) { const el = doc.createElement('small'); appendChildren(token.children, el); return el; }, strike(token) { const el = doc.createElement('del'); appendChildren(token.children, el); return el; }, italic(token) { const el = doc.createElement('i'); appendChildren(token.children, el); return el; }, fn(token) { const el = doc.createElement('i'); appendChildren(token.children, el); return el; }, blockCode(token) { const pre = doc.createElement('pre'); const inner = doc.createElement('code'); inner.textContent = token.node.props.code; pre.appendChild(inner); return pre; }, center(token) { const el = doc.createElement('div'); appendChildren(token.children, el); return el; }, emoji(token) { return doc.createTextNode(token.node.props.emoji ? token.node.props.emoji : `\u200B:${token.node.props.name}:\u200B`); }, hashtag(token) { const a = doc.createElement('a'); a.href = `${config.url}/tags/${token.node.props.hashtag}`; a.textContent = `#${token.node.props.hashtag}`; a.setAttribute('rel', 'tag'); return a; }, inlineCode(token) { const el = doc.createElement('code'); el.textContent = token.node.props.code; return el; }, mathInline(token) { const el = doc.createElement('code'); el.textContent = token.node.props.formula; return el; }, mathBlock(token) { const el = doc.createElement('code'); el.textContent = token.node.props.formula; return el; }, link(token) { const a = doc.createElement('a'); a.href = token.node.props.url; appendChildren(token.children, a); return a; }, mention(token) { const a = doc.createElement('a'); const { username, host, acct } = token.node.props; const wellKnown = wellKnownServices.find(x => x[0] === host); if (wellKnown) { a.href = wellKnown[1](username); } else { const remoteUserInfo = mentionedRemoteUsers.find(remoteUser => remoteUser.username === username && remoteUser.host === host); a.href = remoteUserInfo ? (remoteUserInfo.url ? remoteUserInfo.url : remoteUserInfo.uri) : `${config.url}/${acct}`; a.className = 'u-url mention'; } a.textContent = acct; return a; }, quote(token) { const el = doc.createElement('blockquote'); appendChildren(token.children, el); return el; }, text(token) { const el = doc.createElement('span'); const nodes = (token.node.props.text as string).split(/\r\n|\r|\n/).map(x => doc.createTextNode(x) as Node); for (const x of intersperse<Node | 'br'>('br', nodes)) { el.appendChild(x === 'br' ? doc.createElement('br') : x); } return el; }, url(token) { const a = doc.createElement('a'); a.href = token.node.props.url; a.textContent = token.node.props.url; return a; }, search(token) { const a = doc.createElement('a'); a.href = `https://www.google.com/search?q=${token.node.props.query}`; a.textContent = token.node.props.content; return a; } }; appendChildren(tokens, doc.body); return `<p>${doc.body.innerHTML}</p>`; }
/** * Copyright (C) 2014 Politecnico di Milano (michele.guerriero@mail.polimi.it) * * 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 it.polimi.modaclouds.recedingHorizonScaling4Cloud.sshConnector; import it.polimi.modaclouds.recedingHorizonScaling4Cloud.util.ConfigManager; import java.util.List; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Shell { protected static final Logger journal = LoggerFactory.getLogger(Shell.class); public static final int SSH_PORT = 22; protected String ip; protected String user; protected String password; protected String key; public Shell(String ip, String user, String password, String key) { this.ip = ip; this.user = user; this.password = password; this.key = key; } public Shell() { this(ConfigManager.SSH_HOST, ConfigManager.SSH_USER_NAME, ConfigManager.SSH_PASSWORD, null); } public List<String> exec(String command) throws Exception { long init = System.currentTimeMillis(); List<String> res = null; if (ConfigManager.isRunningLocally()) res = LocalShell.exec(command); else res = RemoteShell.exec(ip, user, password, key, command); long duration = System.currentTimeMillis() - init; journal.debug("Executed `{}` on {} in {}", command, ip, durationToString(duration)); return res; } public void receiveFile(String lfile, String rfile) throws Exception { long init = System.currentTimeMillis(); if (ConfigManager.isRunningLocally()) LocalShell.receiveFile(lfile, rfile); else RemoteShell.receiveFile(ip, user, password, key, lfile, rfile); long duration = System.currentTimeMillis() - init; journal.debug("File `{}` received from {} in {}", rfile, ip, durationToString(duration)); } public void sendFile(String lfile, String rfile) throws Exception { long init = System.currentTimeMillis(); if (ConfigManager.isRunningLocally()) LocalShell.sendFile(lfile, rfile); else RemoteShell.sendFile(ip, user, password, key, lfile, rfile); long duration = System.currentTimeMillis() - init; journal.debug("File `{}` sent to {} in {}", lfile, ip, durationToString(duration)); } public static String durationToString(long duration) { StringBuilder sb = new StringBuilder(); { int res = (int) TimeUnit.MILLISECONDS.toSeconds(duration); if (res > 60 * 60) { sb.append(res / (60 * 60)); sb.append(" h "); res = res % (60 * 60); } if (res > 60) { sb.append(res / 60); sb.append(" m "); res = res % 60; } sb.append(res); sb.append(" s"); } return sb.toString(); } }
# -*- coding: utf-8 -*- import os import sys import glob import re import nbconvert import pandas as pd sys.path.append('/home/rstudio/codes') from pyBatman.nbrun import run_notebook from pyBatman import sub_dir_path, mkdir_p from pyBatman.constants import WD, SPECTRA_DIR, BACKGROUND_DIR, OUTPUT_DIR def process_spectra(nb_name_input): if os.path.isdir(WD): # if wd exists (has been mapped) spectra_found = os.path.isdir(SPECTRA_DIR) background_found = os.path.isdir(BACKGROUND_DIR) if spectra_found and background_found: input_spectra = sub_dir_path(SPECTRA_DIR) input_spectra = natural_sort(input_spectra) mkdir_p(OUTPUT_DIR) for i in range(len(input_spectra)): sd = input_spectra[i] base_name = os.path.basename(os.path.normpath(sd)) print 'Now processing %d/%d: %s' % (i+1, len(input_spectra), base_name) nb_name_output = os.path.join(OUTPUT_DIR, '%s.html' % base_name) timeout = -1 # never times out nb_kwargs = {'spectra_dir': sd} try: run_notebook(nb_name_input, nb_name_output, timeout=timeout, nb_kwargs=nb_kwargs) except nbconvert.preprocessors.execute.CellExecutionError, e: print 'Failed to process this spectra: %s' % str(e) def get_file_id(csv_filename): basename = os.path.basename(os.path.normpath(csv_filename)) filename_no_extension = os.path.splitext(basename)[0] tokens = filename_no_extension.split('.') try: # Only for curve studies, extract e.g. 2001 from 'Curve_study.ID_2001.fP-EDTA.130510' file_id = tokens[1] file_id = file_id.replace('ID_', '') except IndexError: file_id = tokens[0] return file_id def get_df(csv_filename): df = pd.read_csv(csv_filename, header=0, index_col=0) file_id = get_file_id(csv_filename) df.rename(columns={'Concentration (mM)': file_id}, inplace=True) return df def natural_sort(l): convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] return sorted(l, key = alphanum_key) def process_output(csv_files): dfs = [] csv_files = natural_sort(csv_files) for csv_filename in csv_files: df = get_df(csv_filename) dfs.append(df) combined_df = pd.concat(dfs, axis=1) combined_df = combined_df.transpose() combined_df = combined_df.sort_index() combined_df.to_csv(os.path.join(OUTPUT_DIR, 'results.csv')) def main(): # process all the spectra nb_name_input = '/home/rstudio/codes/notebooks/predict_spectra_concentrations.ipynb' process_spectra(nb_name_input) # combined all the individual results into a single csv file csv_dir = os.path.join(OUTPUT_DIR, 'csv') csv_files = glob.glob(os.path.join(csv_dir, '*.csv')) process_output(csv_files) if __name__ == "__main__": main()
module("core", { teardown: moduleTeardown }); test("Unit Testing Environment", function () { expect(2); ok( hasPHP, "Running in an environment with PHP support. The AJAX tests only run if the environment supports PHP!" ); ok( !isLocal, "Unit tests are not ran from file:// (especially in Chrome. If you must test from file:// with Chrome, run it with the --allow-file-access-from-files flag!)" ); }); test("Basic requirements", function() { expect(7); ok( Array.prototype.push, "Array.push()" ); ok( Function.prototype.apply, "Function.apply()" ); ok( document.getElementById, "getElementById" ); ok( document.getElementsByTagName, "getElementsByTagName" ); ok( RegExp, "RegExp" ); ok( jQuery, "jQuery" ); ok( $, "$" ); }); test("jQuery()", function() { var elem, i, obj = jQuery("div"), code = jQuery("<code/>"), img = jQuery("<img/>"), div = jQuery("<div/><hr/><code/><b/>"), exec = false, lng = "", expected = 22, attrObj = { "text": "test", "class": "test2", "id": "test3" }; // The $(html, props) signature can stealth-call any $.fn method, check for a // few here but beware of modular builds where these methods may be excluded. if ( jQuery.fn.click ) { expected++; attrObj["click"] = function() { ok( exec, "Click executed." ); }; } if ( jQuery.fn.width ) { expected++; attrObj["width"] = 10; } if ( jQuery.fn.offset ) { expected++; attrObj["offset"] = { "top": 1, "left": 1 }; } if ( jQuery.fn.css ) { expected += 2; attrObj["css"] = { "paddingLeft": 1, "paddingRight": 1 }; } if ( jQuery.fn.attr ) { expected++; attrObj.attr = { "desired": "very" }; } expect( expected ); // Basic constructor's behavior equal( jQuery().length, 0, "jQuery() === jQuery([])" ); equal( jQuery(undefined).length, 0, "jQuery(undefined) === jQuery([])" ); equal( jQuery(null).length, 0, "jQuery(null) === jQuery([])" ); equal( jQuery("").length, 0, "jQuery('') === jQuery([])" ); equal( jQuery("#").length, 0, "jQuery('#') === jQuery([])" ); equal( jQuery(obj).selector, "div", "jQuery(jQueryObj) == jQueryObj" ); // can actually yield more than one, when iframes are included, the window is an array as well equal( jQuery(window).length, 1, "Correct number of elements generated for jQuery(window)" ); /* // disabled since this test was doing nothing. i tried to fix it but i'm not sure // what the expected behavior should even be. FF returns "\n" for the text node // make sure this is handled var crlfContainer = jQuery('<p>\r\n</p>'); var x = crlfContainer.contents().get(0).nodeValue; equal( x, what???, "Check for \\r and \\n in jQuery()" ); */ /* // Disabled until we add this functionality in var pass = true; try { jQuery("<div>Testing</div>").appendTo(document.getElementById("iframe").contentDocument.body); } catch(e){ pass = false; } ok( pass, "jQuery('&lt;tag&gt;') needs optional document parameter to ease cross-frame DOM wrangling, see #968" );*/ equal( code.length, 1, "Correct number of elements generated for code" ); equal( code.parent().length, 0, "Make sure that the generated HTML has no parent." ); equal( img.length, 1, "Correct number of elements generated for img" ); equal( img.parent().length, 0, "Make sure that the generated HTML has no parent." ); equal( div.length, 4, "Correct number of elements generated for div hr code b" ); equal( div.parent().length, 0, "Make sure that the generated HTML has no parent." ); equal( jQuery([1,2,3]).get(1), 2, "Test passing an array to the factory" ); equal( jQuery(document.body).get(0), jQuery("body").get(0), "Test passing an html node to the factory" ); elem = jQuery(" <em>hello</em>")[0]; equal( elem.nodeName.toLowerCase(), "em", "leading space" ); elem = jQuery("\n\n<em>world</em>")[0]; equal( elem.nodeName.toLowerCase(), "em", "leading newlines" ); elem = jQuery("<div/>", attrObj ); if ( jQuery.fn.width ) { equal( elem[0].style.width, "10px", "jQuery() quick setter width"); } if ( jQuery.fn.offset ) { equal( elem[0].style.top, "1px", "jQuery() quick setter offset"); } if ( jQuery.fn.css ) { equal( elem[0].style.paddingLeft, "1px", "jQuery quick setter css"); equal( elem[0].style.paddingRight, "1px", "jQuery quick setter css"); } if ( jQuery.fn.attr ) { equal( elem[0].getAttribute("desired"), "very", "jQuery quick setter attr"); } equal( elem[0].childNodes.length, 1, "jQuery quick setter text"); equal( elem[0].firstChild.nodeValue, "test", "jQuery quick setter text"); equal( elem[0].className, "test2", "jQuery() quick setter class"); equal( elem[0].id, "test3", "jQuery() quick setter id"); exec = true; elem.trigger("click"); // manually clean up detached elements elem.remove(); for ( i = 0; i < 3; ++i ) { elem = jQuery("<input type='text' value='TEST' />"); } equal( elem[0].defaultValue, "TEST", "Ensure cached nodes are cloned properly (Bug #6655)" ); // manually clean up detached elements elem.remove(); for ( i = 0; i < 128; i++ ) { lng += "12345678"; } }); test("jQuery(selector, context)", function() { expect(3); deepEqual( jQuery("div p", "#qunit-fixture").get(), q("sndp", "en", "sap"), "Basic selector with string as context" ); deepEqual( jQuery("div p", q("qunit-fixture")[0]).get(), q("sndp", "en", "sap"), "Basic selector with element as context" ); deepEqual( jQuery("div p", jQuery("#qunit-fixture")).get(), q("sndp", "en", "sap"), "Basic selector with jQuery object as context" ); }); test( "selector state", function() { expect( 18 ); var test; test = jQuery( undefined ); equal( test.selector, "", "Empty jQuery Selector" ); equal( test.context, undefined, "Empty jQuery Context" ); test = jQuery( document ); equal( test.selector, "", "Document Selector" ); equal( test.context, document, "Document Context" ); test = jQuery( document.body ); equal( test.selector, "", "Body Selector" ); equal( test.context, document.body, "Body Context" ); test = jQuery("#qunit-fixture"); equal( test.selector, "#qunit-fixture", "#qunit-fixture Selector" ); equal( test.context, document, "#qunit-fixture Context" ); test = jQuery("#notfoundnono"); equal( test.selector, "#notfoundnono", "#notfoundnono Selector" ); equal( test.context, document, "#notfoundnono Context" ); test = jQuery( "#qunit-fixture", document ); equal( test.selector, "#qunit-fixture", "#qunit-fixture Selector" ); equal( test.context, document, "#qunit-fixture Context" ); test = jQuery( "#qunit-fixture", document.body ); equal( test.selector, "#qunit-fixture", "#qunit-fixture Selector" ); equal( test.context, document.body, "#qunit-fixture Context" ); // Test cloning test = jQuery( test ); equal( test.selector, "#qunit-fixture", "#qunit-fixture Selector" ); equal( test.context, document.body, "#qunit-fixture Context" ); test = jQuery( document.body ).find("#qunit-fixture"); equal( test.selector, "#qunit-fixture", "#qunit-fixture find Selector" ); equal( test.context, document.body, "#qunit-fixture find Context" ); }); test( "globalEval", function() { expect( 3 ); Globals.register("globalEvalTest"); jQuery.globalEval("globalEvalTest = 1;"); equal( window.globalEvalTest, 1, "Test variable assignments are global" ); jQuery.globalEval("var globalEvalTest = 2;"); equal( window.globalEvalTest, 2, "Test variable declarations are global" ); jQuery.globalEval("this.globalEvalTest = 3;"); equal( window.globalEvalTest, 3, "Test context (this) is the window object" ); }); test( "globalEval with 'use strict'", function() { expect( 1 ); Globals.register("strictEvalTest"); jQuery.globalEval("'use strict'; var strictEvalTest = 1;"); equal( window.strictEvalTest, 1, "Test variable declarations are global (strict mode)" ); }); test("noConflict", function() { expect(7); var $$ = jQuery; strictEqual( jQuery, jQuery.noConflict(), "noConflict returned the jQuery object" ); strictEqual( window["jQuery"], $$, "Make sure jQuery wasn't touched." ); strictEqual( window["$"], original$, "Make sure $ was reverted." ); jQuery = $ = $$; strictEqual( jQuery.noConflict(true), $$, "noConflict returned the jQuery object" ); strictEqual( window["jQuery"], originaljQuery, "Make sure jQuery was reverted." ); strictEqual( window["$"], original$, "Make sure $ was reverted." ); ok( $$().pushStack([]), "Make sure that jQuery still works." ); window["jQuery"] = jQuery = $$; }); test("trim", function() { expect(13); var nbsp = String.fromCharCode(160); equal( jQuery.trim("hello "), "hello", "trailing space" ); equal( jQuery.trim(" hello"), "hello", "leading space" ); equal( jQuery.trim(" hello "), "hello", "space on both sides" ); equal( jQuery.trim(" " + nbsp + "hello " + nbsp + " "), "hello", "&nbsp;" ); equal( jQuery.trim(), "", "Nothing in." ); equal( jQuery.trim( undefined ), "", "Undefined" ); equal( jQuery.trim( null ), "", "Null" ); equal( jQuery.trim( 5 ), "5", "Number" ); equal( jQuery.trim( false ), "false", "Boolean" ); equal( jQuery.trim(" "), "", "space should be trimmed" ); equal( jQuery.trim("ipad\xA0"), "ipad", "nbsp should be trimmed" ); equal( jQuery.trim("\uFEFF"), "", "zwsp should be trimmed" ); equal( jQuery.trim("\uFEFF \xA0! | \uFEFF"), "! |", "leading/trailing should be trimmed" ); }); test("type", function() { expect( 28 ); equal( jQuery.type(null), "null", "null" ); equal( jQuery.type(undefined), "undefined", "undefined" ); equal( jQuery.type(true), "boolean", "Boolean" ); equal( jQuery.type(false), "boolean", "Boolean" ); equal( jQuery.type(Boolean(true)), "boolean", "Boolean" ); equal( jQuery.type(0), "number", "Number" ); equal( jQuery.type(1), "number", "Number" ); equal( jQuery.type(Number(1)), "number", "Number" ); equal( jQuery.type(""), "string", "String" ); equal( jQuery.type("a"), "string", "String" ); equal( jQuery.type(String("a")), "string", "String" ); equal( jQuery.type({}), "object", "Object" ); equal( jQuery.type(/foo/), "regexp", "RegExp" ); equal( jQuery.type(new RegExp("asdf")), "regexp", "RegExp" ); equal( jQuery.type([1]), "array", "Array" ); equal( jQuery.type(new Date()), "date", "Date" ); equal( jQuery.type(new Function("return;")), "function", "Function" ); equal( jQuery.type(function(){}), "function", "Function" ); equal( jQuery.type(new Error()), "error", "Error" ); equal( jQuery.type(window), "object", "Window" ); equal( jQuery.type(document), "object", "Document" ); equal( jQuery.type(document.body), "object", "Element" ); equal( jQuery.type(document.createTextNode("foo")), "object", "TextNode" ); equal( jQuery.type(document.getElementsByTagName("*")), "object", "NodeList" ); // Avoid Lint complaints var MyString = String, MyNumber = Number, MyBoolean = Boolean, MyObject = Object; equal( jQuery.type(new MyBoolean(true)), "boolean", "Boolean" ); equal( jQuery.type(new MyNumber(1)), "number", "Number" ); equal( jQuery.type(new MyString("a")), "string", "String" ); equal( jQuery.type(new MyObject()), "object", "Object" ); }); asyncTest("isPlainObject", function() { expect(15); var pass, iframe, doc, fn = function() {}; // The use case that we want to match ok( jQuery.isPlainObject({}), "{}" ); // Not objects shouldn't be matched ok( !jQuery.isPlainObject(""), "string" ); ok( !jQuery.isPlainObject(0) && !jQuery.isPlainObject(1), "number" ); ok( !jQuery.isPlainObject(true) && !jQuery.isPlainObject(false), "boolean" ); ok( !jQuery.isPlainObject(null), "null" ); ok( !jQuery.isPlainObject(undefined), "undefined" ); // Arrays shouldn't be matched ok( !jQuery.isPlainObject([]), "array" ); // Instantiated objects shouldn't be matched ok( !jQuery.isPlainObject(new Date()), "new Date" ); // Functions shouldn't be matched ok( !jQuery.isPlainObject(fn), "fn" ); // Again, instantiated objects shouldn't be matched ok( !jQuery.isPlainObject(new fn()), "new fn (no methods)" ); // Makes the function a little more realistic // (and harder to detect, incidentally) fn.prototype["someMethod"] = function(){}; // Again, instantiated objects shouldn't be matched ok( !jQuery.isPlainObject(new fn()), "new fn" ); // DOM Element ok( !jQuery.isPlainObject( document.createElement("div") ), "DOM Element" ); // Window ok( !jQuery.isPlainObject( window ), "window" ); pass = false; try { jQuery.isPlainObject( window.location ); pass = true; } catch ( e ) {} ok( pass, "Does not throw exceptions on host objects" ); // Objects from other windows should be matched Globals.register("iframeDone"); window.iframeDone = function( otherObject, detail ) { window.iframeDone = undefined; iframe.parentNode.removeChild( iframe ); ok( jQuery.isPlainObject(new otherObject()), "new otherObject" + ( detail ? " - " + detail : "" ) ); start(); }; try { iframe = jQuery("#qunit-fixture")[0].appendChild( document.createElement("iframe") ); doc = iframe.contentDocument || iframe.contentWindow.document; doc.open(); doc.write("<body onload='window.parent.iframeDone(Object);'>"); doc.close(); } catch(e) { window.iframeDone( Object, "iframes not supported" ); } }); test("isFunction", function() { expect(19); var mystr, myarr, myfunction, fn, obj, nodes, first, input, a; // Make sure that false values return false ok( !jQuery.isFunction(), "No Value" ); ok( !jQuery.isFunction( null ), "null Value" ); ok( !jQuery.isFunction( undefined ), "undefined Value" ); ok( !jQuery.isFunction( "" ), "Empty String Value" ); ok( !jQuery.isFunction( 0 ), "0 Value" ); // Check built-ins ok( jQuery.isFunction(String), "String Function("+String+")" ); ok( jQuery.isFunction(Array), "Array Function("+Array+")" ); ok( jQuery.isFunction(Object), "Object Function("+Object+")" ); ok( jQuery.isFunction(Function), "Function Function("+Function+")" ); // When stringified, this could be misinterpreted mystr = "function"; ok( !jQuery.isFunction(mystr), "Function String" ); // When stringified, this could be misinterpreted myarr = [ "function" ]; ok( !jQuery.isFunction(myarr), "Function Array" ); // When stringified, this could be misinterpreted myfunction = { "function": "test" }; ok( !jQuery.isFunction(myfunction), "Function Object" ); // Make sure normal functions still work fn = function(){}; ok( jQuery.isFunction(fn), "Normal Function" ); obj = document.createElement("object"); // Firefox says this is a function ok( !jQuery.isFunction(obj), "Object Element" ); // Since 1.3, this isn't supported (#2968) //ok( jQuery.isFunction(obj.getAttribute), "getAttribute Function" ); nodes = document.body.childNodes; // Safari says this is a function ok( !jQuery.isFunction(nodes), "childNodes Property" ); first = document.body.firstChild; // Normal elements are reported ok everywhere ok( !jQuery.isFunction(first), "A normal DOM Element" ); input = document.createElement("input"); input.type = "text"; document.body.appendChild( input ); // Since 1.3, this isn't supported (#2968) //ok( jQuery.isFunction(input.focus), "A default function property" ); document.body.removeChild( input ); a = document.createElement("a"); a.href = "some-function"; document.body.appendChild( a ); // This serializes with the word 'function' in it ok( !jQuery.isFunction(a), "Anchor Element" ); document.body.removeChild( a ); // Recursive function calls have lengths and array-like properties function callme(callback){ function fn(response){ callback(response); } ok( jQuery.isFunction(fn), "Recursive Function Call" ); fn({ some: "data" }); } callme(function(){ callme(function(){}); }); }); test( "isNumeric", function() { expect( 38 ); var t = jQuery.isNumeric, ToString = function( value ) { this.toString = function() { return String( value ); }; }; ok( t( "-10" ), "Negative integer string" ); ok( t( "0" ), "Zero string" ); ok( t( "5" ), "Positive integer string" ); ok( t( -16 ), "Negative integer number" ); ok( t( 0 ), "Zero integer number" ); ok( t( 32 ), "Positive integer number" ); ok( t( "040" ), "Octal integer literal string" ); ok( t( "0xFF" ), "Hexadecimal integer literal string" ); ok( t( 0xFFF ), "Hexadecimal integer literal" ); ok( t( "-1.6" ), "Negative floating point string" ); ok( t( "4.536" ), "Positive floating point string" ); ok( t( -2.6 ), "Negative floating point number" ); ok( t( 3.1415 ), "Positive floating point number" ); ok( t( 1.5999999999999999 ), "Very precise floating point number" ); ok( t( 8e5 ), "Exponential notation" ); ok( t( "123e-2" ), "Exponential notation string" ); ok( t( new ToString( "42" ) ), "Custom .toString returning number" ); equal( t( "" ), false, "Empty string" ); equal( t( " " ), false, "Whitespace characters string" ); equal( t( "\t\t" ), false, "Tab characters string" ); equal( t( "abcdefghijklm1234567890" ), false, "Alphanumeric character string" ); equal( t( "xabcdefx" ), false, "Non-numeric character string" ); equal( t( true ), false, "Boolean true literal" ); equal( t( false ), false, "Boolean false literal" ); equal( t( "bcfed5.2" ), false, "Number with preceding non-numeric characters" ); equal( t( "7.2acdgs" ), false, "Number with trailling non-numeric characters" ); equal( t( undefined ), false, "Undefined value" ); equal( t( null ), false, "Null value" ); equal( t( NaN ), false, "NaN value" ); equal( t( Infinity ), false, "Infinity primitive" ); equal( t( Number.POSITIVE_INFINITY ), false, "Positive Infinity" ); equal( t( Number.NEGATIVE_INFINITY ), false, "Negative Infinity" ); equal( t( new ToString( "Devo" ) ), false, "Custom .toString returning non-number" ); equal( t( {} ), false, "Empty object" ); equal( t( [] ), false, "Empty array" ); equal( t( [ 42 ] ), false, "Array with one number" ); equal( t( function(){} ), false, "Instance of a function" ); equal( t( new Date() ), false, "Instance of a Date" ); }); test("isXMLDoc - HTML", function() { expect(4); ok( !jQuery.isXMLDoc( document ), "HTML document" ); ok( !jQuery.isXMLDoc( document.documentElement ), "HTML documentElement" ); ok( !jQuery.isXMLDoc( document.body ), "HTML Body Element" ); var body, iframe = document.createElement("iframe"); document.body.appendChild( iframe ); try { body = jQuery(iframe).contents()[0]; try { ok( !jQuery.isXMLDoc( body ), "Iframe body element" ); } catch(e) { ok( false, "Iframe body element exception" ); } } catch(e) { ok( true, "Iframe body element - iframe not working correctly" ); } document.body.removeChild( iframe ); }); test("XSS via location.hash", function() { expect(1); stop(); jQuery["_check9521"] = function(x){ ok( x, "script called from #id-like selector with inline handler" ); jQuery("#check9521").remove(); delete jQuery["_check9521"]; start(); }; try { // This throws an error because it's processed like an id jQuery( "#<img id='check9521' src='no-such-.gif' onerror='jQuery._check9521(false)'>" ).appendTo("#qunit-fixture"); } catch (err) { jQuery["_check9521"](true); } }); test("isXMLDoc - XML", function() { expect(3); var xml = createDashboardXML(); ok( jQuery.isXMLDoc( xml ), "XML document" ); ok( jQuery.isXMLDoc( xml.documentElement ), "XML documentElement" ); ok( jQuery.isXMLDoc( jQuery("tab", xml)[0] ), "XML Tab Element" ); }); test("isWindow", function() { expect( 14 ); ok( jQuery.isWindow(window), "window" ); ok( jQuery.isWindow(document.getElementsByTagName("iframe")[0].contentWindow), "iframe.contentWindow" ); ok( !jQuery.isWindow(), "empty" ); ok( !jQuery.isWindow(null), "null" ); ok( !jQuery.isWindow(undefined), "undefined" ); ok( !jQuery.isWindow(document), "document" ); ok( !jQuery.isWindow(document.documentElement), "documentElement" ); ok( !jQuery.isWindow(""), "string" ); ok( !jQuery.isWindow(1), "number" ); ok( !jQuery.isWindow(true), "boolean" ); ok( !jQuery.isWindow({}), "object" ); ok( !jQuery.isWindow({ setInterval: function(){} }), "fake window" ); ok( !jQuery.isWindow(/window/), "regexp" ); ok( !jQuery.isWindow(function(){}), "function" ); }); test("jQuery('html')", function() { expect( 18 ); var s, div, j; jQuery["foo"] = false; s = jQuery("<script>jQuery.foo='test';</script>")[0]; ok( s, "Creating a script" ); ok( !jQuery["foo"], "Make sure the script wasn't executed prematurely" ); jQuery("body").append("<script>jQuery.foo='test';</script>"); ok( jQuery["foo"], "Executing a scripts contents in the right context" ); // Test multi-line HTML div = jQuery("<div>\r\nsome text\n<p>some p</p>\nmore text\r\n</div>")[0]; equal( div.nodeName.toUpperCase(), "DIV", "Make sure we're getting a div." ); equal( div.firstChild.nodeType, 3, "Text node." ); equal( div.lastChild.nodeType, 3, "Text node." ); equal( div.childNodes[1].nodeType, 1, "Paragraph." ); equal( div.childNodes[1].firstChild.nodeType, 3, "Paragraph text." ); ok( jQuery("<link rel='stylesheet'/>")[0], "Creating a link" ); ok( !jQuery("<script/>")[0].parentNode, "Create a script" ); ok( jQuery("<input/>").attr("type", "hidden"), "Create an input and set the type." ); j = jQuery("<span>hi</span> there <!-- mon ami -->"); ok( j.length >= 2, "Check node,textnode,comment creation (some browsers delete comments)" ); ok( !jQuery("<option>test</option>")[0].selected, "Make sure that options are auto-selected #2050" ); ok( jQuery("<div></div>")[0], "Create a div with closing tag." ); ok( jQuery("<table></table>")[0], "Create a table with closing tag." ); equal( jQuery( "element[attribute='<div></div>']" ).length, 0, "When html is within brackets, do not recognize as html." ); //equal( jQuery( "element[attribute=<div></div>]" ).length, 0, // "When html is within brackets, do not recognize as html." ); equal( jQuery( "element:not(<div></div>)" ).length, 0, "When html is within parens, do not recognize as html." ); equal( jQuery( "\\<div\\>" ).length, 0, "Ignore escaped html characters" ); }); test("jQuery('massive html #7990')", function() { expect( 3 ); var i, li = "<li>very very very very large html string</li>", html = ["<ul>"]; for ( i = 0; i < 30000; i += 1 ) { html[html.length] = li; } html[html.length] = "</ul>"; html = jQuery(html.join(""))[0]; equal( html.nodeName.toLowerCase(), "ul"); equal( html.firstChild.nodeName.toLowerCase(), "li"); equal( html.childNodes.length, 30000 ); }); test("jQuery('html', context)", function() { expect(1); var $div = jQuery("<div/>")[0], $span = jQuery("<span/>", $div); equal($span.length, 1, "verify a span created with a div context works, #1763"); }); test("jQuery(selector, xml).text(str) - loaded via xml document", function() { expect(2); var xml = createDashboardXML(), // tests for #1419 where ie was a problem tab = jQuery("tab", xml).eq(0); equal( tab.text(), "blabla", "verify initial text correct" ); tab.text("newtext"); equal( tab.text(), "newtext", "verify new text correct" ); }); test("end()", function() { expect(3); equal( "Yahoo", jQuery("#yahoo").parent().end().text(), "check for end" ); ok( jQuery("#yahoo").end(), "check for end with nothing to end" ); var x = jQuery("#yahoo"); x.parent(); equal( "Yahoo", jQuery("#yahoo").text(), "check for non-destructive behaviour" ); }); test("length", function() { expect(1); equal( jQuery("#qunit-fixture p").length, 6, "Get Number of Elements Found" ); }); test("get()", function() { expect(1); deepEqual( jQuery("#qunit-fixture p").get(), q("firstp","ap","sndp","en","sap","first"), "Get All Elements" ); }); test("toArray()", function() { expect(1); deepEqual( jQuery("#qunit-fixture p").toArray(), q("firstp","ap","sndp","en","sap","first"), "Convert jQuery object to an Array" ); }); test("inArray()", function() { expect(19); var selections = { p: q("firstp", "sap", "ap", "first"), em: q("siblingnext", "siblingfirst"), div: q("qunit-testrunner-toolbar", "nothiddendiv", "nothiddendivchild", "foo"), a: q("mark", "groups", "google", "simon1"), empty: [] }, tests = { p: { elem: jQuery("#ap")[0], index: 2 }, em: { elem: jQuery("#siblingfirst")[0], index: 1 }, div: { elem: jQuery("#nothiddendiv")[0], index: 1 }, a: { elem: jQuery("#simon1")[0], index: 3 } }, falseTests = { p: jQuery("#liveSpan1")[0], em: jQuery("#nothiddendiv")[0], empty: "" }; jQuery.each( tests, function( key, obj ) { equal( jQuery.inArray( obj.elem, selections[ key ] ), obj.index, "elem is in the array of selections of its tag" ); // Third argument (fromIndex) equal( !!~jQuery.inArray( obj.elem, selections[ key ], 5 ), false, "elem is NOT in the array of selections given a starting index greater than its position" ); equal( !!~jQuery.inArray( obj.elem, selections[ key ], 1 ), true, "elem is in the array of selections given a starting index less than or equal to its position" ); equal( !!~jQuery.inArray( obj.elem, selections[ key ], -3 ), true, "elem is in the array of selections given a negative index" ); }); jQuery.each( falseTests, function( key, elem ) { equal( !!~jQuery.inArray( elem, selections[ key ] ), false, "elem is NOT in the array of selections" ); }); }); test("get(Number)", function() { expect(2); equal( jQuery("#qunit-fixture p").get(0), document.getElementById("firstp"), "Get A Single Element" ); strictEqual( jQuery("#firstp").get(1), undefined, "Try get with index larger elements count" ); }); test("get(-Number)",function() { expect(2); equal( jQuery("p").get(-1), document.getElementById("first"), "Get a single element with negative index" ); strictEqual( jQuery("#firstp").get(-2), undefined, "Try get with index negative index larger then elements count" ); }); test("each(Function)", function() { expect(1); var div, pass, i; div = jQuery("div"); div.each(function(){this.foo = "zoo";}); pass = true; for ( i = 0; i < div.length; i++ ) { if ( div.get(i).foo !== "zoo" ) { pass = false; } } ok( pass, "Execute a function, Relative" ); }); test("slice()", function() { expect(7); var $links = jQuery("#ap a"); deepEqual( $links.slice(1,2).get(), q("groups"), "slice(1,2)" ); deepEqual( $links.slice(1).get(), q("groups", "anchor1", "mark"), "slice(1)" ); deepEqual( $links.slice(0,3).get(), q("google", "groups", "anchor1"), "slice(0,3)" ); deepEqual( $links.slice(-1).get(), q("mark"), "slice(-1)" ); deepEqual( $links.eq(1).get(), q("groups"), "eq(1)" ); deepEqual( $links.eq("2").get(), q("anchor1"), "eq('2')" ); deepEqual( $links.eq(-1).get(), q("mark"), "eq(-1)" ); }); test("first()/last()", function() { expect(4); var $links = jQuery("#ap a"), $none = jQuery("asdf"); deepEqual( $links.first().get(), q("google"), "first()" ); deepEqual( $links.last().get(), q("mark"), "last()" ); deepEqual( $none.first().get(), [], "first() none" ); deepEqual( $none.last().get(), [], "last() none" ); }); test("map()", function() { expect( 2 ); deepEqual( jQuery("#ap").map(function() { return jQuery( this ).find("a").get(); }).get(), q( "google", "groups", "anchor1", "mark" ), "Array Map" ); deepEqual( jQuery("#ap > a").map(function() { return this.parentNode; }).get(), q( "ap","ap","ap" ), "Single Map" ); }); test("jQuery.map", function() { expect( 25 ); var i, label, result, callback; result = jQuery.map( [ 3, 4, 5 ], function( v, k ) { return k; }); equal( result.join(""), "012", "Map the keys from an array" ); result = jQuery.map( [ 3, 4, 5 ], function( v ) { return v; }); equal( result.join(""), "345", "Map the values from an array" ); result = jQuery.map( { a: 1, b: 2 }, function( v, k ) { return k; }); equal( result.join(""), "ab", "Map the keys from an object" ); result = jQuery.map( { a: 1, b: 2 }, function( v ) { return v; }); equal( result.join(""), "12", "Map the values from an object" ); result = jQuery.map( [ "a", undefined, null, "b" ], function( v ) { return v; }); equal( result.join(""), "ab", "Array iteration does not include undefined/null results" ); result = jQuery.map( { a: "a", b: undefined, c: null, d: "b" }, function( v ) { return v; }); equal( result.join(""), "ab", "Object iteration does not include undefined/null results" ); result = { Zero: function() {}, One: function( a ) { a = a; }, Two: function( a, b ) { a = a; b = b; } }; callback = function( v, k ) { equal( k, "foo", label + "-argument function treated like object" ); }; for ( i in result ) { label = i; result[ i ].foo = "bar"; jQuery.map( result[ i ], callback ); } result = { "undefined": undefined, "null": null, "false": false, "true": true, "empty string": "", "nonempty string": "string", "string \"0\"": "0", "negative": -1, "excess": 1 }; callback = function( v, k ) { equal( k, "length", "Object with " + label + " length treated like object" ); }; for ( i in result ) { label = i; jQuery.map( { length: result[ i ] }, callback ); } result = { "sparse Array": Array( 4 ), "length: 1 plain object": { length: 1, "0": true }, "length: 2 plain object": { length: 2, "0": true, "1": true }, NodeList: document.getElementsByTagName("html") }; callback = function( v, k ) { if ( result[ label ] ) { delete result[ label ]; equal( k, "0", label + " treated like array" ); } }; for ( i in result ) { label = i; jQuery.map( result[ i ], callback ); } result = false; jQuery.map( { length: 0 }, function() { result = true; }); ok( !result, "length: 0 plain object treated like array" ); result = false; jQuery.map( document.getElementsByTagName("asdf"), function() { result = true; }); ok( !result, "empty NodeList treated like array" ); result = jQuery.map( Array(4), function( v, k ){ return k % 2 ? k : [k,k,k]; }); equal( result.join(""), "00012223", "Array results flattened (#2616)" ); }); test("jQuery.merge()", function() { expect( 10 ); deepEqual( jQuery.merge( [], [] ), [], "Empty arrays" ); deepEqual( jQuery.merge( [ 1 ], [ 2 ] ), [ 1, 2 ], "Basic (single-element)" ); deepEqual( jQuery.merge( [ 1, 2 ], [ 3, 4 ] ), [ 1, 2, 3, 4 ], "Basic (multiple-element)" ); deepEqual( jQuery.merge( [ 1, 2 ], [] ), [ 1, 2 ], "Second empty" ); deepEqual( jQuery.merge( [], [ 1, 2 ] ), [ 1, 2 ], "First empty" ); // Fixed at [5998], #3641 deepEqual( jQuery.merge( [ -2, -1 ], [ 0, 1, 2 ] ), [ -2, -1 , 0, 1, 2 ], "Second array including a zero (falsy)" ); // After fixing #5527 deepEqual( jQuery.merge( [], [ null, undefined ] ), [ null, undefined ], "Second array including null and undefined values" ); deepEqual( jQuery.merge( { length: 0 }, [ 1, 2 ] ), { length: 2, 0: 1, 1: 2 }, "First array like" ); deepEqual( jQuery.merge( [ 1, 2 ], { length: 1, 0: 3 } ), [ 1, 2, 3 ], "Second array like" ); deepEqual( jQuery.merge( [], document.getElementById("lengthtest").getElementsByTagName("input") ), [ document.getElementById("length"), document.getElementById("idTest") ], "Second NodeList" ); }); test("jQuery.grep()", function() { expect(8); var searchCriterion = function( value ) { return value % 2 === 0; }; deepEqual( jQuery.grep( [], searchCriterion ), [], "Empty array" ); deepEqual( jQuery.grep( new Array(4), searchCriterion ), [], "Sparse array" ); deepEqual( jQuery.grep( [ 1, 2, 3, 4, 5, 6 ], searchCriterion ), [ 2, 4, 6 ], "Satisfying elements present" ); deepEqual( jQuery.grep( [ 1, 3, 5, 7], searchCriterion ), [], "Satisfying elements absent" ); deepEqual( jQuery.grep( [ 1, 2, 3, 4, 5, 6 ], searchCriterion, true ), [ 1, 3, 5 ], "Satisfying elements present and grep inverted" ); deepEqual( jQuery.grep( [ 1, 3, 5, 7], searchCriterion, true ), [1, 3, 5, 7], "Satisfying elements absent and grep inverted" ); deepEqual( jQuery.grep( [ 1, 2, 3, 4, 5, 6 ], searchCriterion, false ), [ 2, 4, 6 ], "Satisfying elements present but grep explicitly uninverted" ); deepEqual( jQuery.grep( [ 1, 3, 5, 7 ], searchCriterion, false ), [], "Satisfying elements absent and grep explicitly uninverted" ); }); test("jQuery.extend(Object, Object)", function() { expect(28); var empty, optionsWithLength, optionsWithDate, myKlass, customObject, optionsWithCustomObject, MyNumber, ret, nullUndef, target, recursive, obj, defaults, defaultsCopy, options1, options1Copy, options2, options2Copy, merged2, settings = { "xnumber1": 5, "xnumber2": 7, "xstring1": "peter", "xstring2": "pan" }, options = { "xnumber2": 1, "xstring2": "x", "xxx": "newstring" }, optionsCopy = { "xnumber2": 1, "xstring2": "x", "xxx": "newstring" }, merged = { "xnumber1": 5, "xnumber2": 1, "xstring1": "peter", "xstring2": "x", "xxx": "newstring" }, deep1 = { "foo": { "bar": true } }, deep2 = { "foo": { "baz": true }, "foo2": document }, deep2copy = { "foo": { "baz": true }, "foo2": document }, deepmerged = { "foo": { "bar": true, "baz": true }, "foo2": document }, arr = [1, 2, 3], nestedarray = { "arr": arr }; jQuery.extend(settings, options); deepEqual( settings, merged, "Check if extended: settings must be extended" ); deepEqual( options, optionsCopy, "Check if not modified: options must not be modified" ); jQuery.extend(settings, null, options); deepEqual( settings, merged, "Check if extended: settings must be extended" ); deepEqual( options, optionsCopy, "Check if not modified: options must not be modified" ); jQuery.extend(true, deep1, deep2); deepEqual( deep1["foo"], deepmerged["foo"], "Check if foo: settings must be extended" ); deepEqual( deep2["foo"], deep2copy["foo"], "Check if not deep2: options must not be modified" ); equal( deep1["foo2"], document, "Make sure that a deep clone was not attempted on the document" ); ok( jQuery.extend(true, {}, nestedarray)["arr"] !== arr, "Deep extend of object must clone child array" ); // #5991 ok( jQuery.isArray( jQuery.extend(true, { "arr": {} }, nestedarray)["arr"] ), "Cloned array have to be an Array" ); ok( jQuery.isPlainObject( jQuery.extend(true, { "arr": arr }, { "arr": {} })["arr"] ), "Cloned object have to be an plain object" ); empty = {}; optionsWithLength = { "foo": { "length": -1 } }; jQuery.extend(true, empty, optionsWithLength); deepEqual( empty["foo"], optionsWithLength["foo"], "The length property must copy correctly" ); empty = {}; optionsWithDate = { "foo": { "date": new Date() } }; jQuery.extend(true, empty, optionsWithDate); deepEqual( empty["foo"], optionsWithDate["foo"], "Dates copy correctly" ); /** @constructor */ myKlass = function() {}; customObject = new myKlass(); optionsWithCustomObject = { "foo": { "date": customObject } }; empty = {}; jQuery.extend(true, empty, optionsWithCustomObject); ok( empty["foo"] && empty["foo"]["date"] === customObject, "Custom objects copy correctly (no methods)" ); // Makes the class a little more realistic myKlass.prototype = { "someMethod": function(){} }; empty = {}; jQuery.extend(true, empty, optionsWithCustomObject); ok( empty["foo"] && empty["foo"]["date"] === customObject, "Custom objects copy correctly" ); MyNumber = Number; ret = jQuery.extend(true, { "foo": 4 }, { "foo": new MyNumber(5) } ); ok( parseInt(ret.foo, 10) === 5, "Wrapped numbers copy correctly" ); nullUndef; nullUndef = jQuery.extend({}, options, { "xnumber2": null }); ok( nullUndef["xnumber2"] === null, "Check to make sure null values are copied"); nullUndef = jQuery.extend({}, options, { "xnumber2": undefined }); ok( nullUndef["xnumber2"] === options["xnumber2"], "Check to make sure undefined values are not copied"); nullUndef = jQuery.extend({}, options, { "xnumber0": null }); ok( nullUndef["xnumber0"] === null, "Check to make sure null values are inserted"); target = {}; recursive = { foo:target, bar:5 }; jQuery.extend(true, target, recursive); deepEqual( target, { bar:5 }, "Check to make sure a recursive obj doesn't go never-ending loop by not copying it over" ); ret = jQuery.extend(true, { foo: [] }, { foo: [0] } ); // 1907 equal( ret.foo.length, 1, "Check to make sure a value with coercion 'false' copies over when necessary to fix #1907" ); ret = jQuery.extend(true, { foo: "1,2,3" }, { foo: [1, 2, 3] } ); ok( typeof ret.foo !== "string", "Check to make sure values equal with coercion (but not actually equal) overwrite correctly" ); ret = jQuery.extend(true, { foo:"bar" }, { foo:null } ); ok( typeof ret.foo !== "undefined", "Make sure a null value doesn't crash with deep extend, for #1908" ); obj = { foo:null }; jQuery.extend(true, obj, { foo:"notnull" } ); equal( obj.foo, "notnull", "Make sure a null value can be overwritten" ); function func() {} jQuery.extend(func, { key: "value" } ); equal( func.key, "value", "Verify a function can be extended" ); defaults = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" }; defaultsCopy = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" }; options1 = { xnumber2: 1, xstring2: "x" }; options1Copy = { xnumber2: 1, xstring2: "x" }; options2 = { xstring2: "xx", xxx: "newstringx" }; options2Copy = { xstring2: "xx", xxx: "newstringx" }; merged2 = { xnumber1: 5, xnumber2: 1, xstring1: "peter", xstring2: "xx", xxx: "newstringx" }; settings = jQuery.extend({}, defaults, options1, options2); deepEqual( settings, merged2, "Check if extended: settings must be extended" ); deepEqual( defaults, defaultsCopy, "Check if not modified: options1 must not be modified" ); deepEqual( options1, options1Copy, "Check if not modified: options1 must not be modified" ); deepEqual( options2, options2Copy, "Check if not modified: options2 must not be modified" ); }); test("jQuery.extend(true,{},{a:[], o:{}}); deep copy with array, followed by object", function() { expect(2); var result, initial = { // This will make "copyIsArray" true array: [ 1, 2, 3, 4 ], // If "copyIsArray" doesn't get reset to false, the check // will evaluate true and enter the array copy block // instead of the object copy block. Since the ternary in the // "copyIsArray" block will will evaluate to false // (check if operating on an array with ), this will be // replaced by an empty array. object: {} }; result = jQuery.extend( true, {}, initial ); deepEqual( result, initial, "The [result] and [initial] have equal shape and values" ); ok( !jQuery.isArray( result.object ), "result.object wasn't paved with an empty array" ); }); test("jQuery.each(Object,Function)", function() { expect( 23 ); var i, label, seen, callback; seen = {}; jQuery.each( [ 3, 4, 5 ], function( k, v ) { seen[ k ] = v; }); deepEqual( seen, { "0": 3, "1": 4, "2": 5 }, "Array iteration" ); seen = {}; jQuery.each( { name: "name", lang: "lang" }, function( k, v ) { seen[ k ] = v; }); deepEqual( seen, { name: "name", lang: "lang" }, "Object iteration" ); seen = []; jQuery.each( [ 1, 2, 3 ], function( k, v ) { seen.push( v ); if ( k === 1 ) { return false; } }); deepEqual( seen, [ 1, 2 ] , "Broken array iteration" ); seen = []; jQuery.each( {"a": 1, "b": 2,"c": 3 }, function( k, v ) { seen.push( v ); return false; }); deepEqual( seen, [ 1 ], "Broken object iteration" ); seen = { Zero: function() {}, One: function( a ) { a = a; }, Two: function( a, b ) { a = a; b = b; } }; callback = function( k ) { equal( k, "foo", label + "-argument function treated like object" ); }; for ( i in seen ) { label = i; seen[ i ].foo = "bar"; jQuery.each( seen[ i ], callback ); } seen = { "undefined": undefined, "null": null, "false": false, "true": true, "empty string": "", "nonempty string": "string", "string \"0\"": "0", "negative": -1, "excess": 1 }; callback = function( k ) { equal( k, "length", "Object with " + label + " length treated like object" ); }; for ( i in seen ) { label = i; jQuery.each( { length: seen[ i ] }, callback ); } seen = { "sparse Array": Array( 4 ), "length: 1 plain object": { length: 1, "0": true }, "length: 2 plain object": { length: 2, "0": true, "1": true }, NodeList: document.getElementsByTagName("html") }; callback = function( k ) { if ( seen[ label ] ) { delete seen[ label ]; equal( k, "0", label + " treated like array" ); return false; } }; for ( i in seen ) { label = i; jQuery.each( seen[ i ], callback ); } seen = false; jQuery.each( { length: 0 }, function() { seen = true; }); ok( !seen, "length: 0 plain object treated like array" ); seen = false; jQuery.each( document.getElementsByTagName("asdf"), function() { seen = true; }); ok( !seen, "empty NodeList treated like array" ); i = 0; jQuery.each( document.styleSheets, function() { i++; }); equal( i, 2, "Iteration over document.styleSheets" ); }); test( "JIT compilation does not interfere with length retrieval (gh-2145)", function() { expect( 4 ); var i; // Trigger JIT compilation of jQuery.each – and therefore isArraylike – in iOS. // Convince JSC to use one of its optimizing compilers // by providing code which can be LICM'd into nothing. for ( i = 0; i < 1000; i++ ) { jQuery.each( [] ); } i = 0; jQuery.each( { 1: "1", 2: "2", 3: "3" }, function( index ) { equal( ++i, index, "Iteration over object with solely " + "numeric indices (gh-2145 JIT iOS 8 bug)" ); }); equal( i, 3, "Iteration over object with solely " + "numeric indices (gh-2145 JIT iOS 8 bug)" ); }); test("jQuery.makeArray", function(){ expect(15); equal( jQuery.makeArray(jQuery("html>*"))[0].nodeName.toUpperCase(), "HEAD", "Pass makeArray a jQuery object" ); equal( jQuery.makeArray(document.getElementsByName("PWD")).slice(0,1)[0].name, "PWD", "Pass makeArray a nodelist" ); equal( (function() { return jQuery.makeArray(arguments); })(1,2).join(""), "12", "Pass makeArray an arguments array" ); equal( jQuery.makeArray([1,2,3]).join(""), "123", "Pass makeArray a real array" ); equal( jQuery.makeArray().length, 0, "Pass nothing to makeArray and expect an empty array" ); equal( jQuery.makeArray( 0 )[0], 0 , "Pass makeArray a number" ); equal( jQuery.makeArray( "foo" )[0], "foo", "Pass makeArray a string" ); equal( jQuery.makeArray( true )[0].constructor, Boolean, "Pass makeArray a boolean" ); equal( jQuery.makeArray( document.createElement("div") )[0].nodeName.toUpperCase(), "DIV", "Pass makeArray a single node" ); equal( jQuery.makeArray( {length:2, 0:"a", 1:"b"} ).join(""), "ab", "Pass makeArray an array like map (with length)" ); ok( !!jQuery.makeArray( document.documentElement.childNodes ).slice(0,1)[0].nodeName, "Pass makeArray a childNodes array" ); // function, is tricky as it has length equal( jQuery.makeArray( function(){ return 1;} )[0](), 1, "Pass makeArray a function" ); //window, also has length equal( jQuery.makeArray(window)[0], window, "Pass makeArray the window" ); equal( jQuery.makeArray(/a/)[0].constructor, RegExp, "Pass makeArray a regex" ); // Some nodes inherit traits of nodelists ok( jQuery.makeArray(document.getElementById("form")).length >= 13, "Pass makeArray a form (treat as elements)" ); }); test("jQuery.inArray", function(){ expect(3); equal( jQuery.inArray( 0, false ), -1 , "Search in 'false' as array returns -1 and doesn't throw exception" ); equal( jQuery.inArray( 0, null ), -1 , "Search in 'null' as array returns -1 and doesn't throw exception" ); equal( jQuery.inArray( 0, undefined ), -1 , "Search in 'undefined' as array returns -1 and doesn't throw exception" ); }); test("jQuery.isEmptyObject", function(){ expect(2); equal(true, jQuery.isEmptyObject({}), "isEmptyObject on empty object literal" ); equal(false, jQuery.isEmptyObject({a:1}), "isEmptyObject on non-empty object literal" ); // What about this ? // equal(true, jQuery.isEmptyObject(null), "isEmptyObject on null" ); }); test("jQuery.proxy", function(){ expect( 9 ); var test2, test3, test4, fn, cb, test = function(){ equal( this, thisObject, "Make sure that scope is set properly." ); }, thisObject = { foo: "bar", method: test }; // Make sure normal works test.call( thisObject ); // Basic scoping jQuery.proxy( test, thisObject )(); // Another take on it jQuery.proxy( thisObject, "method" )(); // Make sure it doesn't freak out equal( jQuery.proxy( null, thisObject ), undefined, "Make sure no function was returned." ); // Partial application test2 = function( a ){ equal( a, "pre-applied", "Ensure arguments can be pre-applied." ); }; jQuery.proxy( test2, null, "pre-applied" )(); // Partial application w/ normal arguments test3 = function( a, b ){ equal( b, "normal", "Ensure arguments can be pre-applied and passed as usual." ); }; jQuery.proxy( test3, null, "pre-applied" )( "normal" ); // Test old syntax test4 = { "meth": function( a ){ equal( a, "boom", "Ensure old syntax works." ); } }; jQuery.proxy( test4, "meth" )( "boom" ); // jQuery 1.9 improved currying with `this` object fn = function() { equal( Array.prototype.join.call( arguments, "," ), "arg1,arg2,arg3", "args passed" ); equal( this.foo, "bar", "this-object passed" ); }; cb = jQuery.proxy( fn, null, "arg1", "arg2" ); cb.call( thisObject, "arg3" ); }); test("jQuery.parseHTML", function() { expect( 18 ); var html, nodes; equal( jQuery.parseHTML(), null, "Nothing in, null out." ); equal( jQuery.parseHTML( null ), null, "Null in, null out." ); equal( jQuery.parseHTML( "" ), null, "Empty string in, null out." ); throws(function() { jQuery.parseHTML( "<div></div>", document.getElementById("form") ); }, "Passing an element as the context raises an exception (context should be a document)"); nodes = jQuery.parseHTML( jQuery("body")[0].innerHTML ); ok( nodes.length > 4, "Parse a large html string" ); equal( jQuery.type( nodes ), "array", "parseHTML returns an array rather than a nodelist" ); html = "<script>undefined()</script>"; equal( jQuery.parseHTML( html ).length, 0, "Ignore scripts by default" ); equal( jQuery.parseHTML( html, true )[0].nodeName.toLowerCase(), "script", "Preserve scripts when requested" ); html += "<div></div>"; equal( jQuery.parseHTML( html )[0].nodeName.toLowerCase(), "div", "Preserve non-script nodes" ); equal( jQuery.parseHTML( html, true )[0].nodeName.toLowerCase(), "script", "Preserve script position"); equal( jQuery.parseHTML("text")[0].nodeType, 3, "Parsing text returns a text node" ); equal( jQuery.parseHTML( "\t<div></div>" )[0].nodeValue, "\t", "Preserve leading whitespace" ); equal( jQuery.parseHTML(" <div/> ")[0].nodeType, 3, "Leading spaces are treated as text nodes (#11290)" ); html = jQuery.parseHTML( "<div>test div</div>" ); equal( html[ 0 ].parentNode.nodeType, 11, "parentNode should be documentFragment" ); equal( html[ 0 ].innerHTML, "test div", "Content should be preserved" ); equal( jQuery.parseHTML("<span><span>").length, 1, "Incorrect html-strings should not break anything" ); equal( jQuery.parseHTML("<td><td>")[ 1 ].parentNode.nodeType, 11, "parentNode should be documentFragment for wrapMap (variable in manipulation module) elements too" ); ok( jQuery.parseHTML("<#if><tr><p>This is a test.</p></tr><#/if>") || true, "Garbage input should not cause error" ); }); test("jQuery.parseJSON", function() { expect( 20 ); strictEqual( jQuery.parseJSON( null ), null, "primitive null" ); strictEqual( jQuery.parseJSON("0.88"), 0.88, "Number" ); strictEqual( jQuery.parseJSON("\" \\\" \\\\ \\/ \\b \\f \\n \\r \\t \\u007E \\u263a \""), " \" \\ / \b \f \n \r \t ~ \u263A ", "String escapes" ); deepEqual( jQuery.parseJSON("{}"), {}, "Empty object" ); deepEqual( jQuery.parseJSON("{\"test\":1}"), { "test": 1 }, "Plain object" ); deepEqual( jQuery.parseJSON("[0]"), [ 0 ], "Simple array" ); deepEqual( jQuery.parseJSON("[ \"string\", -4.2, 2.7180e0, 3.14E-1, {}, [], true, false, null ]"), [ "string", -4.2, 2.718, 0.314, {}, [], true, false, null ], "Array of all data types" ); deepEqual( jQuery.parseJSON( "{ \"string\": \"\", \"number\": 4.2e+1, \"object\": {}," + "\"array\": [[]], \"boolean\": [ true, false ], \"null\": null }"), { string: "", number: 42, object: {}, array: [[]], boolean: [ true, false ], "null": null }, "Dictionary of all data types" ); deepEqual( jQuery.parseJSON("\n{\"test\":1}\t"), { "test": 1 }, "Leading and trailing whitespace are ignored" ); throws(function() { jQuery.parseJSON(); }, null, "Undefined raises an error" ); throws(function() { jQuery.parseJSON( "" ); }, null, "Empty string raises an error" ); throws(function() { jQuery.parseJSON("''"); }, null, "Single-quoted string raises an error" ); /* // Broken on IE8 throws(function() { jQuery.parseJSON("\" \\a \""); }, null, "Invalid string escape raises an error" ); // Broken on IE8, Safari 5.1 Windows throws(function() { jQuery.parseJSON("\"\t\""); }, null, "Unescaped control character raises an error" ); // Broken on IE8 throws(function() { jQuery.parseJSON(".123"); }, null, "Number with no integer component raises an error" ); */ throws(function() { var result = jQuery.parseJSON("0101"); // Support: IE9+ // Ensure base-10 interpretation on browsers that erroneously accept leading-zero numbers if ( result === 101 ) { throw new Error("close enough"); } }, null, "Leading-zero number raises an error or is parsed as decimal" ); throws(function() { jQuery.parseJSON("{a:1}"); }, null, "Unquoted property raises an error" ); throws(function() { jQuery.parseJSON("{'a':1}"); }, null, "Single-quoted property raises an error" ); throws(function() { jQuery.parseJSON("[,]"); }, null, "Array element elision raises an error" ); throws(function() { jQuery.parseJSON("{},[]"); }, null, "Comma expression raises an error" ); throws(function() { jQuery.parseJSON("[]\n,{}"); }, null, "Newline-containing comma expression raises an error" ); throws(function() { jQuery.parseJSON("\"\"\n\"\""); }, null, "Automatic semicolon insertion raises an error" ); strictEqual( jQuery.parseJSON([ 0 ]), 0, "Input cast to string" ); }); test("jQuery.parseXML", 8, function(){ var xml, tmp; try { xml = jQuery.parseXML( "<p>A <b>well-formed</b> xml string</p>" ); tmp = xml.getElementsByTagName( "p" )[ 0 ]; ok( !!tmp, "<p> present in document" ); tmp = tmp.getElementsByTagName( "b" )[ 0 ]; ok( !!tmp, "<b> present in document" ); strictEqual( tmp.childNodes[ 0 ].nodeValue, "well-formed", "<b> text is as expected" ); } catch (e) { strictEqual( e, undefined, "unexpected error" ); } try { xml = jQuery.parseXML( "<p>Not a <<b>well-formed</b> xml string</p>" ); ok( false, "invalid xml not detected" ); } catch( e ) { strictEqual( e.message, "Invalid XML: <p>Not a <<b>well-formed</b> xml string</p>", "invalid xml detected" ); } try { xml = jQuery.parseXML( "" ); strictEqual( xml, null, "empty string => null document" ); xml = jQuery.parseXML(); strictEqual( xml, null, "undefined string => null document" ); xml = jQuery.parseXML( null ); strictEqual( xml, null, "null string => null document" ); xml = jQuery.parseXML( true ); strictEqual( xml, null, "non-string => null document" ); } catch( e ) { ok( false, "empty input throws exception" ); } }); test("jQuery.camelCase()", function() { var tests = { "foo-bar": "fooBar", "foo-bar-baz": "fooBarBaz", "girl-u-want": "girlUWant", "the-4th-dimension": "the4thDimension", "-o-tannenbaum": "OTannenbaum", "-moz-illa": "MozIlla", "-ms-take": "msTake" }; expect(7); jQuery.each( tests, function( key, val ) { equal( jQuery.camelCase( key ), val, "Converts: " + key + " => " + val ); }); }); testIframeWithCallback( "Conditional compilation compatibility (#13274)", "core/cc_on.html", function( cc_on, errors, $ ) { expect( 3 ); ok( true, "JScript conditional compilation " + ( cc_on ? "supported" : "not supported" ) ); deepEqual( errors, [], "No errors" ); ok( $(), "jQuery executes" ); }); // iOS7 doesn't fire the load event if the long-loading iframe gets its source reset to about:blank. // This makes this test fail but it doesn't seem to cause any real-life problems so blacklisting // this test there is preferred to complicating the hard-to-test core/ready code further. if ( !/iphone os 7_/i.test( navigator.userAgent ) ) { testIframeWithCallback( "document ready when jQuery loaded asynchronously (#13655)", "core/dynamic_ready.html", function( ready ) { expect( 1 ); equal( true, ready, "document ready correctly fired when jQuery is loaded after DOMContentLoaded" ); }); } testIframeWithCallback( "Tolerating alias-masked DOM properties (#14074)", "core/aliased.html", function( errors ) { expect( 1 ); deepEqual( errors, [], "jQuery loaded" ); } ); testIframeWithCallback( "Don't call window.onready (#14802)", "core/onready.html", function( error ) { expect( 1 ); equal( error, false, "no call to user-defined onready" ); } );
class Array alias append push end
package cli import ( "fmt" "github.com/capitancambio/go-subcommand" //"github.com/capitancambio/go-subcommand" //"github.com/daisy-consortium/pipeline-clientlib-go" "io/ioutil" "log" "os" "testing" ) func TestGetBasePath(t *testing.T) { //return os.Getwd() basePath := getBasePath(true) if len(basePath) == 0 { t.Error("Base path is 0") } if basePath[len(basePath)-1] != "/"[0] { t.Error("Last element of the basePath should be /") } basePath = getBasePath(false) if len(basePath) != 0 { t.Errorf("Base path len is !=0: %v", basePath) } } func TestParseInputs(t *testing.T) { log.SetOutput(ioutil.Discard) url, err := pathToUri(in1, "") if err != nil { t.Errorf("Unexpected error %v", err) return } if url.String() != in1 { t.Errorf("Url 1 is not formatted %v", url.String()) } url, err = pathToUri(in2, "") if err != nil { t.Errorf("Unexpected error %v", err) return } if url.String() != in2 { t.Errorf("Url 2 is not formatted %v", url.String()) } } func TestParseInputsBased(t *testing.T) { url, err := pathToUri(in1, "/mydata/") if !os.IsNotExist(err) { t.Errorf("Unexpected pass %v", err) if err != nil { t.Errorf("Unexpected error %v", err) return } } if url.String() != "file:///mydata/"+"tmp/dir1/file.xml" { t.Errorf("Url 1 is not formated %v", url.String()) } // for windows oldSep := pathSeparator defer func() { pathSeparator = oldSep }() pathSeparator = '\\' url, err = pathToUri(in1, "C:\\Users\\bert\\mydata\\") if !os.IsNotExist(err) { t.Errorf("Unexpected pass %v", err) if err != nil { t.Errorf("Unexpected error %v", err) return } } if url.String() != "file:///C:/Users/bert/mydata/tmp/dir1/file.xml" { t.Errorf("Url 1 is not formated %v", url.String()) } } func TestScriptPriority(t *testing.T) { config := copyConf() config[STARTING] = false pipeline := newPipelineTest(false) pipeline.fsallow = false link := &PipelineLink{pipeline: pipeline, config: config} cli, err := makeCli("test", link) link.pipeline.(*PipelineTest).withScripts = false if err != nil { t.Error("Unexpected error") } jobRequest, err := scriptToCommand(SCRIPT, cli, link) if err != nil { t.Error("Unexpected error") } //parser.Parse([]string{"test","--source","value"}) err = cli.Run([]string{"test", "-o", os.TempDir(), "-d", os.TempDir(), "--source", "./tmp/file", "--single", "./tmp/file2", "--test-opt", "./myfile.xml", "--another-opt", "bar", "--priority", "low"}) if err != nil { t.Errorf("Unexpected error %v", err) } if jobRequest.Priority != "low" { t.Errorf("Priority not set %s!=%s", jobRequest.Priority, "low") } } func TestScriptNiceName(t *testing.T) { config := copyConf() config[STARTING] = false pipeline := newPipelineTest(false) pipeline.fsallow = false link := &PipelineLink{pipeline: pipeline, config: config} cli, err := makeCli("test", link) link.pipeline.(*PipelineTest).withScripts = false if err != nil { t.Error("Unexpected error") } jobRequest, err := scriptToCommand(SCRIPT, cli, link) if err != nil { t.Error("Unexpected error") } //parser.Parse([]string{"test","--source","value"}) err = cli.Run([]string{"test", "-o", os.TempDir(), "-d", os.TempDir(), "--source", "./tmp/file", "--single", "./tmp/file2", "--test-opt", "./myfile.xml", "--another-opt", "bar", "--nicename", "my_job"}) if err != nil { t.Errorf("Unexpected error %v", err) } if jobRequest.Nicename != "my_job" { t.Errorf("Nice name not set %s!=%s", jobRequest.Nicename, "my_job") } } func TestScriptPriorityMedium(t *testing.T) { config := copyConf() config[STARTING] = false pipeline := newPipelineTest(false) pipeline.fsallow = false link := &PipelineLink{pipeline: pipeline, config: config} cli, err := makeCli("test", link) link.pipeline.(*PipelineTest).withScripts = false if err != nil { t.Error("Unexpected error") } _, err = scriptToCommand(SCRIPT, cli, link) if err != nil { t.Error("Unexpected error") } ////medium err = cli.Run([]string{"test", "-o", os.TempDir(), "-d", os.TempDir(), "--source", "./tmp/file", "--single", "./tmp/file2", "--test-opt", "./myfile.xml", "--another-opt", "bar", "--priority", "medium"}) if err != nil { t.Errorf("Unexpected error %v", err) } } func TestScriptPriorityHigh(t *testing.T) { config := copyConf() config[STARTING] = false pipeline := newPipelineTest(false) pipeline.fsallow = false link := &PipelineLink{pipeline: pipeline, config: config} cli, err := makeCli("test", link) link.pipeline.(*PipelineTest).withScripts = false if err != nil { t.Error("Unexpected error") } _, err = scriptToCommand(SCRIPT, cli, link) if err != nil { t.Error("Unexpected error") } ////medium err = cli.Run([]string{"test", "-o", os.TempDir(), "-d", os.TempDir(), "--source", "./tmp/file", "--single", "./tmp/file2", "--test-opt", "./myfile.xml", "--another-opt", "bar", "--priority", "high"}) if err != nil { t.Errorf("Unexpected error %v", err) } } func TestScriptPriorityWrongValue(t *testing.T) { config := copyConf() config[STARTING] = false pipeline := newPipelineTest(false) pipeline.fsallow = false link := &PipelineLink{pipeline: pipeline, config: config} cli, err := makeCli("test", link) link.pipeline.(*PipelineTest).withScripts = false if err != nil { t.Error("Unexpected error") } _, err = scriptToCommand(SCRIPT, cli, link) if err != nil { t.Error("Unexpected error") } err = cli.Run([]string{"test", "-o", os.TempDir(), "-d", os.TempDir(), "--source", "./tmp/file", "--single", "./tmp/file2", "--test-opt", "./myfile.xml", "--another-opt", "bar", "--priority", "not_so_low"}) if err == nil { t.Errorf("Wrong priority value didn't error") } } func TestScriptToCommand(t *testing.T) { config := copyConf() config[STARTING] = false pipeline := newPipelineTest(false) pipeline.fsallow = false link := &PipelineLink{pipeline: pipeline, config: config} cli, err := makeCli("test", link) link.pipeline.(*PipelineTest).withScripts = false if err != nil { t.Error("Unexpected error") } jobRequest, err := scriptToCommand(SCRIPT, cli, link) if err != nil { t.Error("Unexpected error") } //parser.Parse([]string{"test","--source","value"}) err = cli.Run([]string{"test", "-o", os.TempDir(), "-d", os.TempDir(), "--source", "./tmp/file", "--single", "./tmp/file2", "--test-opt", "./myfile.xml", "--another-opt", "bar"}) if err != nil { t.Errorf("Unexpected error %v", err) } if jobRequest.Script != "test" { t.Error("script not set") } fmt.Printf("jobRequest.Inputs %+v\n", jobRequest.Inputs) if jobRequest.Inputs["source"][0].String() != "./tmp/file" { t.Errorf("Input source not set %v", jobRequest.Inputs["source"][0].String()) } if jobRequest.Inputs["single"][0].String() != "./tmp/file2" { t.Errorf("Input source not set %v", jobRequest.Inputs["source"][0].String()) } if jobRequest.Options["test-opt"][0] != "./myfile.xml" { t.Errorf("Option test opt not set %v", jobRequest.Options["test-opt"][0]) } if jobRequest.Options["another-opt"][0] != "bar" { t.Errorf("Option test opt not set %v", jobRequest.Options["another-opt"][0]) } } func TestScriptToCommandNoLocalFail(t *testing.T) { config[STARTING] = false pipeline := newPipelineTest(false) pipeline.fsallow = false link := &PipelineLink{pipeline: pipeline, config: config} cli, err := makeCli("test", link) if err != nil { t.Error("Unexpected error") } overrideOutput(cli) link.pipeline.(*PipelineTest).withScripts = false _, err = scriptToCommand(SCRIPT, cli, link) if err != nil { t.Error("Unexpected error") } //parser.Parse([]string{"test","--source","value"}) err = cli.Run([]string{"test", "-o", os.TempDir(), "--source", "./tmp/file", "--single", "./tmp/file2", "--test-opt", "./myfile.xml", "--another-opt", "bar"}) if err == nil { t.Error("Expected error not thrown") } } func TestCliRequiredOptions(t *testing.T) { config[STARTING] = false link := &PipelineLink{FsAllow: true, pipeline: newPipelineTest(true), config: config} cli, err := makeCli("test", link) if err != nil { t.Error("Unexpected error") } overrideOutput(cli) _, err = scriptToCommand(SCRIPT, cli, link) if err != nil { t.Error("Unexpected error") } link.pipeline.(*PipelineTest).withScripts = false //parser.Parse([]string{"test","--source","value"}) err = cli.Run([]string{"test", "--source", "./tmp/file", "--single", "./tmp/file2", "--another-opt", "bar"}) if err == nil { t.Errorf("Missing required option wasn't thrown") } } func TestStoreLastId(t *testing.T) { LastIdPath = os.TempDir() + string(os.PathSeparator) + "testLastId" //mariachi style id := "ayayyyyaaay" err := storeLastId(id) if err != nil { t.Errorf("Unexpected error %v", err) } idGet, err := getLastId() if err != nil { t.Errorf("Unexpected error %v", err) } if id != idGet { t.Errorf("Wrong %v\n\tExpected: %v\n\tResult: %v", "id ", id, idGet) } os.Remove(LastIdPath) } func TestGetLastIdErr(t *testing.T) { LastIdPath = os.TempDir() + string(os.PathSeparator) + "pipeline_go_testing_id_bad" _, err := getLastId() if err == nil { t.Error("Expected error not thrown") } LastIdPath = os.TempDir() + string(os.PathSeparator) + "testLastId" } func TestScriptNoOutput(t *testing.T) { config[STARTING] = false link := &PipelineLink{FsAllow: true, pipeline: newPipelineTest(false), config: config} cli, err := makeCli("test", link) if err != nil { t.Error("Unexpected error") } overrideOutput(cli) link.pipeline.(*PipelineTest).withScripts = false _, err = scriptToCommand(SCRIPT, cli, link) if err != nil { t.Error("Unexpected error") } //parser.Parse([]string{"test","--source","value"}) err = cli.Run([]string{"test", "--source", "./tmp/file", "--single", "./tmp/file2", "--test-opt", "./myfile.xml", "--another-opt", "bar"}) if err == nil { t.Errorf("No error thrown") } } func TestScriptDefault(t *testing.T) { pipeline := newPipelineTest(false) link := &PipelineLink{FsAllow: true, pipeline: pipeline} cli, err := makeCli("test", link) if err != nil { t.Error("Unexpected error") } overrideOutput(cli) link.pipeline.(*PipelineTest).withScripts = false _, err = scriptToCommand(SCRIPT, cli, link) if err != nil { t.Error("Unexpected error") } //parser.Parse([]string{"test","--source","value"}) err = cli.Run([]string{"test", "-o", os.TempDir(), "--source", "./tmp/file", "--single", "./tmp/file2", "--test-opt", "./myfile.xml", "--another-opt", "bar"}) // FIXME: make this job pass if !os.IsNotExist(err) { t.Errorf("Unexpected pass %v", err) if err != nil { t.Errorf("Unexpected error %v", err) return } if !pipeline.deleted { t.Error("Job not deleted ") } } } func TestScriptBackground(t *testing.T) { pipeline := newPipelineTest(false) link := &PipelineLink{FsAllow: true, pipeline: pipeline} cli, err := makeCli("test", link) if err != nil { t.Error("Unexpected error") } overrideOutput(cli) _, err = scriptToCommand(SCRIPT, cli, link) if err != nil { t.Error("Unexpected error") } link.pipeline.(*PipelineTest).withScripts = false //parser.Parse([]string{"test","--source","value"}) err = cli.Run([]string{"test", "-b", "-o", os.TempDir(), "--source", "./tmp/file", "--single", "./tmp/file2", "--test-opt", "./myfile.xml", "--another-opt", "bar"}) // FIXME: make this job pass if !os.IsNotExist(err) { t.Errorf("Unexpected pass %v", err) if err != nil { t.Errorf("Unexpected error %v", err) return } if pipeline.deleted { t.Error("Job deleted in the background") } if pipeline.count != 0 { t.Error("gathering the job several times in the background") } if pipeline.resulted { t.Error("tried to get the results from a background job") } } } func TestScriptPersistent(t *testing.T) { pipeline := newPipelineTest(false) link := &PipelineLink{FsAllow: true, pipeline: pipeline} cli, err := makeCli("test", link) if err != nil { t.Error("Unexpected error") } overrideOutput(cli) link.pipeline.(*PipelineTest).withScripts = false _, err = scriptToCommand(SCRIPT, cli, link) if err != nil { t.Error("Unexpected error") } //parser.Parse([]string{"test","--source","value"}) err = cli.Run([]string{"test", "-p", "-o", os.TempDir(), "--source", "./tmp/file", "--single", "./tmp/file2", "--test-opt", "./myfile.xml", "--another-opt", "bar"}) // FIXME: make this job pass if !os.IsNotExist(err) { t.Errorf("Unexpected pass %v", err) if err != nil { t.Errorf("Unexpected error %v", err) return } if pipeline.deleted { t.Error("Job deleted and should be persistent") } if pipeline.count == 0 { t.Error("Persistent job did not gather several times its status from the server") } if getCall(*link) != RESULTS_CALL { t.Errorf("Persistent job did not gather its results") } } } func TestGetFlagName(t *testing.T) { name := getFlagName("myflag", "", []subcommand.Flag{subcommand.Flag{}}) if name != "myflag" { t.Errorf("name is my myflag != %v", name) } } func TestGetFlagCommonName(t *testing.T) { name := getFlagName("myflag", "t-", []subcommand.Flag{subcommand.Flag{Long: "--myflag"}}) if name != "t-myflag" { t.Errorf("expting t-myflag!= %v", name) } } func TestGetFlagCommonExists(t *testing.T) { name := getFlagName("output", "t-", []subcommand.Flag{subcommand.Flag{}}) if name != "t-output" { t.Errorf("expting t-output != %v", name) } }
// Copyright (c) 2015 Andrew Sutton // All rights reserved #ifndef BEAKER_STRING_HPP #define BEAKER_STRING_HPP #include <cctype> #include <cstring> #include <algorithm> #include <iosfwd> #include <string> #include <stdexcept> // -------------------------------------------------------------------------- // // Strings // The string type. using String = std::string; // Returns true if c is the horizontal whitespace. // Note that vertical tabs and carriage returns // are considered horizontal white space. inline bool is_space(char c) { switch (c) { case ' ': case '\t': case '\r': case '\v': return true; default: return false; } } // Returns true if c is a newline character. inline bool is_newline(char c) { return c == '\n'; } // Returns true if c in the class [01]. inline bool is_binary_digit(char c) { return (c - '0' < 2); } // Returns true if c is in the class [0-9]. inline bool is_decimal_digit(char c) { return std::isdigit(c); } // If is a digit in base d, return n. Otherwise, // throw a runtime error. inline int if_in_base(int n, int b) { if (n < b) return n; else throw std::runtime_error("invalid digit"); } // Returns the integer value of a character in base b, // or -1 if the character is not a digit in that base. inline int char_to_int(char c, int b) { if ('0' <= c && c <= '9') return if_in_base(c - '0', b); if ('a' <= c && c <= 'z') return if_in_base(c - 'a' + 10, b); if ('A' <= c && c <= 'Z') return if_in_base(c - 'A' + 10, b); return if_in_base(c, 0); } // Returns the integer value of the string in [first, last), // which contains an integer representation in base b. If // [first, last) contains any characters that are not digits // in base b, this throws a runtime error. // // Note that T must be an integer type and is given as an // explicit template argument. template<typename T, typename I> inline T string_to_int(I first, I last, int b) { T n = 0; while (first != last) { n = n * b + char_to_int(*first, b); ++first; } return n; } // Returns the integer value of a string containing an // integer representation in base b. If s contains any // characters that are not digits in base b, this throws // a runtime error. template<typename T> inline T string_to_int(String const& s, int b) { return string_to_int<T>(s.begin(), s.end(), b); } // -------------------------------------------------------------------------- // // String builder // The string builder facilitates the caching of characters // needed to form a string during lexical analysis. // // TODO: Allow strings greater than 128 bytes in length. // Basically, this entails implementing the small-string // optimization. class String_builder { static constexpr int init_size = 128; public: String_builder(); String str() const; String take(); void put(char c); void put(char const*); void put(char const*, int n); void put(char const*, char const*); void clear(); private: char buf_[init_size]; int len_; }; inline String_builder::String_builder() : len_(0) { std::fill(buf_, buf_ + init_size, 0); } // FIXME: This should return a string view, but until // we can efficiently hash-compare a string view against // a string, it won't matter. inline String String_builder::str() const { return String(buf_, buf_ + len_); } // Return the string in the builder and then reset it. inline String String_builder::take() { String s = str(); clear(); return s; } inline void String_builder::put(char c) { if (len_ == init_size) throw std::runtime_error("string builder overflow"); buf_[len_++] = c; } inline void String_builder::put(char const* s) { put(s, std::strlen(s)); } inline void String_builder::put(char const* s, int n) { if (len_ + n >= init_size) throw std::runtime_error("string builder overflow"); std::copy_n(s, n, buf_ + len_); len_ += n; } inline void String_builder::put(char const* first, char const* last) { put(first, last - first); } // Reset the string builder so that it's content // is empty. inline void String_builder::clear() { std::fill(buf_, buf_ + init_size, 0); len_ = 0; } // -------------------------------------------------------------------------- // // String buffer // The string buffer class provides implements a simple // string-based buffer for a stream. The string must not // have null characters. class Stringbuf { public: Stringbuf() = default; Stringbuf(String const&); Stringbuf(std::istream& is); void assign(std::istream& is); char const* begin() const; char const* end() const; private: String buf_; }; // Initialize the sting buffer from a pre-existing // string. Note that this copies the string. inline Stringbuf::Stringbuf(String const& s) : buf_(s) { } // Returns an iterator to the beginning of the string // buffer. inline char const* Stringbuf::begin() const { return buf_.c_str(); } // Returns an iterator past the end of the string buffer. inline char const* Stringbuf::end() const { return begin() + buf_.size(); } #endif
<?php defined('SYSPATH') or die('No direct script access.'); /** * Twig loader. * * @package Kotwig * @author John Heathco <jheathco@gmail.com> */ class Kohana_Kotwig { /** * @var object Kotwig instance */ public static $instance; /** * @var Twig_Environment */ public $twig; /** * @var object Kotwig configuration (Kohana_Config object) */ public $config; public static function instance() { if ( ! Kotwig::$instance) { Kotwig::$instance = new static(); // Load Twig configuration Kotwig::$instance->config = Kohana::$config->load('kotwig'); // Create the the loader $views = Kohana::include_paths(); $look_in = array(); foreach ($views as $key => $view) { $dir = $view.Kotwig::$instance->config->templates; if (is_dir($dir)) { $look_in[] = $dir; } } $loader = new Twig_Loader_Filesystem($look_in); // Set up Twig Kotwig::$instance->twig = new Twig_Environment($loader, Kotwig::$instance->config->environment); foreach (Kotwig::$instance->config->extensions as $extension) { // Load extensions Kotwig::$instance->twig->addExtension(new $extension); } foreach (Kotwig::$instance->config->globals as $global => $object) { // Load globals Kotwig::$instance->twig->addGlobal($global, $object); } foreach (Kotwig::$instance->config->filters as $filter => $object) { // Load filters Kotwig::$instance->twig->addFilter($filter, $object); } } return Kotwig::$instance; } final private function __construct() { // This is a singleton class } } // End Kotwig
/* * Main header file for the ALSA sequencer * Copyright (c) 1998-1999 by Frank van de Pol <fvdpol@coil.demon.nl> * (c) 1998-1999 by Jaroslav Kysela <perex@perex.cz> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #ifndef __SOUND_ASEQUENCER_H #define __SOUND_ASEQUENCER_H #ifdef __KERNEL__ #include <linux/ioctl.h> #endif #include <sound/asound.h> /** version of the sequencer */ #define SNDRV_SEQ_VERSION SNDRV_PROTOCOL_VERSION (1, 0, 1) #ifdef __KERNEL__ /** * definition of sequencer event types */ /** system messages * event data type = #sndrv_seq_result_t */ #define SNDRV_SEQ_EVENT_SYSTEM 0 #define SNDRV_SEQ_EVENT_RESULT 1 /** note messages (channel specific) * event data type = #sndrv_seq_ev_note */ #define SNDRV_SEQ_EVENT_NOTE 5 #define SNDRV_SEQ_EVENT_NOTEON 6 #define SNDRV_SEQ_EVENT_NOTEOFF 7 #define SNDRV_SEQ_EVENT_KEYPRESS 8 /** control messages (channel specific) * event data type = #sndrv_seq_ev_ctrl */ #define SNDRV_SEQ_EVENT_CONTROLLER 10 #define SNDRV_SEQ_EVENT_PGMCHANGE 11 #define SNDRV_SEQ_EVENT_CHANPRESS 12 #define SNDRV_SEQ_EVENT_PITCHBEND 13 /**< from -8192 to 8191 */ #define SNDRV_SEQ_EVENT_CONTROL14 14 /**< 14 bit controller value */ #define SNDRV_SEQ_EVENT_NONREGPARAM 15 /**< 14 bit NRPN address + 14 bit unsigned value */ #define SNDRV_SEQ_EVENT_REGPARAM 16 /**< 14 bit RPN address + 14 bit unsigned value */ /** synchronisation messages * event data type = #sndrv_seq_ev_ctrl */ #define SNDRV_SEQ_EVENT_SONGPOS 20 /* Song Position Pointer with LSB and MSB values */ #define SNDRV_SEQ_EVENT_SONGSEL 21 /* Song Select with song ID number */ #define SNDRV_SEQ_EVENT_QFRAME 22 /* midi time code quarter frame */ #define SNDRV_SEQ_EVENT_TIMESIGN 23 /* SMF Time Signature event */ #define SNDRV_SEQ_EVENT_KEYSIGN 24 /* SMF Key Signature event */ /** timer messages * event data type = sndrv_seq_ev_queue_control_t */ #define SNDRV_SEQ_EVENT_START 30 /* midi Real Time Start message */ #define SNDRV_SEQ_EVENT_CONTINUE 31 /* midi Real Time Continue message */ #define SNDRV_SEQ_EVENT_STOP 32 /* midi Real Time Stop message */ #define SNDRV_SEQ_EVENT_SETPOS_TICK 33 /* set tick queue position */ #define SNDRV_SEQ_EVENT_SETPOS_TIME 34 /* set realtime queue position */ #define SNDRV_SEQ_EVENT_TEMPO 35 /* (SMF) Tempo event */ #define SNDRV_SEQ_EVENT_CLOCK 36 /* midi Real Time Clock message */ #define SNDRV_SEQ_EVENT_TICK 37 /* midi Real Time Tick message */ #define SNDRV_SEQ_EVENT_QUEUE_SKEW 38 /* skew queue tempo */ /** others * event data type = none */ #define SNDRV_SEQ_EVENT_TUNE_REQUEST 40 /* tune request */ #define SNDRV_SEQ_EVENT_RESET 41 /* reset to power-on state */ #define SNDRV_SEQ_EVENT_SENSING 42 /* "active sensing" event */ /** echo back, kernel private messages * event data type = any type */ #define SNDRV_SEQ_EVENT_ECHO 50 /* echo event */ #define SNDRV_SEQ_EVENT_OSS 51 /* OSS raw event */ /** system status messages (broadcast for subscribers) * event data type = sndrv_seq_addr_t */ #define SNDRV_SEQ_EVENT_CLIENT_START 60 /* new client has connected */ #define SNDRV_SEQ_EVENT_CLIENT_EXIT 61 /* client has left the system */ #define SNDRV_SEQ_EVENT_CLIENT_CHANGE 62 /* client status/info has changed */ #define SNDRV_SEQ_EVENT_PORT_START 63 /* new port was created */ #define SNDRV_SEQ_EVENT_PORT_EXIT 64 /* port was deleted from system */ #define SNDRV_SEQ_EVENT_PORT_CHANGE 65 /* port status/info has changed */ /** port connection changes * event data type = sndrv_seq_connect_t */ #define SNDRV_SEQ_EVENT_PORT_SUBSCRIBED 66 /* ports connected */ #define SNDRV_SEQ_EVENT_PORT_UNSUBSCRIBED 67 /* ports disconnected */ /* 70-89: synthesizer events - obsoleted */ /** user-defined events with fixed length * event data type = any */ #define SNDRV_SEQ_EVENT_USR0 90 #define SNDRV_SEQ_EVENT_USR1 91 #define SNDRV_SEQ_EVENT_USR2 92 #define SNDRV_SEQ_EVENT_USR3 93 #define SNDRV_SEQ_EVENT_USR4 94 #define SNDRV_SEQ_EVENT_USR5 95 #define SNDRV_SEQ_EVENT_USR6 96 #define SNDRV_SEQ_EVENT_USR7 97 #define SNDRV_SEQ_EVENT_USR8 98 #define SNDRV_SEQ_EVENT_USR9 99 /* 100-118: instrument layer - obsoleted */ /* 119-129: reserved */ /* 130-139: variable length events * event data type = sndrv_seq_ev_ext * (SNDRV_SEQ_EVENT_LENGTH_VARIABLE must be set) */ #define SNDRV_SEQ_EVENT_SYSEX 130 /* system exclusive data (variable length) */ #define SNDRV_SEQ_EVENT_BOUNCE 131 /* error event */ /* 132-134: reserved */ #define SNDRV_SEQ_EVENT_USR_VAR0 135 #define SNDRV_SEQ_EVENT_USR_VAR1 136 #define SNDRV_SEQ_EVENT_USR_VAR2 137 #define SNDRV_SEQ_EVENT_USR_VAR3 138 #define SNDRV_SEQ_EVENT_USR_VAR4 139 /* 150-151: kernel events with quote - DO NOT use in user clients */ #define SNDRV_SEQ_EVENT_KERNEL_ERROR 150 #define SNDRV_SEQ_EVENT_KERNEL_QUOTE 151 /* obsolete */ /* 152-191: reserved */ /* 192-254: hardware specific events */ /* 255: special event */ #define SNDRV_SEQ_EVENT_NONE 255 typedef unsigned char sndrv_seq_event_type_t; /** event address */ struct sndrv_seq_addr { unsigned char client; /**< Client number: 0..255, 255 = broadcast to all clients */ unsigned char port; /**< Port within client: 0..255, 255 = broadcast to all ports */ }; /** port connection */ struct sndrv_seq_connect { struct sndrv_seq_addr sender; struct sndrv_seq_addr dest; }; #define SNDRV_SEQ_ADDRESS_UNKNOWN 253 /* unknown source */ #define SNDRV_SEQ_ADDRESS_SUBSCRIBERS 254 /* send event to all subscribed ports */ #define SNDRV_SEQ_ADDRESS_BROADCAST 255 /* send event to all queues/clients/ports/channels */ #define SNDRV_SEQ_QUEUE_DIRECT 253 /* direct dispatch */ /* event mode flag - NOTE: only 8 bits available! */ #define SNDRV_SEQ_TIME_STAMP_TICK (0<<0) /* timestamp in clock ticks */ #define SNDRV_SEQ_TIME_STAMP_REAL (1<<0) /* timestamp in real time */ #define SNDRV_SEQ_TIME_STAMP_MASK (1<<0) #define SNDRV_SEQ_TIME_MODE_ABS (0<<1) /* absolute timestamp */ #define SNDRV_SEQ_TIME_MODE_REL (1<<1) /* relative to current time */ #define SNDRV_SEQ_TIME_MODE_MASK (1<<1) #define SNDRV_SEQ_EVENT_LENGTH_FIXED (0<<2) /* fixed event size */ #define SNDRV_SEQ_EVENT_LENGTH_VARIABLE (1<<2) /* variable event size */ #define SNDRV_SEQ_EVENT_LENGTH_VARUSR (2<<2) /* variable event size - user memory space */ #define SNDRV_SEQ_EVENT_LENGTH_MASK (3<<2) #define SNDRV_SEQ_PRIORITY_NORMAL (0<<4) /* normal priority */ #define SNDRV_SEQ_PRIORITY_HIGH (1<<4) /* event should be processed before others */ #define SNDRV_SEQ_PRIORITY_MASK (1<<4) /* note event */ struct sndrv_seq_ev_note { unsigned char channel; unsigned char note; unsigned char velocity; unsigned char off_velocity; /* only for SNDRV_SEQ_EVENT_NOTE */ unsigned int duration; /* only for SNDRV_SEQ_EVENT_NOTE */ }; /* controller event */ struct sndrv_seq_ev_ctrl { unsigned char channel; unsigned char unused1, unused2, unused3; /* pad */ unsigned int param; signed int value; }; /* generic set of bytes (12x8 bit) */ struct sndrv_seq_ev_raw8 { unsigned char d[12]; /* 8 bit value */ }; /* generic set of integers (3x32 bit) */ struct sndrv_seq_ev_raw32 { unsigned int d[3]; /* 32 bit value */ }; /* external stored data */ struct sndrv_seq_ev_ext { unsigned int len; /* length of data */ void *ptr; /* pointer to data (note: maybe 64-bit) */ } __attribute__((packed)); struct sndrv_seq_result { int event; /* processed event type */ int result; }; struct sndrv_seq_real_time { unsigned int tv_sec; /* seconds */ unsigned int tv_nsec; /* nanoseconds */ }; typedef unsigned int sndrv_seq_tick_time_t; /* midi ticks */ union sndrv_seq_timestamp { sndrv_seq_tick_time_t tick; struct sndrv_seq_real_time time; }; struct sndrv_seq_queue_skew { unsigned int value; unsigned int base; }; /* queue timer control */ struct sndrv_seq_ev_queue_control { unsigned char queue; /* affected queue */ unsigned char pad[3]; /* reserved */ union { signed int value; /* affected value (e.g. tempo) */ union sndrv_seq_timestamp time; /* time */ unsigned int position; /* sync position */ struct sndrv_seq_queue_skew skew; unsigned int d32[2]; unsigned char d8[8]; } param; }; /* quoted event - inside the kernel only */ struct sndrv_seq_ev_quote { struct sndrv_seq_addr origin; /* original sender */ unsigned short value; /* optional data */ struct sndrv_seq_event *event; /* quoted event */ } __attribute__((packed)); /* sequencer event */ struct sndrv_seq_event { sndrv_seq_event_type_t type; /* event type */ unsigned char flags; /* event flags */ char tag; unsigned char queue; /* schedule queue */ union sndrv_seq_timestamp time; /* schedule time */ struct sndrv_seq_addr source; /* source address */ struct sndrv_seq_addr dest; /* destination address */ union { /* event data... */ struct sndrv_seq_ev_note note; struct sndrv_seq_ev_ctrl control; struct sndrv_seq_ev_raw8 raw8; struct sndrv_seq_ev_raw32 raw32; struct sndrv_seq_ev_ext ext; struct sndrv_seq_ev_queue_control queue; union sndrv_seq_timestamp time; struct sndrv_seq_addr addr; struct sndrv_seq_connect connect; struct sndrv_seq_result result; struct sndrv_seq_ev_quote quote; } data; }; /* * bounce event - stored as variable size data */ struct sndrv_seq_event_bounce { int err; struct sndrv_seq_event event; /* external data follows here. */ }; #define sndrv_seq_event_bounce_ext_data(ev) ((void*)((char *)(ev)->data.ext.ptr + sizeof(sndrv_seq_event_bounce_t))) /* * type check macros */ /* result events: 0-4 */ #define sndrv_seq_ev_is_result_type(ev) ((ev)->type < 5) /* channel specific events: 5-19 */ #define sndrv_seq_ev_is_channel_type(ev) ((ev)->type >= 5 && (ev)->type < 20) /* note events: 5-9 */ #define sndrv_seq_ev_is_note_type(ev) ((ev)->type >= 5 && (ev)->type < 10) /* control events: 10-19 */ #define sndrv_seq_ev_is_control_type(ev) ((ev)->type >= 10 && (ev)->type < 20) /* queue control events: 30-39 */ #define sndrv_seq_ev_is_queue_type(ev) ((ev)->type >= 30 && (ev)->type < 40) /* system status messages */ #define sndrv_seq_ev_is_message_type(ev) ((ev)->type >= 60 && (ev)->type < 69) /* sample messages */ #define sndrv_seq_ev_is_sample_type(ev) ((ev)->type >= 70 && (ev)->type < 79) /* user-defined messages */ #define sndrv_seq_ev_is_user_type(ev) ((ev)->type >= 90 && (ev)->type < 99) /* fixed length events: 0-99 */ #define sndrv_seq_ev_is_fixed_type(ev) ((ev)->type < 100) /* variable length events: 130-139 */ #define sndrv_seq_ev_is_variable_type(ev) ((ev)->type >= 130 && (ev)->type < 140) /* reserved for kernel */ #define sndrv_seq_ev_is_reserved(ev) ((ev)->type >= 150) /* direct dispatched events */ #define sndrv_seq_ev_is_direct(ev) ((ev)->queue == SNDRV_SEQ_QUEUE_DIRECT) /* * macros to check event flags */ /* prior events */ #define sndrv_seq_ev_is_prior(ev) (((ev)->flags & SNDRV_SEQ_PRIORITY_MASK) == SNDRV_SEQ_PRIORITY_HIGH) /* event length type */ #define sndrv_seq_ev_length_type(ev) ((ev)->flags & SNDRV_SEQ_EVENT_LENGTH_MASK) #define sndrv_seq_ev_is_fixed(ev) (sndrv_seq_ev_length_type(ev) == SNDRV_SEQ_EVENT_LENGTH_FIXED) #define sndrv_seq_ev_is_variable(ev) (sndrv_seq_ev_length_type(ev) == SNDRV_SEQ_EVENT_LENGTH_VARIABLE) #define sndrv_seq_ev_is_varusr(ev) (sndrv_seq_ev_length_type(ev) == SNDRV_SEQ_EVENT_LENGTH_VARUSR) /* time-stamp type */ #define sndrv_seq_ev_timestamp_type(ev) ((ev)->flags & SNDRV_SEQ_TIME_STAMP_MASK) #define sndrv_seq_ev_is_tick(ev) (sndrv_seq_ev_timestamp_type(ev) == SNDRV_SEQ_TIME_STAMP_TICK) #define sndrv_seq_ev_is_real(ev) (sndrv_seq_ev_timestamp_type(ev) == SNDRV_SEQ_TIME_STAMP_REAL) /* time-mode type */ #define sndrv_seq_ev_timemode_type(ev) ((ev)->flags & SNDRV_SEQ_TIME_MODE_MASK) #define sndrv_seq_ev_is_abstime(ev) (sndrv_seq_ev_timemode_type(ev) == SNDRV_SEQ_TIME_MODE_ABS) #define sndrv_seq_ev_is_reltime(ev) (sndrv_seq_ev_timemode_type(ev) == SNDRV_SEQ_TIME_MODE_REL) /* queue sync port */ #define sndrv_seq_queue_sync_port(q) ((q) + 16) #endif /* __KERNEL__ */ /* system information */ struct sndrv_seq_system_info { int queues; /* maximum queues count */ int clients; /* maximum clients count */ int ports; /* maximum ports per client */ int channels; /* maximum channels per port */ int cur_clients; /* current clients */ int cur_queues; /* current queues */ char reserved[24]; }; /* system running information */ struct sndrv_seq_running_info { unsigned char client; /* client id */ unsigned char big_endian; /* 1 = big-endian */ unsigned char cpu_mode; /* 4 = 32bit, 8 = 64bit */ unsigned char pad; /* reserved */ unsigned char reserved[12]; }; /* known client numbers */ #define SNDRV_SEQ_CLIENT_SYSTEM 0 /* internal client numbers */ #define SNDRV_SEQ_CLIENT_DUMMY 14 /* midi through */ #define SNDRV_SEQ_CLIENT_OSS 15 /* oss sequencer emulator */ /* client types */ enum sndrv_seq_client_type { NO_CLIENT = 0, USER_CLIENT = 1, KERNEL_CLIENT = 2 }; /* event filter flags */ #define SNDRV_SEQ_FILTER_BROADCAST (1<<0) /* accept broadcast messages */ #define SNDRV_SEQ_FILTER_MULTICAST (1<<1) /* accept multicast messages */ #define SNDRV_SEQ_FILTER_BOUNCE (1<<2) /* accept bounce event in error */ #define SNDRV_SEQ_FILTER_USE_EVENT (1<<31) /* use event filter */ struct sndrv_seq_client_info { int client; /* client number to inquire */ int type; /* client type */ char name[64]; /* client name */ unsigned int filter; /* filter flags */ unsigned char multicast_filter[8]; /* multicast filter bitmap */ unsigned char event_filter[32]; /* event filter bitmap */ int num_ports; /* RO: number of ports */ int event_lost; /* number of lost events */ char reserved[64]; /* for future use */ }; /* client pool size */ struct sndrv_seq_client_pool { int client; /* client number to inquire */ int output_pool; /* outgoing (write) pool size */ int input_pool; /* incoming (read) pool size */ int output_room; /* minimum free pool size for select/blocking mode */ int output_free; /* unused size */ int input_free; /* unused size */ char reserved[64]; }; /* Remove events by specified criteria */ #define SNDRV_SEQ_REMOVE_INPUT (1<<0) /* Flush input queues */ #define SNDRV_SEQ_REMOVE_OUTPUT (1<<1) /* Flush output queues */ #define SNDRV_SEQ_REMOVE_DEST (1<<2) /* Restrict by destination q:client:port */ #define SNDRV_SEQ_REMOVE_DEST_CHANNEL (1<<3) /* Restrict by channel */ #define SNDRV_SEQ_REMOVE_TIME_BEFORE (1<<4) /* Restrict to before time */ #define SNDRV_SEQ_REMOVE_TIME_AFTER (1<<5) /* Restrict to time or after */ #define SNDRV_SEQ_REMOVE_TIME_TICK (1<<6) /* Time is in ticks */ #define SNDRV_SEQ_REMOVE_EVENT_TYPE (1<<7) /* Restrict to event type */ #define SNDRV_SEQ_REMOVE_IGNORE_OFF (1<<8) /* Do not flush off events */ #define SNDRV_SEQ_REMOVE_TAG_MATCH (1<<9) /* Restrict to events with given tag */ struct sndrv_seq_remove_events { unsigned int remove_mode; /* Flags that determine what gets removed */ union sndrv_seq_timestamp time; unsigned char queue; /* Queue for REMOVE_DEST */ struct sndrv_seq_addr dest; /* Address for REMOVE_DEST */ unsigned char channel; /* Channel for REMOVE_DEST */ int type; /* For REMOVE_EVENT_TYPE */ char tag; /* Tag for REMOVE_TAG */ int reserved[10]; /* To allow for future binary compatibility */ }; /* known port numbers */ #define SNDRV_SEQ_PORT_SYSTEM_TIMER 0 #define SNDRV_SEQ_PORT_SYSTEM_ANNOUNCE 1 /* port capabilities (32 bits) */ #define SNDRV_SEQ_PORT_CAP_READ (1<<0) /* readable from this port */ #define SNDRV_SEQ_PORT_CAP_WRITE (1<<1) /* writable to this port */ #define SNDRV_SEQ_PORT_CAP_SYNC_READ (1<<2) #define SNDRV_SEQ_PORT_CAP_SYNC_WRITE (1<<3) #define SNDRV_SEQ_PORT_CAP_DUPLEX (1<<4) #define SNDRV_SEQ_PORT_CAP_SUBS_READ (1<<5) /* allow read subscription */ #define SNDRV_SEQ_PORT_CAP_SUBS_WRITE (1<<6) /* allow write subscription */ #define SNDRV_SEQ_PORT_CAP_NO_EXPORT (1<<7) /* routing not allowed */ /* port type */ #define SNDRV_SEQ_PORT_TYPE_SPECIFIC (1<<0) /* hardware specific */ #define SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC (1<<1) /* generic MIDI device */ #define SNDRV_SEQ_PORT_TYPE_MIDI_GM (1<<2) /* General MIDI compatible device */ #define SNDRV_SEQ_PORT_TYPE_MIDI_GS (1<<3) /* GS compatible device */ #define SNDRV_SEQ_PORT_TYPE_MIDI_XG (1<<4) /* XG compatible device */ #define SNDRV_SEQ_PORT_TYPE_MIDI_MT32 (1<<5) /* MT-32 compatible device */ #define SNDRV_SEQ_PORT_TYPE_MIDI_GM2 (1<<6) /* General MIDI 2 compatible device */ /* other standards...*/ #define SNDRV_SEQ_PORT_TYPE_SYNTH (1<<10) /* Synth device (no MIDI compatible - direct wavetable) */ #define SNDRV_SEQ_PORT_TYPE_DIRECT_SAMPLE (1<<11) /* Sampling device (support sample download) */ #define SNDRV_SEQ_PORT_TYPE_SAMPLE (1<<12) /* Sampling device (sample can be downloaded at any time) */ /*...*/ #define SNDRV_SEQ_PORT_TYPE_HARDWARE (1<<16) /* driver for a hardware device */ #define SNDRV_SEQ_PORT_TYPE_SOFTWARE (1<<17) /* implemented in software */ #define SNDRV_SEQ_PORT_TYPE_SYNTHESIZER (1<<18) /* generates sound */ #define SNDRV_SEQ_PORT_TYPE_PORT (1<<19) /* connects to other device(s) */ #define SNDRV_SEQ_PORT_TYPE_APPLICATION (1<<20) /* application (sequencer/editor) */ /* misc. conditioning flags */ #define SNDRV_SEQ_PORT_FLG_GIVEN_PORT (1<<0) #define SNDRV_SEQ_PORT_FLG_TIMESTAMP (1<<1) #define SNDRV_SEQ_PORT_FLG_TIME_REAL (1<<2) struct sndrv_seq_port_info { struct sndrv_seq_addr addr; /* client/port numbers */ char name[64]; /* port name */ unsigned int capability; /* port capability bits */ unsigned int type; /* port type bits */ int midi_channels; /* channels per MIDI port */ int midi_voices; /* voices per MIDI port */ int synth_voices; /* voices per SYNTH port */ int read_use; /* R/O: subscribers for output (from this port) */ int write_use; /* R/O: subscribers for input (to this port) */ void *kernel; /* reserved for kernel use (must be NULL) */ unsigned int flags; /* misc. conditioning */ unsigned char time_queue; /* queue # for timestamping */ char reserved[59]; /* for future use */ }; /* queue flags */ #define SNDRV_SEQ_QUEUE_FLG_SYNC (1<<0) /* sync enabled */ /* queue information */ struct sndrv_seq_queue_info { int queue; /* queue id */ /* * security settings, only owner of this queue can start/stop timer * etc. if the queue is locked for other clients */ int owner; /* client id for owner of the queue */ int locked:1; /* timing queue locked for other queues */ char name[64]; /* name of this queue */ unsigned int flags; /* flags */ char reserved[60]; /* for future use */ }; /* queue info/status */ struct sndrv_seq_queue_status { int queue; /* queue id */ int events; /* read-only - queue size */ sndrv_seq_tick_time_t tick; /* current tick */ struct sndrv_seq_real_time time; /* current time */ int running; /* running state of queue */ int flags; /* various flags */ char reserved[64]; /* for the future */ }; /* queue tempo */ struct sndrv_seq_queue_tempo { int queue; /* sequencer queue */ unsigned int tempo; /* current tempo, us/tick */ int ppq; /* time resolution, ticks/quarter */ unsigned int skew_value; /* queue skew */ unsigned int skew_base; /* queue skew base */ char reserved[24]; /* for the future */ }; /* sequencer timer sources */ #define SNDRV_SEQ_TIMER_ALSA 0 /* ALSA timer */ #define SNDRV_SEQ_TIMER_MIDI_CLOCK 1 /* Midi Clock (CLOCK event) */ #define SNDRV_SEQ_TIMER_MIDI_TICK 2 /* Midi Timer Tick (TICK event) */ /* queue timer info */ struct sndrv_seq_queue_timer { int queue; /* sequencer queue */ int type; /* source timer type */ union { struct { struct sndrv_timer_id id; /* ALSA's timer ID */ unsigned int resolution; /* resolution in Hz */ } alsa; } u; char reserved[64]; /* for the future use */ }; struct sndrv_seq_queue_client { int queue; /* sequencer queue */ int client; /* sequencer client */ int used; /* queue is used with this client (must be set for accepting events) */ /* per client watermarks */ char reserved[64]; /* for future use */ }; #define SNDRV_SEQ_PORT_SUBS_EXCLUSIVE (1<<0) /* exclusive connection */ #define SNDRV_SEQ_PORT_SUBS_TIMESTAMP (1<<1) #define SNDRV_SEQ_PORT_SUBS_TIME_REAL (1<<2) struct sndrv_seq_port_subscribe { struct sndrv_seq_addr sender; /* sender address */ struct sndrv_seq_addr dest; /* destination address */ unsigned int voices; /* number of voices to be allocated (0 = don't care) */ unsigned int flags; /* modes */ unsigned char queue; /* input time-stamp queue (optional) */ unsigned char pad[3]; /* reserved */ char reserved[64]; }; /* type of query subscription */ #define SNDRV_SEQ_QUERY_SUBS_READ 0 #define SNDRV_SEQ_QUERY_SUBS_WRITE 1 struct sndrv_seq_query_subs { struct sndrv_seq_addr root; /* client/port id to be searched */ int type; /* READ or WRITE */ int index; /* 0..N-1 */ int num_subs; /* R/O: number of subscriptions on this port */ struct sndrv_seq_addr addr; /* R/O: result */ unsigned char queue; /* R/O: result */ unsigned int flags; /* R/O: result */ char reserved[64]; /* for future use */ }; /* * IOCTL commands */ #define SNDRV_SEQ_IOCTL_PVERSION _IOR ('S', 0x00, int) #define SNDRV_SEQ_IOCTL_CLIENT_ID _IOR ('S', 0x01, int) #define SNDRV_SEQ_IOCTL_SYSTEM_INFO _IOWR('S', 0x02, struct sndrv_seq_system_info) #define SNDRV_SEQ_IOCTL_RUNNING_MODE _IOWR('S', 0x03, struct sndrv_seq_running_info) #define SNDRV_SEQ_IOCTL_GET_CLIENT_INFO _IOWR('S', 0x10, struct sndrv_seq_client_info) #define SNDRV_SEQ_IOCTL_SET_CLIENT_INFO _IOW ('S', 0x11, struct sndrv_seq_client_info) #define SNDRV_SEQ_IOCTL_CREATE_PORT _IOWR('S', 0x20, struct sndrv_seq_port_info) #define SNDRV_SEQ_IOCTL_DELETE_PORT _IOW ('S', 0x21, struct sndrv_seq_port_info) #define SNDRV_SEQ_IOCTL_GET_PORT_INFO _IOWR('S', 0x22, struct sndrv_seq_port_info) #define SNDRV_SEQ_IOCTL_SET_PORT_INFO _IOW ('S', 0x23, struct sndrv_seq_port_info) #define SNDRV_SEQ_IOCTL_SUBSCRIBE_PORT _IOW ('S', 0x30, struct sndrv_seq_port_subscribe) #define SNDRV_SEQ_IOCTL_UNSUBSCRIBE_PORT _IOW ('S', 0x31, struct sndrv_seq_port_subscribe) #define SNDRV_SEQ_IOCTL_CREATE_QUEUE _IOWR('S', 0x32, struct sndrv_seq_queue_info) #define SNDRV_SEQ_IOCTL_DELETE_QUEUE _IOW ('S', 0x33, struct sndrv_seq_queue_info) #define SNDRV_SEQ_IOCTL_GET_QUEUE_INFO _IOWR('S', 0x34, struct sndrv_seq_queue_info) #define SNDRV_SEQ_IOCTL_SET_QUEUE_INFO _IOWR('S', 0x35, struct sndrv_seq_queue_info) #define SNDRV_SEQ_IOCTL_GET_NAMED_QUEUE _IOWR('S', 0x36, struct sndrv_seq_queue_info) #define SNDRV_SEQ_IOCTL_GET_QUEUE_STATUS _IOWR('S', 0x40, struct sndrv_seq_queue_status) #define SNDRV_SEQ_IOCTL_GET_QUEUE_TEMPO _IOWR('S', 0x41, struct sndrv_seq_queue_tempo) #define SNDRV_SEQ_IOCTL_SET_QUEUE_TEMPO _IOW ('S', 0x42, struct sndrv_seq_queue_tempo) #define SNDRV_SEQ_IOCTL_GET_QUEUE_OWNER _IOWR('S', 0x43, struct sndrv_seq_queue_owner) #define SNDRV_SEQ_IOCTL_SET_QUEUE_OWNER _IOW ('S', 0x44, struct sndrv_seq_queue_owner) #define SNDRV_SEQ_IOCTL_GET_QUEUE_TIMER _IOWR('S', 0x45, struct sndrv_seq_queue_timer) #define SNDRV_SEQ_IOCTL_SET_QUEUE_TIMER _IOW ('S', 0x46, struct sndrv_seq_queue_timer) /* XXX #define SNDRV_SEQ_IOCTL_GET_QUEUE_SYNC _IOWR('S', 0x53, struct sndrv_seq_queue_sync) #define SNDRV_SEQ_IOCTL_SET_QUEUE_SYNC _IOW ('S', 0x54, struct sndrv_seq_queue_sync) */ #define SNDRV_SEQ_IOCTL_GET_QUEUE_CLIENT _IOWR('S', 0x49, struct sndrv_seq_queue_client) #define SNDRV_SEQ_IOCTL_SET_QUEUE_CLIENT _IOW ('S', 0x4a, struct sndrv_seq_queue_client) #define SNDRV_SEQ_IOCTL_GET_CLIENT_POOL _IOWR('S', 0x4b, struct sndrv_seq_client_pool) #define SNDRV_SEQ_IOCTL_SET_CLIENT_POOL _IOW ('S', 0x4c, struct sndrv_seq_client_pool) #define SNDRV_SEQ_IOCTL_REMOVE_EVENTS _IOW ('S', 0x4e, struct sndrv_seq_remove_events) #define SNDRV_SEQ_IOCTL_QUERY_SUBS _IOWR('S', 0x4f, struct sndrv_seq_query_subs) #define SNDRV_SEQ_IOCTL_GET_SUBSCRIPTION _IOWR('S', 0x50, struct sndrv_seq_port_subscribe) #define SNDRV_SEQ_IOCTL_QUERY_NEXT_CLIENT _IOWR('S', 0x51, struct sndrv_seq_client_info) #define SNDRV_SEQ_IOCTL_QUERY_NEXT_PORT _IOWR('S', 0x52, struct sndrv_seq_port_info) #endif /* __SOUND_ASEQUENCER_H */
/* * Copyright (c) 2014 xxworkshop. All rights reserved. * Created by Broche Xu on 4/22/14 7:42 PM. */ package com.xxworkshop.ui.welcome; public final class ElementTransformation { public float x = 0f; public float xOffset = 0f; public float y = 0f; public float yOffset = 0f; public float w = 0f; public float wOffset = 0f; public float h = 0f; public float hOffset = 0f; public float a = 0f; public float aOffset = 0f; public ElementTransformation setxOffset(float xOffset) { this.xOffset = xOffset; return this; } public ElementTransformation setyOffset(float yOffset) { this.yOffset = yOffset; return this; } public ElementTransformation setwOffset(float wOffset) { this.wOffset = wOffset; return this; } public ElementTransformation sethOffset(float hOffset) { this.hOffset = hOffset; return this; } public ElementTransformation setaOffset(float aOffset) { this.aOffset = aOffset; return this; } public ElementTransformation setX(float x) { this.x = x; return this; } public ElementTransformation setY(float y) { this.y = y; return this; } public ElementTransformation setW(float w) { this.w = w; return this; } public ElementTransformation setH(float h) { this.h = h; return this; } public ElementTransformation setA(float a) { this.a = a; return this; } }
import java.util.LinkedHashSet; import java.util.ArrayList; public class Problem003 { public static void main(String[] args) { long toFactor = 600851475143L; // Values to try: 4 6 9 16 30 13195 600851475143 LinkedHashSet<Long> primeFactorSet = new LinkedHashSet<>(); long nextCandidate = 2; do { if ((toFactor % nextCandidate) == 0) { primeFactorSet.add(nextCandidate); toFactor = toFactor / nextCandidate; } else { nextCandidate++; } } while ((nextCandidate * nextCandidate) <= toFactor); primeFactorSet.add(toFactor); ArrayList<Long> primeFactorList = new ArrayList<>(primeFactorSet); System.out.println(primeFactorList.get(primeFactorList.size() - 1)); } }
///////////////////////////////////////////////////////////////////////// // // © University of Southampton IT Innovation Centre, 2014 // // Copyright in this library belongs to the University of Southampton // IT Innovation Centre of Gamma House, Enterprise Road, // Chilworth Science Park, Southampton, SO16 7NS, UK. // // This software may not be used, sold, licensed, transferred, copied // or reproduced in whole or in part in any manner or form or in or // on any media by any person other than in accordance with the terms // of the Licence Agreement supplied with the software, or otherwise // without the prior written consent of the copyright owners. // // This software is distributed WITHOUT ANY WARRANTY, without even the // implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE, except where stated in the Licence Agreement supplied with // the software. // // Created By : Maxim Bashevoy // Created Date : 2014-04-22 // Created for Project : EXPERIMEDIA // ///////////////////////////////////////////////////////////////////////// package uk.ac.soton.itinnovation.ecc.service.domain; import java.util.ArrayList; /** * Represents a simple set of data points. */ public class EccGenericMeasurementSet { private String unit, type, timestamp = ""; private ArrayList<EccGenericMeasurement> data; public EccGenericMeasurementSet() { } public EccGenericMeasurementSet(String unit, String type, ArrayList<EccGenericMeasurement> data) { this.unit = unit; this.type = type; this.data = data; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getType() { return type; } public void setType(String type) { this.type = type; } public ArrayList<EccGenericMeasurement> getData() { return data; } public void setData(ArrayList<EccGenericMeasurement> data) { this.data = data; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } }
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Cosmosdb::Mgmt::V2020_06_01_preview module Models # # An Azure Cosmos DB trigger. # class SqlTriggerGetResults < ARMResourceProperties include MsRestAzure # @return [SqlTriggerGetPropertiesResource] attr_accessor :resource # # Mapper for SqlTriggerGetResults class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'SqlTriggerGetResults', type: { name: 'Composite', class_name: 'SqlTriggerGetResults', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, location: { client_side_validation: true, required: false, serialized_name: 'location', type: { name: 'String' } }, tags: { client_side_validation: true, required: false, serialized_name: 'tags', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, identity: { client_side_validation: true, required: false, serialized_name: 'identity', type: { name: 'Composite', class_name: 'ManagedServiceIdentity' } }, resource: { client_side_validation: true, required: false, serialized_name: 'properties.resource', type: { name: 'Composite', class_name: 'SqlTriggerGetPropertiesResource' } } } } } end end end end
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
<!DOCTYPE html> <!-- DO NOT EDIT! Generated by referrer-policy/generic/tools/generate.py using common/security-features/tools/template/test.release.html.template. --> <html> <head> <title>Referrer-Policy: Referrer Policy is set to 'no-referrer-when-downgrade'</title> <meta charset='utf-8'> <meta name="description" content="Check that non a priori insecure subresource gets the full Referrer URL. A priori insecure subresource gets no referrer information."> <link rel="author" title="Kristijan Burnik" href="burnik@chromium.org"> <link rel="help" href="https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-no-referrer-when-downgrade"> <meta name="assert" content="Referrer Policy: Expects stripped-referrer for xhr to cross-http origin and no-redirect redirection from http context."> <meta name="referrer" content="no-referrer-when-downgrade"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/security-features/resources/common.sub.js"></script> <script src="/referrer-policy/generic/test-case.sub.js"></script> </head> <body> <script> TestCase( { "expectation": "stripped-referrer", "origin": "cross-http", "redirection": "no-redirect", "source_context_list": [], "source_scheme": "http", "subresource": "xhr", "subresource_policy_deliveries": [] }, document.querySelector("meta[name=assert]").content, new SanityChecker() ).start(); </script> <div id="log"></div> </body> </html>
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Rubber_Ducky")] [assembly: AssemblyProduct("Rubber_Ducky")] [assembly: AssemblyDescription("")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. Only Windows // assemblies support COM. [assembly: ComVisible(false)] // On Windows, the following GUID is for the ID of the typelib if this // project is exposed to COM. On other platforms, it unique identifies the // title storage container when deploying this assembly to the device. [assembly: Guid("e085781f-04ab-4953-b732-259a8f757705")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")]
/** * This file is part of groufix. * Copyright (c) Stef Velzel. All rights reserved. * * groufix : graphics engine produced by Stef Velzel. * www : <www.vuzzel.nl> */ #include "groufix/core.h" #include <assert.h> /**************************** * Callback for GLFW errors. */ static void _gfx_glfw_error(int error, const char* description) { // Just log it as a groufix error, // this should already take care of threading. gfx_log_error("GLFW: %s", description); } /****************************/ GFX_API int gfx_init(void) { // Already initialized, just do nothing. if (_groufix.initialized) return 1; // Initialize global state. if (!_gfx_init()) { gfx_log_fatal("Could not initialize global state."); return 0; } gfx_log_info("Global state initialized succesfully."); // Ok so now we want to attach this thread as 'main' thread. // If this fails, undo everything... if (!gfx_attach()) goto terminate; // During initialization we log to stderr. // This because no logging file can be set, but we want the logs somewhere. // After logging is setup, init GLFW and the Vulkan loader. gfx_log_set_out(1); glfwSetErrorCallback(_gfx_glfw_error); if (!glfwInit()) goto terminate; if (!glfwVulkanSupported()) goto terminate; gfx_log_info("GLFW initialized succesfully, Vulkan loader found."); // Initialize all other internal state. if (!_gfx_vulkan_init()) goto terminate; if (!_gfx_devices_init()) goto terminate; if (!_gfx_monitors_init()) goto terminate; gfx_log_info("All internal state initialized succesfully, ready."); // If not in debug mode, disable logging to stderr again. #if defined (NDEBUG) gfx_log_set_out(0); #endif return 1; // Cleanup on failure. terminate: gfx_log_fatal("Could not initialize the engine."); gfx_terminate(); return 0; } /****************************/ GFX_API void gfx_terminate(void) { // Not yet initialized, just do nothing. if (!_groufix.initialized) return; // Terminate the contents of the engine. _gfx_monitors_terminate(); _gfx_devices_terminate(); _gfx_vulkan_terminate(); glfwTerminate(); // Detach and terminate. gfx_detach(); _gfx_terminate(); gfx_log_info("All internal state terminated."); } /****************************/ GFX_API int gfx_attach(void) { // Not yet initialized, cannot attach. if (!_groufix.initialized) return 0; // Already attached. if (_gfx_get_local()) return 1; // Create thread local state. if (!_gfx_create_local()) { gfx_log_error("Could not attach a thread."); return 0; } // Every thread identifies itself on stderr. gfx_log_info("Attached self to groufix."); // If not in debug mode, disable logging to stderr, // it's now the user's responsibility. #if defined (NDEBUG) gfx_log_set_out(0); #endif return 1; } /****************************/ GFX_API void gfx_detach(void) { // Not yet initialized or attached. if (!_groufix.initialized || !_gfx_get_local()) return; // Every thread may have one last say :) gfx_log_set_out(1); gfx_log_info("Detaching self from groufix."); _gfx_destroy_local(); } /****************************/ GFX_API void gfx_poll_events(void) { assert(_groufix.initialized); glfwPollEvents(); } /****************************/ GFX_API void gfx_wait_events(void) { assert(_groufix.initialized); glfwWaitEvents(); } /****************************/ GFX_API void gfx_wake(void) { assert(_groufix.initialized); glfwPostEmptyEvent(); }
{% extends "admin/base_site.html" %} {% load i18n %} {% if not is_popup %} {% block breadcrumbs %} {{ block.super }} <li><a href="../">{% trans "Site Manager" %}</a></li> <li class="active"> {% for app in app_list %} {% blocktrans with app.name as name %}{{ name }}{% endblocktrans %} {% endfor %} </li> {% endblock %} {% endif %} {% block admin_content %} <div class="span12 pad"> {% if title %}<h3 class="title">{{ title }}</h3>{% endif %} <div class="holder"> <div id="content-main"> {% if app_list %} {% for app in app_list %} <table class="table table-bordered table-striped" summary="{% blocktrans with app.name as name %}Models available in the {{ name }} application.{% endblocktrans %}"> <tr> <th colspan="2"><a href="{{ app.app_url }}" class="section">{% blocktrans with app.name as name %}{{ name }}{% endblocktrans %}</a></th> </tr> {% for model in app.models %} <tr> {% if model.perms.change %} <th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}</a></th> {% else %} <th scope="row">{{ model.name }}</th> {% endif %} <td width="20%"> <div data-toggle="buttons-checkbox" class="btn-group"> {% if model.perms.add %} <a href="{{ model.admin_url }}add/" class="btn-small">{% trans 'Add' %}</a> {% endif %} {% if model.perms.change %} <a href="{{ model.admin_url }}" class="btn-small">{% trans 'Change' %}</a> {% endif %} </div> </td> </tr> {% endfor %} </table> {% endfor %} {% else %} <p>{% trans "You don't have permission to edit anything." %}</p> {% endif %} </div> </div> </div> {% endblock admin_content %} {% block sidebar %}{% endblock sidebar %}
/* -*- c++ -*- */ /* * Copyright 2014 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_volk_64u_byteswap_u_H #define INCLUDED_volk_64u_byteswap_u_H #include <inttypes.h> #include <stdio.h> #ifdef LV_HAVE_SSE2 #include <emmintrin.h> /*! \brief Byteswaps (in-place) an aligned vector of int64_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_64u_byteswap_u_sse2(uint64_t* intsToSwap, unsigned int num_points){ uint32_t* inputPtr = (uint32_t*)intsToSwap; __m128i input, byte1, byte2, byte3, byte4, output; __m128i byte2mask = _mm_set1_epi32(0x00FF0000); __m128i byte3mask = _mm_set1_epi32(0x0000FF00); uint64_t number = 0; const unsigned int halfPoints = num_points / 2; for(;number < halfPoints; number++){ // Load the 32t values, increment inputPtr later since we're doing it in-place. input = _mm_loadu_si128((__m128i*)inputPtr); // Do the four shifts byte1 = _mm_slli_epi32(input, 24); byte2 = _mm_slli_epi32(input, 8); byte3 = _mm_srli_epi32(input, 8); byte4 = _mm_srli_epi32(input, 24); // Or bytes together output = _mm_or_si128(byte1, byte4); byte2 = _mm_and_si128(byte2, byte2mask); output = _mm_or_si128(output, byte2); byte3 = _mm_and_si128(byte3, byte3mask); output = _mm_or_si128(output, byte3); // Reorder the two words output = _mm_shuffle_epi32(output, _MM_SHUFFLE(2, 3, 0, 1)); // Store the results _mm_storeu_si128((__m128i*)inputPtr, output); inputPtr += 4; } // Byteswap any remaining points: number = halfPoints*2; for(; number < num_points; number++){ uint32_t output1 = *inputPtr; uint32_t output2 = inputPtr[1]; output1 = (((output1 >> 24) & 0xff) | ((output1 >> 8) & 0x0000ff00) | ((output1 << 8) & 0x00ff0000) | ((output1 << 24) & 0xff000000)); output2 = (((output2 >> 24) & 0xff) | ((output2 >> 8) & 0x0000ff00) | ((output2 << 8) & 0x00ff0000) | ((output2 << 24) & 0xff000000)); *inputPtr++ = output2; *inputPtr++ = output1; } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Byteswaps (in-place) an aligned vector of int64_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_64u_byteswap_generic(uint64_t* intsToSwap, unsigned int num_points){ uint32_t* inputPtr = (uint32_t*)intsToSwap; unsigned int point; for(point = 0; point < num_points; point++){ uint32_t output1 = *inputPtr; uint32_t output2 = inputPtr[1]; output1 = (((output1 >> 24) & 0xff) | ((output1 >> 8) & 0x0000ff00) | ((output1 << 8) & 0x00ff0000) | ((output1 << 24) & 0xff000000)); output2 = (((output2 >> 24) & 0xff) | ((output2 >> 8) & 0x0000ff00) | ((output2 << 8) & 0x00ff0000) | ((output2 << 24) & 0xff000000)); *inputPtr++ = output2; *inputPtr++ = output1; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_64u_byteswap_u_H */ #ifndef INCLUDED_volk_64u_byteswap_a_H #define INCLUDED_volk_64u_byteswap_a_H #include <inttypes.h> #include <stdio.h> #ifdef LV_HAVE_SSE2 #include <emmintrin.h> /*! \brief Byteswaps (in-place) an aligned vector of int64_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_64u_byteswap_a_sse2(uint64_t* intsToSwap, unsigned int num_points){ uint32_t* inputPtr = (uint32_t*)intsToSwap; __m128i input, byte1, byte2, byte3, byte4, output; __m128i byte2mask = _mm_set1_epi32(0x00FF0000); __m128i byte3mask = _mm_set1_epi32(0x0000FF00); uint64_t number = 0; const unsigned int halfPoints = num_points / 2; for(;number < halfPoints; number++){ // Load the 32t values, increment inputPtr later since we're doing it in-place. input = _mm_load_si128((__m128i*)inputPtr); // Do the four shifts byte1 = _mm_slli_epi32(input, 24); byte2 = _mm_slli_epi32(input, 8); byte3 = _mm_srli_epi32(input, 8); byte4 = _mm_srli_epi32(input, 24); // Or bytes together output = _mm_or_si128(byte1, byte4); byte2 = _mm_and_si128(byte2, byte2mask); output = _mm_or_si128(output, byte2); byte3 = _mm_and_si128(byte3, byte3mask); output = _mm_or_si128(output, byte3); // Reorder the two words output = _mm_shuffle_epi32(output, _MM_SHUFFLE(2, 3, 0, 1)); // Store the results _mm_store_si128((__m128i*)inputPtr, output); inputPtr += 4; } // Byteswap any remaining points: number = halfPoints*2; for(; number < num_points; number++){ uint32_t output1 = *inputPtr; uint32_t output2 = inputPtr[1]; output1 = (((output1 >> 24) & 0xff) | ((output1 >> 8) & 0x0000ff00) | ((output1 << 8) & 0x00ff0000) | ((output1 << 24) & 0xff000000)); output2 = (((output2 >> 24) & 0xff) | ((output2 >> 8) & 0x0000ff00) | ((output2 << 8) & 0x00ff0000) | ((output2 << 24) & 0xff000000)); *inputPtr++ = output2; *inputPtr++ = output1; } } #endif /* LV_HAVE_SSE2 */ #ifdef LV_HAVE_GENERIC /*! \brief Byteswaps (in-place) an aligned vector of int64_t's. \param intsToSwap The vector of data to byte swap \param numDataPoints The number of data points */ static inline void volk_64u_byteswap_a_generic(uint64_t* intsToSwap, unsigned int num_points){ uint32_t* inputPtr = (uint32_t*)intsToSwap; unsigned int point; for(point = 0; point < num_points; point++){ uint32_t output1 = *inputPtr; uint32_t output2 = inputPtr[1]; output1 = (((output1 >> 24) & 0xff) | ((output1 >> 8) & 0x0000ff00) | ((output1 << 8) & 0x00ff0000) | ((output1 << 24) & 0xff000000)); output2 = (((output2 >> 24) & 0xff) | ((output2 >> 8) & 0x0000ff00) | ((output2 << 8) & 0x00ff0000) | ((output2 << 24) & 0xff000000)); *inputPtr++ = output2; *inputPtr++ = output1; } } #endif /* LV_HAVE_GENERIC */ #endif /* INCLUDED_volk_64u_byteswap_a_H */
/* ** Nofrendo (c) 1998-2000 Matthew Conte (matt@conte.com) ** ** ** This program is free software; you can redistribute it and/or ** modify it under the terms of version 2 of the GNU Library 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 ** Library General Public License for more details. To obtain a ** copy of the GNU Library General Public License, write to the Free ** Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ** ** Any permitted reproduction of these routines, in whole or in part, ** must bear this legend. ** ** ** fds_snd.c ** ** Famicom Disk System sound emulation ** $Id: fds_snd.c,v 1.1 2003/01/08 07:04:35 tmmm Exp $ */ #include "types.h" #include "nes_apu.h" #include "fds_snd.h" static int32 fds_incsize = 0; /* mix sound channels together */ static int32 fds_process(void) { int32 output; output = 0; return output; } /* write to registers */ static void fds_write(uint32 address, uint8 value) { } /* reset state of vrcvi sound channels */ static void fds_reset(void) { fds_incsize = apu_getcyclerate(); } static void fds_init(void) { } /* TODO: bleh */ static void fds_shutdown(void) { } static apu_memwrite fds_memwrite[] = { { 0x4040, 0x4092, fds_write }, { -1, -1, NULL } }; apuext_t fds_ext = { fds_init, fds_shutdown, fds_reset, fds_process, NULL, /* no reads */ fds_memwrite }; /* ** $Log: fds_snd.c,v $ ** Revision 1.1 2003/01/08 07:04:35 tmmm ** initial import of Nosefart sources ** ** Revision 1.3 2000/07/03 02:18:53 matt ** much better external module exporting ** ** Revision 1.2 2000/06/20 04:06:16 matt ** migrated external sound definition to apu module ** ** Revision 1.1 2000/06/20 00:06:47 matt ** initial revision ** */
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import imp import os.path import sys import unittest # Disable lint check for finding modules: # pylint: disable=F0401 def _GetDirAbove(dirname): """Returns the directory "above" this file containing |dirname| (which must also be "above" this file).""" path = os.path.abspath(__file__) while True: path, tail = os.path.split(path) assert tail if tail == dirname: return path try: imp.find_module("mojom") except ImportError: sys.path.append(os.path.join(_GetDirAbove("pylib"), "pylib")) import mojom.parse.ast as ast import mojom.parse.lexer as lexer import mojom.parse.parser as parser class ParserTest(unittest.TestCase): """Tests |parser.Parse()|.""" def testTrivialValidSource(self): """Tests a trivial, but valid, .mojom source.""" source = """\ // This is a comment. module my_module { } """ expected = ast.Mojom( ast.Module(('IDENTIFIER', 'my_module'), None), ast.ImportList(), []) self.assertEquals(parser.Parse(source, "my_file.mojom"), expected) def testSourceWithCrLfs(self): """Tests a .mojom source with CR-LFs instead of LFs.""" source = "// This is a comment.\r\n\r\nmodule my_module {\r\n}\r\n" expected = ast.Mojom( ast.Module(('IDENTIFIER', 'my_module'), None), ast.ImportList(), []) self.assertEquals(parser.Parse(source, "my_file.mojom"), expected) def testUnexpectedEOF(self): """Tests a "truncated" .mojom source.""" source = """\ // This is a comment. module my_module { """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom: Error: Unexpected end of file$"): parser.Parse(source, "my_file.mojom") def testCommentLineNumbers(self): """Tests that line numbers are correctly tracked when comments are present.""" source1 = """\ // Isolated C++-style comments. // Foo. asdf1 """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:4: Error: Unexpected 'asdf1':\n *asdf1$"): parser.Parse(source1, "my_file.mojom") source2 = """\ // Consecutive C++-style comments. // Foo. // Bar. struct Yada { // Baz. // Quux. int32 x; }; asdf2 """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:10: Error: Unexpected 'asdf2':\n *asdf2$"): parser.Parse(source2, "my_file.mojom") source3 = """\ /* Single-line C-style comments. */ /* Foobar. */ /* Baz. */ asdf3 """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:5: Error: Unexpected 'asdf3':\n *asdf3$"): parser.Parse(source3, "my_file.mojom") source4 = """\ /* Multi-line C-style comments. */ /* Foo. Bar. */ /* Baz Quux. */ asdf4 """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:10: Error: Unexpected 'asdf4':\n *asdf4$"): parser.Parse(source4, "my_file.mojom") def testSimpleStruct(self): """Tests a simple .mojom source that just defines a struct.""" source = """\ module my_module { struct MyStruct { int32 a; double b; }; } // module my_module """ expected = ast.Mojom( ast.Module(('IDENTIFIER', 'my_module'), None), ast.ImportList(), [('STRUCT', 'MyStruct', None, [('FIELD', 'int32', 'a', ast.Ordinal(None), None), ('FIELD', 'double', 'b', ast.Ordinal(None), None)])]) self.assertEquals(parser.Parse(source, "my_file.mojom"), expected) def testSimpleStructWithoutModule(self): """Tests a simple struct without an enclosing module.""" source = """\ struct MyStruct { int32 a; double b; }; """ expected = ast.Mojom( None, ast.ImportList(), [('STRUCT', 'MyStruct', None, [('FIELD', 'int32', 'a', ast.Ordinal(None), None), ('FIELD', 'double', 'b', ast.Ordinal(None), None)])]) self.assertEquals(parser.Parse(source, "my_file.mojom"), expected) def testMissingModuleName(self): """Tests an (invalid) .mojom with a missing module name.""" source1 = """\ // Missing module name. module { struct MyStruct { int32 a; }; } """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:2: Error: Unexpected '{':\n *module {$"): parser.Parse(source1, "my_file.mojom") # Another similar case, but make sure that line-number tracking/reporting # is correct. source2 = """\ module // This line intentionally left unblank. { } """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:4: Error: Unexpected '{':\n *{$"): parser.Parse(source2, "my_file.mojom") def testEnums(self): """Tests that enum statements are correctly parsed.""" source = """\ module my_module { enum MyEnum1 { VALUE1, VALUE2 }; // No trailing comma. enum MyEnum2 { VALUE1 = -1, VALUE2 = 0, VALUE3 = + 987, // Check that space is allowed. VALUE4 = 0xAF12, VALUE5 = -0x09bcd, VALUE6 = VALUE5, VALUE7, // Leave trailing comma. }; } // my_module """ expected = ast.Mojom( ast.Module(('IDENTIFIER', 'my_module'), None), ast.ImportList(), [('ENUM', 'MyEnum1', [('ENUM_VALUE', 'VALUE1', None), ('ENUM_VALUE', 'VALUE2', None)]), ('ENUM', 'MyEnum2', [('ENUM_VALUE', 'VALUE1', '-1'), ('ENUM_VALUE', 'VALUE2', '0'), ('ENUM_VALUE', 'VALUE3', '+987'), ('ENUM_VALUE', 'VALUE4', '0xAF12'), ('ENUM_VALUE', 'VALUE5', '-0x09bcd'), ('ENUM_VALUE', 'VALUE6', ('IDENTIFIER', 'VALUE5')), ('ENUM_VALUE', 'VALUE7', None)])]) self.assertEquals(parser.Parse(source, "my_file.mojom"), expected) def testInvalidEnumInitializers(self): """Tests that invalid enum initializers are correctly detected.""" # No values. source1 = """\ enum MyEnum { }; """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:2: Error: Unexpected '}':\n" r" *};$"): parser.Parse(source1, "my_file.mojom") # Floating point value. source2 = "enum MyEnum { VALUE = 0.123 };" with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:1: Error: Unexpected '0\.123':\n" r"enum MyEnum { VALUE = 0\.123 };$"): parser.Parse(source2, "my_file.mojom") # Boolean value. source2 = "enum MyEnum { VALUE = true };" with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:1: Error: Unexpected 'true':\n" r"enum MyEnum { VALUE = true };$"): parser.Parse(source2, "my_file.mojom") def testConsts(self): """Tests some constants and struct members initialized with them.""" source = """\ module my_module { struct MyStruct { const int8 kNumber = -1; int8 number@0 = kNumber; }; } // my_module """ expected = ast.Mojom( ast.Module(('IDENTIFIER', 'my_module'), None), ast.ImportList(), [('STRUCT', 'MyStruct', None, [('CONST', 'int8', 'kNumber', '-1'), ('FIELD', 'int8', 'number', ast.Ordinal(0), ('IDENTIFIER', 'kNumber'))])]) self.assertEquals(parser.Parse(source, "my_file.mojom"), expected) def testNoConditionals(self): """Tests that ?: is not allowed.""" source = """\ module my_module { enum MyEnum { MY_ENUM_1 = 1 ? 2 : 3 }; } // my_module """ with self.assertRaisesRegexp( lexer.LexError, r"^my_file\.mojom:4: Error: Illegal character '\?'$"): parser.Parse(source, "my_file.mojom") def testSimpleOrdinals(self): """Tests that (valid) ordinal values are scanned correctly.""" source = """\ module my_module { // This isn't actually valid .mojom, but the problem (missing ordinals) // should be handled at a different level. struct MyStruct { int32 a0@0; int32 a1@1; int32 a2@2; int32 a9@9; int32 a10 @10; int32 a11 @11; int32 a29 @29; int32 a1234567890 @1234567890; }; } // module my_module """ expected = ast.Mojom( ast.Module(('IDENTIFIER', 'my_module'), None), ast.ImportList(), [('STRUCT', 'MyStruct', None, [('FIELD', 'int32', 'a0', ast.Ordinal(0), None), ('FIELD', 'int32', 'a1', ast.Ordinal(1), None), ('FIELD', 'int32', 'a2', ast.Ordinal(2), None), ('FIELD', 'int32', 'a9', ast.Ordinal(9), None), ('FIELD', 'int32', 'a10', ast.Ordinal(10), None), ('FIELD', 'int32', 'a11', ast.Ordinal(11), None), ('FIELD', 'int32', 'a29', ast.Ordinal(29), None), ('FIELD', 'int32', 'a1234567890', ast.Ordinal(1234567890), None)])]) self.assertEquals(parser.Parse(source, "my_file.mojom"), expected) def testInvalidOrdinals(self): """Tests that (lexically) invalid ordinals are correctly detected.""" source1 = """\ module my_module { struct MyStruct { int32 a_missing@; }; } // module my_module """ with self.assertRaisesRegexp( lexer.LexError, r"^my_file\.mojom:4: Error: Missing ordinal value$"): parser.Parse(source1, "my_file.mojom") source2 = """\ module my_module { struct MyStruct { int32 a_octal@01; }; } // module my_module """ with self.assertRaisesRegexp( lexer.LexError, r"^my_file\.mojom:4: Error: " r"Octal and hexadecimal ordinal values not allowed$"): parser.Parse(source2, "my_file.mojom") source3 = """\ module my_module { struct MyStruct { int32 a_invalid_octal@08; }; } """ with self.assertRaisesRegexp( lexer.LexError, r"^my_file\.mojom:1: Error: " r"Octal and hexadecimal ordinal values not allowed$"): parser.Parse(source3, "my_file.mojom") source4 = "module my_module { struct MyStruct { int32 a_hex@0x1aB9; }; }" with self.assertRaisesRegexp( lexer.LexError, r"^my_file\.mojom:1: Error: " r"Octal and hexadecimal ordinal values not allowed$"): parser.Parse(source4, "my_file.mojom") source5 = "module my_module { struct MyStruct { int32 a_hex@0X0; }; }" with self.assertRaisesRegexp( lexer.LexError, r"^my_file\.mojom:1: Error: " r"Octal and hexadecimal ordinal values not allowed$"): parser.Parse(source5, "my_file.mojom") source6 = """\ struct MyStruct { int32 a_too_big@999999999999; }; """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:2: Error: " r"Ordinal value 999999999999 too large:\n" r" *int32 a_too_big@999999999999;$"): parser.Parse(source6, "my_file.mojom") def testNestedNamespace(self): """Tests that "nested" namespaces work.""" source = """\ module my.mod { struct MyStruct { int32 a; }; } // module my.mod """ expected = ast.Mojom( ast.Module(('IDENTIFIER', 'my.mod'), None), ast.ImportList(), [('STRUCT', 'MyStruct', None, [('FIELD', 'int32', 'a', ast.Ordinal(None), None)])]) self.assertEquals(parser.Parse(source, "my_file.mojom"), expected) def testValidHandleTypes(self): """Tests (valid) handle types.""" source = """\ struct MyStruct { handle a; handle<data_pipe_consumer> b; handle <data_pipe_producer> c; handle < message_pipe > d; handle < shared_buffer > e; }; """ expected = ast.Mojom( None, ast.ImportList(), [('STRUCT', 'MyStruct', None, [('FIELD', 'handle', 'a', ast.Ordinal(None), None), ('FIELD', 'handle<data_pipe_consumer>', 'b', ast.Ordinal(None), None), ('FIELD', 'handle<data_pipe_producer>', 'c', ast.Ordinal(None), None), ('FIELD', 'handle<message_pipe>', 'd', ast.Ordinal(None), None), ('FIELD', 'handle<shared_buffer>', 'e', ast.Ordinal(None), None)])]) self.assertEquals(parser.Parse(source, "my_file.mojom"), expected) def testInvalidHandleType(self): """Tests an invalid (unknown) handle type.""" source = """\ struct MyStruct { handle<wtf_is_this> foo; }; """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:2: Error: " r"Invalid handle type 'wtf_is_this':\n" r" *handle<wtf_is_this> foo;$"): parser.Parse(source, "my_file.mojom") def testValidDefaultValues(self): """Tests default values that are valid (to the parser).""" source = """\ struct MyStruct { int16 a0 = 0; uint16 a1 = 0x0; uint16 a2 = 0x00; uint16 a3 = 0x01; uint16 a4 = 0xcd; int32 a5 = 12345; int64 a6 = -12345; int64 a7 = +12345; uint32 a8 = 0x12cd3; uint32 a9 = -0x12cD3; uint32 a10 = +0x12CD3; bool a11 = true; bool a12 = false; float a13 = 1.2345; float a14 = -1.2345; float a15 = +1.2345; float a16 = 123.; float a17 = .123; double a18 = 1.23E10; double a19 = 1.E-10; double a20 = .5E+10; double a21 = -1.23E10; double a22 = +.123E10; }; """ expected = ast.Mojom( None, ast.ImportList(), [('STRUCT', 'MyStruct', None, [('FIELD', 'int16', 'a0', ast.Ordinal(None), '0'), ('FIELD', 'uint16', 'a1', ast.Ordinal(None), '0x0'), ('FIELD', 'uint16', 'a2', ast.Ordinal(None), '0x00'), ('FIELD', 'uint16', 'a3', ast.Ordinal(None), '0x01'), ('FIELD', 'uint16', 'a4', ast.Ordinal(None), '0xcd'), ('FIELD', 'int32', 'a5' , ast.Ordinal(None), '12345'), ('FIELD', 'int64', 'a6', ast.Ordinal(None), '-12345'), ('FIELD', 'int64', 'a7', ast.Ordinal(None), '+12345'), ('FIELD', 'uint32', 'a8', ast.Ordinal(None), '0x12cd3'), ('FIELD', 'uint32', 'a9', ast.Ordinal(None), '-0x12cD3'), ('FIELD', 'uint32', 'a10', ast.Ordinal(None), '+0x12CD3'), ('FIELD', 'bool', 'a11', ast.Ordinal(None), 'true'), ('FIELD', 'bool', 'a12', ast.Ordinal(None), 'false'), ('FIELD', 'float', 'a13', ast.Ordinal(None), '1.2345'), ('FIELD', 'float', 'a14', ast.Ordinal(None), '-1.2345'), ('FIELD', 'float', 'a15', ast.Ordinal(None), '+1.2345'), ('FIELD', 'float', 'a16', ast.Ordinal(None), '123.'), ('FIELD', 'float', 'a17', ast.Ordinal(None), '.123'), ('FIELD', 'double', 'a18', ast.Ordinal(None), '1.23E10'), ('FIELD', 'double', 'a19', ast.Ordinal(None), '1.E-10'), ('FIELD', 'double', 'a20', ast.Ordinal(None), '.5E+10'), ('FIELD', 'double', 'a21', ast.Ordinal(None), '-1.23E10'), ('FIELD', 'double', 'a22', ast.Ordinal(None), '+.123E10')])]) self.assertEquals(parser.Parse(source, "my_file.mojom"), expected) def testValidFixedSizeArray(self): """Tests parsing a fixed size array.""" source = """\ struct MyStruct { int32[] normal_array; int32[1] fixed_size_array_one_entry; int32[10] fixed_size_array_ten_entries; }; """ expected = ast.Mojom( None, ast.ImportList(), [('STRUCT', 'MyStruct', None, [('FIELD', 'int32[]', 'normal_array', ast.Ordinal(None), None), ('FIELD', 'int32[1]', 'fixed_size_array_one_entry', ast.Ordinal(None), None), ('FIELD', 'int32[10]', 'fixed_size_array_ten_entries', ast.Ordinal(None), None)])]) self.assertEquals(parser.Parse(source, "my_file.mojom"), expected) def testValidNestedArray(self): """Tests parsing a nested array.""" source = "struct MyStruct { int32[][] nested_array; };" expected = ast.Mojom( None, ast.ImportList(), [('STRUCT', 'MyStruct', None, [('FIELD', 'int32[][]', 'nested_array', ast.Ordinal(None), None)])]) self.assertEquals(parser.Parse(source, "my_file.mojom"), expected) def testInvalidFixedArraySize(self): """Tests that invalid fixed array bounds are correctly detected.""" source1 = """\ struct MyStruct { int32[0] zero_size_array; }; """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:2: Error: Fixed array size 0 invalid\n" r" *int32\[0\] zero_size_array;$"): parser.Parse(source1, "my_file.mojom") source2 = """\ struct MyStruct { int32[999999999999] too_big_array; }; """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:2: Error: Fixed array size 999999999999 invalid\n" r" *int32\[999999999999\] too_big_array;$"): parser.Parse(source2, "my_file.mojom") source3 = """\ struct MyStruct { int32[abcdefg] not_a_number; }; """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:2: Error: Unexpected 'abcdefg':\n" r" *int32\[abcdefg\] not_a_number;"): parser.Parse(source3, "my_file.mojom") def testValidMethod(self): """Tests parsing method declarations.""" source1 = "interface MyInterface { MyMethod(int32 a); };" expected1 = ast.Mojom( None, ast.ImportList(), [('INTERFACE', 'MyInterface', None, [('METHOD', 'MyMethod', ast.ParameterList(ast.Parameter('int32', 'a', ast.Ordinal(None))), ast.Ordinal(None), None)])]) self.assertEquals(parser.Parse(source1, "my_file.mojom"), expected1) source2 = """\ interface MyInterface { MyMethod1@0(int32 a@0, int64 b@1); MyMethod2@1() => (); }; """ expected2 = ast.Mojom( None, ast.ImportList(), [('INTERFACE', 'MyInterface', None, [('METHOD', 'MyMethod1', ast.ParameterList([ast.Parameter('int32', 'a', ast.Ordinal(0)), ast.Parameter('int64', 'b', ast.Ordinal(1))]), ast.Ordinal(0), None), ('METHOD', 'MyMethod2', ast.ParameterList(), ast.Ordinal(1), ast.ParameterList())])]) self.assertEquals(parser.Parse(source2, "my_file.mojom"), expected2) source3 = """\ interface MyInterface { MyMethod(string a) => (int32 a, bool b); }; """ expected3 = ast.Mojom( None, ast.ImportList(), [('INTERFACE', 'MyInterface', None, [('METHOD', 'MyMethod', ast.ParameterList(ast.Parameter('string', 'a', ast.Ordinal(None))), ast.Ordinal(None), ast.ParameterList([ast.Parameter('int32', 'a', ast.Ordinal(None)), ast.Parameter('bool', 'b', ast.Ordinal(None))]))])]) self.assertEquals(parser.Parse(source3, "my_file.mojom"), expected3) def testInvalidMethods(self): """Tests that invalid method declarations are correctly detected.""" # No trailing commas. source1 = """\ interface MyInterface { MyMethod(string a,); }; """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:2: Error: Unexpected '\)':\n" r" *MyMethod\(string a,\);$"): parser.Parse(source1, "my_file.mojom") # No leading commas. source2 = """\ interface MyInterface { MyMethod(, string a); }; """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:2: Error: Unexpected ',':\n" r" *MyMethod\(, string a\);$"): parser.Parse(source2, "my_file.mojom") def testValidAttributes(self): """Tests parsing attributes (and attribute lists).""" # Note: We use structs because they have (optional) attribute lists. # Empty attribute list. source1 = "[] struct MyStruct {};" expected1 = ast.Mojom( None, ast.ImportList(), [('STRUCT', 'MyStruct', ast.AttributeList(), None)]) self.assertEquals(parser.Parse(source1, "my_file.mojom"), expected1) # One-element attribute list, with name value. source2 = "[MyAttribute=MyName] struct MyStruct {};" expected2 = ast.Mojom( None, ast.ImportList(), [('STRUCT', 'MyStruct', ast.AttributeList(ast.Attribute("MyAttribute", "MyName")), None)]) self.assertEquals(parser.Parse(source2, "my_file.mojom"), expected2) # Two-element attribute list, with one string value and one integer value. source3 = "[MyAttribute1 = \"hello\", MyAttribute2 = 5] struct MyStruct {};" expected3 = ast.Mojom( None, ast.ImportList(), [('STRUCT', 'MyStruct', ast.AttributeList([ast.Attribute("MyAttribute1", "hello"), ast.Attribute("MyAttribute2", 5)]), None)]) self.assertEquals(parser.Parse(source3, "my_file.mojom"), expected3) # TODO(vtl): Boolean attributes don't work yet. (In fact, we just |eval()| # literal (non-name) values, which is extremely dubious.) def testInvalidAttributes(self): """Tests that invalid attributes and attribute lists are correctly detected.""" # Trailing commas not allowed. source1 = "[MyAttribute=MyName,] struct MyStruct {};" with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:1: Error: Unexpected '\]':\n" r"\[MyAttribute=MyName,\] struct MyStruct {};$"): parser.Parse(source1, "my_file.mojom") # Missing value. source2 = "[MyAttribute=] struct MyStruct {};" with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:1: Error: Unexpected '\]':\n" r"\[MyAttribute=\] struct MyStruct {};$"): parser.Parse(source2, "my_file.mojom") # Missing key. source3 = "[=MyName] struct MyStruct {};" with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:1: Error: Unexpected '=':\n" r"\[=MyName\] struct MyStruct {};$"): parser.Parse(source3, "my_file.mojom") def testValidImports(self): """Tests parsing import statements.""" # One import (no module statement). source1 = "import \"somedir/my.mojom\"" expected1 = ast.Mojom( None, ast.ImportList(ast.Import("somedir/my.mojom")), []) self.assertEquals(parser.Parse(source1, "my_file.mojom"), expected1) # Two imports (no module statement). source2 = """\ import "somedir/my1.mojom" import "somedir/my2.mojom" """ expected2 = ast.Mojom( None, ast.ImportList([ast.Import("somedir/my1.mojom"), ast.Import("somedir/my2.mojom")]), []) self.assertEquals(parser.Parse(source2, "my_file.mojom"), expected2) # Imports with module statement. source3 = """\ import "somedir/my1.mojom" import "somedir/my2.mojom" module my_module {} """ expected3 = ast.Mojom( ast.Module(('IDENTIFIER', 'my_module'), None), ast.ImportList([ast.Import("somedir/my1.mojom"), ast.Import("somedir/my2.mojom")]), []) def testInvalidImports(self): """Tests that invalid import statements are correctly detected.""" source1 = """\ // Make the error occur on line 2. import invalid """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:2: Error: Unexpected 'invalid':\n" r" *import invalid$"): parser.Parse(source1, "my_file.mojom") source2 = """\ import // Missing string. module {} """ with self.assertRaisesRegexp( parser.ParseError, r"^my_file\.mojom:2: Error: Unexpected 'module':\n" r" *module {}$"): parser.Parse(source2, "my_file.mojom") if __name__ == "__main__": unittest.main()
using System.Threading.Tasks; using Amplified.CSharp.Extensions; using Amplified.CSharp.Util; using Xunit; using static Amplified.CSharp.Maybe; namespace Amplified.CSharp { // ReSharper disable once InconsistentNaming public class AsyncMaybe_Map { [Fact] public async Task Sync_WhenSome_ReturnsMappedResult() { const int expected = 5; var result = await AsyncMaybe<int>.Some(2).Map(some => some + 3).OrFail(); Assert.Equal(expected, result); } [Fact] public async Task Sync_WhenNone_ReturnsNone() { var isNone = await AsyncMaybe<int>.None().Map(some => some + 3).IsNone; Assert.True(isNone); } #region Map<T>(Action<T> mapper) [Fact] public async Task Some_Map_ActionLambda_ReturnsSomeUnit() { var source = AsyncMaybe<int>.Some(5); var result = await source.Map(it => { }); var unit = result.MustBeSome(); Assert.IsType<Unit>(unit); } [Fact] public async Task Some_Map_ActionMethodReference_ReturnsSomeUnit() { void Foo(int it) {} var source = AsyncMaybe<int>.Some(5); var result = await source.Map(Foo); var unit = result.MustBeSome(); Assert.IsType<Unit>(unit); } [Fact] public async Task Some_Map_Action_ActionIsInvokedOnlyOnce() { var rec = new Recorder(); var source = AsyncMaybe<int>.Some(5); var result = await source.Map(rec.Record((int it) => { })); result.MustBeSome(); rec.MustHaveExactly(1.Invocations()); } [Fact] public async Task None_Map_Action_ActionIsNotInvoked() { var rec = new Recorder(); var source = AsyncMaybe<int>.None(); var result = await source.Map(rec.Record((int it) => { })); result.MustBeNone(); rec.MustHaveExactly(0.Invocations()); } [Fact] public async Task None_Map_Action_ReturnsNoneUnit() { var source = AsyncMaybe<int>.None(); var result = await source.Map(it => { }); result.MustBeNone(); } #endregion } }
//----------------------------------------------------------------------- // <copyright file="BuiltInActors.cs" company="Akka.NET Project"> // Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using Akka.Dispatch.SysMsg; using Akka.Event; namespace Akka.Actor { /// <summary> /// Class EventStreamActor. /// </summary> public class EventStreamActor : ActorBase { /// <summary> /// Processor for user defined messages. /// </summary> /// <param name="message">The message.</param> protected override bool Receive(object message) { return true; } } /// <summary> /// Class GuardianActor. /// </summary> public class GuardianActor : ActorBase { protected override bool Receive(object message) { if(message is Terminated) Context.Stop(Self); else if(message is StopChild) Context.Stop(((StopChild)message).Child); else Context.System.DeadLetters.Tell(new DeadLetter(message, Sender, Self), Sender); return true; } } /// <summary> /// System guardian. /// /// Root actor for all actors under the /system path. /// </summary> public class SystemGuardianActor : ActorBase { private readonly IActorRef _userGuardian; private readonly HashSet<IActorRef> _terminationHooks; public SystemGuardianActor(IActorRef userGuardian) { _userGuardian = userGuardian; _terminationHooks = new HashSet<IActorRef>(); } /// <summary> /// Processor for messages that are sent to the root system guardian /// </summary> /// <param name="message"></param> protected override bool Receive(object message) { var terminated = message as Terminated; if(terminated != null) { var terminatedActor = terminated.ActorRef; if(_userGuardian.Equals(terminatedActor)) { // time for the systemGuardian to stop, but first notify all the // termination hooks, they will reply with TerminationHookDone // and when all are done the systemGuardian is stopped Context.Become(Terminating); foreach(var terminationHook in _terminationHooks) { terminationHook.Tell(TerminationHook.Instance); } StopWhenAllTerminationHooksDone(); } else { // a registered, and watched termination hook terminated before // termination process of guardian has started _terminationHooks.Remove(terminatedActor); } return true; } var stopChild = message as StopChild; if(stopChild != null) { Context.Stop(stopChild.Child); return true; } var sender = Sender; var registerTerminationHook = message as RegisterTerminationHook; if(registerTerminationHook != null && !ReferenceEquals(sender, Context.System.DeadLetters)) { _terminationHooks.Add(sender); Context.Watch(sender); return true; } Context.System.DeadLetters.Tell(new DeadLetter(message, sender, Self), sender); return true; } private bool Terminating(object message) { var terminated = message as Terminated; if(terminated != null) { StopWhenAllTerminationHooksDone(terminated.ActorRef); return true; } var sender = Sender; var terminationHookDone = message as TerminationHookDone; if(terminationHookDone != null) { StopWhenAllTerminationHooksDone(sender); return true; } Context.System.DeadLetters.Tell(new DeadLetter(message, sender, Self), sender); return true; } private void StopWhenAllTerminationHooksDone(IActorRef terminatedActor) { _terminationHooks.Remove(terminatedActor); StopWhenAllTerminationHooksDone(); } private void StopWhenAllTerminationHooksDone() { if(_terminationHooks.Count == 0) { var actorSystem = Context.System; actorSystem.EventStream.StopDefaultLoggers(actorSystem); Context.Stop(Self); } } protected override void PreRestart(Exception reason, object message) { //Guardian MUST NOT lose its children during restart //Intentionally left blank } } /// <summary> /// Class DeadLetterActorRef. /// </summary> public class DeadLetterActorRef : EmptyLocalActorRef { private readonly EventStream _eventStream; public DeadLetterActorRef(IActorRefProvider provider, ActorPath path, EventStream eventStream) : base(provider, path, eventStream) { _eventStream = eventStream; } //TODO: Since this isn't overriding SendUserMessage it doesn't handle all messages as Akka JVM does protected override void HandleDeadLetter(DeadLetter deadLetter) { if(!SpecialHandle(deadLetter.Message, deadLetter.Sender)) _eventStream.Publish(deadLetter); } protected override bool SpecialHandle(object message, IActorRef sender) { var w = message as Watch; if(w != null) { if(w.Watchee != this && w.Watcher != this) { w.Watcher.Tell(new DeathWatchNotification(w.Watchee, existenceConfirmed: false, addressTerminated: false)); } return true; } return base.SpecialHandle(message, sender); } } }
package com.submarine.gameservices.quests; /** * Created by mariam on 5/5/15. */ public interface LoadedQuestListener { public void info(String name, String description); }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ru"> <head> <title>Uses of Class org.apache.poi.hsmf.datatypes.ByteChunk (POI API Documentation)</title> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.poi.hsmf.datatypes.ByteChunk (POI API Documentation)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/poi/hsmf/datatypes/ByteChunk.html" title="class in org.apache.poi.hsmf.datatypes">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/poi/hsmf/datatypes/class-use/ByteChunk.html" target="_top">Frames</a></li> <li><a href="ByteChunk.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.poi.hsmf.datatypes.ByteChunk" class="title">Uses of Class<br>org.apache.poi.hsmf.datatypes.ByteChunk</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/apache/poi/hsmf/datatypes/ByteChunk.html" title="class in org.apache.poi.hsmf.datatypes">ByteChunk</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.poi.hsmf.datatypes">org.apache.poi.hsmf.datatypes</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.poi.hsmf.datatypes"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/poi/hsmf/datatypes/ByteChunk.html" title="class in org.apache.poi.hsmf.datatypes">ByteChunk</a> in <a href="../../../../../../org/apache/poi/hsmf/datatypes/package-summary.html">org.apache.poi.hsmf.datatypes</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../../org/apache/poi/hsmf/datatypes/package-summary.html">org.apache.poi.hsmf.datatypes</a> declared as <a href="../../../../../../org/apache/poi/hsmf/datatypes/ByteChunk.html" title="class in org.apache.poi.hsmf.datatypes">ByteChunk</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/poi/hsmf/datatypes/ByteChunk.html" title="class in org.apache.poi.hsmf.datatypes">ByteChunk</a></code></td> <td class="colLast"><span class="strong">AttachmentChunks.</span><code><strong><a href="../../../../../../org/apache/poi/hsmf/datatypes/AttachmentChunks.html#attachData">attachData</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/poi/hsmf/datatypes/ByteChunk.html" title="class in org.apache.poi.hsmf.datatypes">ByteChunk</a></code></td> <td class="colLast"><span class="strong">AttachmentChunks.</span><code><strong><a href="../../../../../../org/apache/poi/hsmf/datatypes/AttachmentChunks.html#attachRenderingWMF">attachRenderingWMF</a></strong></code> <div class="block">This is in WMF Format.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/poi/hsmf/datatypes/ByteChunk.html" title="class in org.apache.poi.hsmf.datatypes">ByteChunk</a></code></td> <td class="colLast"><span class="strong">Chunks.</span><code><strong><a href="../../../../../../org/apache/poi/hsmf/datatypes/Chunks.html#htmlBodyChunkBinary">htmlBodyChunkBinary</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/poi/hsmf/datatypes/ByteChunk.html" title="class in org.apache.poi.hsmf.datatypes">ByteChunk</a></code></td> <td class="colLast"><span class="strong">RecipientChunks.</span><code><strong><a href="../../../../../../org/apache/poi/hsmf/datatypes/RecipientChunks.html#recipientSearchChunk">recipientSearchChunk</a></strong></code> <div class="block">TODO</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/poi/hsmf/datatypes/ByteChunk.html" title="class in org.apache.poi.hsmf.datatypes">ByteChunk</a></code></td> <td class="colLast"><span class="strong">Chunks.</span><code><strong><a href="../../../../../../org/apache/poi/hsmf/datatypes/Chunks.html#rtfBodyChunk">rtfBodyChunk</a></strong></code> <div class="block">BODY Rtf Chunk, for Rtf (Rich) messages</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/poi/hsmf/datatypes/ByteChunk.html" title="class in org.apache.poi.hsmf.datatypes">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/poi/hsmf/datatypes/class-use/ByteChunk.html" target="_top">Frames</a></li> <li><a href="ByteChunk.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright 2014 The Apache Software Foundation or its licensors, as applicable.</i> </small></p> </body> </html>
package com.nilhcem.droidconae.ui.core.picasso; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import com.squareup.picasso.Transformation; public class CircleTransformation implements Transformation { @Override public Bitmap transform(Bitmap source) { int size = Math.min(source.getWidth(), source.getHeight()); int x = (source.getWidth() - size) / 2; int y = (source.getHeight() - size) / 2; Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); if (squaredBitmap != source) { source.recycle(); } Bitmap.Config config = source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888; Bitmap bitmap = Bitmap.createBitmap(size, size, config); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); paint.setShader(shader); paint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, paint); squaredBitmap.recycle(); return bitmap; } @Override public String key() { return "circle"; } }
/* * Copyright 2009-2017 Aconex * * 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 io.pcp.parfait.timing; import java.util.concurrent.atomic.AtomicLong; import io.pcp.parfait.Counter; public interface ThreadCounter extends ThreadValue<AtomicLong>, Counter { public static class ThreadLocalCounter extends ThreadValue.ThreadLocalMap<AtomicLong> implements ThreadCounter { public ThreadLocalCounter() { super(new ThreadLocal<AtomicLong>() { @Override protected AtomicLong initialValue() { return new AtomicLong(); } }); } @Override public void inc() { inc(1L); } @Override public void inc(long increment) { threadLocal.get().addAndGet(increment); } } public static class ThreadMapCounter extends ThreadValue.WeakReferenceThreadMap<AtomicLong> implements ThreadCounter { public ThreadMapCounter() { super(); } @Override protected AtomicLong initialValue() { return new AtomicLong(); } @Override public void inc() { inc(1L); } @Override public void inc(long increment) { loadingCache.getUnchecked(Thread.currentThread()).addAndGet(increment); } } }
/* *** Sears '91 Neutron Scattering Length Data *** src/data/isotopes.h Copyright T. Youngs 2012-2018 This file is part of Dissolve. Dissolve is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Dissolve 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 Dissolve. If not, see <http://www.gnu.org/licenses/>. */ #ifndef DISSOLVE_ISOTOPESDATA_H #define DISSOLVE_ISOTOPESDATA_H #include "data/elements.h" #include "templates/array.h" #include "templates/list.h" // Isotopic Neutron Scattering Data class Isotope : public ElementReference, public ListItem<Isotope> { public: // Constructor Isotope(int z = 0, const char* symbol = NULL, int A = 0, const char* spin = NULL, double mass = 0.0, double bc = 0.0, double bi = 0.0, double sc = 0.0, double si = 0.0, double totalxs = 0.0, double absxs = 0.0); // Assignment Operator Isotope& operator=(const Isotope& source); /* * Isotope Data */ private: // Mass number (A) of isotope int A_; // Isotope mass(given C = 12) double mass_; // Nuclear spin description const char* spin_; // Bound coherent scattering length (fm) double boundCoherent_; // Bound incoherent scattering length (fm) double boundIncoherent_; // Bound coherent scattering cross section (barn) double boundCoherentXS_; // Bound incoherent scattering cross section (barn) double boundIncoherentXS_; // Total bound scattering cross section (barn) double totalXS_; // Absorption cross section for thermal (2200 m/s) neutron (barn) double absorptionXS_; public: // Return index of isotope in it's Element parent's list int index() const; // Return mass number (A) of Isotope int A() const; // Return isotope mass (given C = 12) double mass() const; // Return bound coherent scattering length (fm) double boundCoherent() const; // Return bound incoherent scattering length (fm) double boundIncoherent() const; // Return bound coherent scattering cross section (barn) double boundCoherentXS() const; // Return bound incoherent scattering cross section (barn) double boundIncoherentXS() const; // Return total bound scattering cross section (barn) double totalXS() const; // Return absorption cross section for thermal (2200 m/s) neutron (barn) double absorptionXS() const; }; // Sears '91 Isotope Data class Isotopes : public Elements { private: // Isotope data, grouped by element static Array< List<Isotope> > isotopesByElementPrivate_; private: // Return isotope data for specified Element static List<Isotope>& isotopesByElement(int Z); public: // Register specified Isotope to given Element static void registerIsotope(Isotope* isotope, int Z); // Return Isotope with specified A (if it exists) for given Z static Isotope* isotope(int Z, int A); // Return Isotope with specified A (if it exists) for given Element static Isotope* isotope(Element* el, int A); // Return Isotope with specified index (if it exists) in its parent Element static Isotope* isotopeAtIndex(int Z, int index); // Return List of all Isotopes available for specified Element static const List<Isotope>& isotopes(int Z); // Return natural Isotope for given Element static Isotope* naturalIsotope(Element* el); }; #endif
/* eslint-disable */ class Sizes extends React.Component { render() { return ( <Layout> <Cell> <TagList tags={[ { id: '1', children: 'Tag 1' }, { id: '2', children: 'Tag 2' }, { id: '3', children: 'Tag 3' }, ]} actionButton={{ label: 'Button' }} /> </Cell> <Cell> <TagList size="medium" tags={[ { id: '1', children: 'Tag 1' }, { id: '2', children: 'Tag 2' }, { id: '3', children: 'Tag 3' }, ]} actionButton={{ label: 'Button' }} /> </Cell> <Cell> <TagList size="large" tags={[ { id: '1', children: 'Tag 1' }, { id: '2', children: 'Tag 2' }, { id: '3', children: 'Tag 3' }, ]} actionButton={{ label: 'Button' }} /> </Cell> </Layout> ); } }
/* =Primary Layout ----------------------------------------------- */ #slider_blvd #optionsframework .metabox-holder { max-width: 780px; } #slider_blvd #optionsframework, #slider_blvd #optionsframework .full-width { max-width: none; } #slider_blvd #optionsframework .updated { max-width: none; } #slider_blvd #optionsframework .inner-sidebar .section .heading { font-size: 1em; } /* =Manage Slides ----------------------------------------------- */ #slider_blvd #edit_slider #titlediv { margin: 10px 0 10px 0; } #slider_blvd #edit_slider #titlediv h2 { float: left; margin: 0 12px; } #slider_blvd #edit_slider #titlediv .ajax-loading { display: none; float: left; margin: 9px 0 0 5px; visibility: visible; } #slider_blvd #edit_slider #titlediv #add_new_slide { float: left; margin: 5px 0 0 0; } #slider_blvd #edit_slider #slidesort { min-height: 200px; } #slider_blvd #edit_slider .widget-content .pad { min-height: 250px; } #slider_blvd #edit_slider .slide-set-type { background: #f7f7f7; border-bottom: 1px solid #dddddd; height: 40px; } #slider_blvd #edit_slider .slide-set-type strong { float: left; margin: 14px 0 0 10px; } #slider_blvd #edit_slider .slide-set-type select { float: right; margin: 8px 10px 0 0; } #slider_blvd #edit_slider .slide-set-media { float: left; margin: 0 3% 0 0; width: 37%; } #slider_blvd #edit_slider .widget { margin-bottom:10px; } #slider_blvd #optionsframework .widget-content .controls input.upload_button, #slider_blvd #optionsframework .widget-content .controls input.upload { float: none; width: 75px; } #slider_blvd #optionsframework .widget-content .controls input.upload { width: 100%; } #slider_blvd #optionsframework .widget-content .controls textarea { height: 200px; } #slider_blvd #optionsframework .widget-content .controls td textarea { height: 80px; } #slider_blvd #edit_slider .slide-include-elements { border-left: 1px solid #dddddd; float: left; width: 58%; } #slider_blvd #edit_slider .slide-section { padding: 10px 0 10px 20px; } #slider_blvd #optionsframework .screenshot { width: 100%; } #slider_blvd #optionsframework .screenshot img { width: 90%; } #slider_blvd #edit_slider .slide-set-media h3 { margin: 0; padding: 5px; } #slider_blvd #edit_slider .slide-set-media .explain { font-style: italic; color: #666; margin-top: 0; } #slider_blvd #edit_slider .slide-include-elements h4 { margin: 0 0 10px 0; } #slider_blvd #edit_slider .slide-include-elements h5 { font-size: 12px; margin: 0 0 7px 0; } #slider_blvd #edit_slider .slide-include-elements .slide-element-check { width: 15px; text-align: center; vertical-align: middle; } #slider_blvd #edit_slider .slide-include-elements .field { margin: 0 0 7px 0; padding: 5px 10px; } #slider_blvd #edit_slider .slide-include-elements .slide-element-header { background: #f2f2f2; } #slider_blvd #edit_slider .slide-include-elements .slide-element-options { display: none; } #slider_blvd #edit_slider .slide-include-elements .widefat td { vertical-align: middle; } #slider_blvd #optionsframework .widget-content .controls input[type=checkbox] { margin-bottom: 0; }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Rails::Rack::LogTailer</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="../../../css/reset.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../../css/main.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../../css/github.css" type="text/css" media="screen" /> <script src="../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script> <script src="../../../js/main.js" type="text/javascript" charset="utf-8"></script> <script src="../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div class="banner"> <span>Ruby on Rails 4.0.0</span><br /> <h1> <span class="type">Class</span> Rails::Rack::LogTailer <span class="parent">&lt; <a href="../../Object.html">Object</a> </span> </h1> <ul class="files"> <li><a href="../../../files/home/jude/_gem/ruby/2_0_0/gems/railties-4_0_0/lib/rails/rack/log_tailer_rb.html">/home/jude/.gem/ruby/2.0.0/gems/railties-4.0.0/lib/rails/rack/log_tailer.rb</a></li> </ul> </div> <div id="bodyContent"> <div id="content"> <!-- Method ref --> <div class="sectiontitle">Methods</div> <dl class="methods"> <dt>C</dt> <dd> <ul> <li> <a href="#method-i-call">call</a> </li> </ul> </dd> <dt>N</dt> <dd> <ul> <li> <a href="#method-c-new">new</a> </li> </ul> </dd> <dt>T</dt> <dd> <ul> <li> <a href="#method-i-tail-21">tail!</a> </li> </ul> </dd> </dl> <!-- Methods --> <div class="sectiontitle">Class Public methods</div> <div class="method"> <div class="title method-title" id="method-c-new"> <b>new</b>(app, log = nil) <a href="../../../classes/Rails/Rack/LogTailer.html#method-c-new" name="method-c-new" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-c-new_source')" id="l_method-c-new_source">show</a> </p> <div id="method-c-new_source" class="dyn-source"> <pre><span class="ruby-comment"># File /home/jude/.gem/ruby/2.0.0/gems/railties-4.0.0/lib/rails/rack/log_tailer.rb, line 4</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">initialize</span>(<span class="ruby-identifier">app</span>, <span class="ruby-identifier">log</span> = <span class="ruby-keyword">nil</span>) <span class="ruby-ivar">@app</span> = <span class="ruby-identifier">app</span> <span class="ruby-identifier">path</span> = <span class="ruby-constant">Pathname</span>.<span class="ruby-identifier">new</span>(<span class="ruby-identifier">log</span> <span class="ruby-operator">||</span> <span class="ruby-node">&quot;#{::File.expand_path(Rails.root)}/log/#{Rails.env}.log&quot;</span>).<span class="ruby-identifier">cleanpath</span> <span class="ruby-ivar">@cursor</span> = <span class="ruby-ivar">@file</span> = <span class="ruby-keyword">nil</span> <span class="ruby-keyword">if</span> <span class="ruby-operator">::</span><span class="ruby-constant">File</span>.<span class="ruby-identifier">exists?</span>(<span class="ruby-identifier">path</span>) <span class="ruby-ivar">@cursor</span> = <span class="ruby-operator">::</span><span class="ruby-constant">File</span>.<span class="ruby-identifier">size</span>(<span class="ruby-identifier">path</span>) <span class="ruby-ivar">@file</span> = <span class="ruby-operator">::</span><span class="ruby-constant">File</span>.<span class="ruby-identifier">open</span>(<span class="ruby-identifier">path</span>, <span class="ruby-string">&#39;r&#39;</span>) <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="sectiontitle">Instance Public methods</div> <div class="method"> <div class="title method-title" id="method-i-call"> <b>call</b>(env) <a href="../../../classes/Rails/Rack/LogTailer.html#method-i-call" name="method-i-call" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-call_source')" id="l_method-i-call_source">show</a> </p> <div id="method-i-call_source" class="dyn-source"> <pre><span class="ruby-comment"># File /home/jude/.gem/ruby/2.0.0/gems/railties-4.0.0/lib/rails/rack/log_tailer.rb, line 16</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">call</span>(<span class="ruby-identifier">env</span>) <span class="ruby-identifier">response</span> = <span class="ruby-ivar">@app</span>.<span class="ruby-identifier">call</span>(<span class="ruby-identifier">env</span>) <span class="ruby-identifier">tail!</span> <span class="ruby-identifier">response</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="method"> <div class="title method-title" id="method-i-tail-21"> <b>tail!</b>() <a href="../../../classes/Rails/Rack/LogTailer.html#method-i-tail-21" name="method-i-tail-21" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-tail-21_source')" id="l_method-i-tail-21_source">show</a> </p> <div id="method-i-tail-21_source" class="dyn-source"> <pre><span class="ruby-comment"># File /home/jude/.gem/ruby/2.0.0/gems/railties-4.0.0/lib/rails/rack/log_tailer.rb, line 22</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">tail!</span> <span class="ruby-keyword">return</span> <span class="ruby-keyword">unless</span> <span class="ruby-ivar">@cursor</span> <span class="ruby-ivar">@file</span>.<span class="ruby-identifier">seek</span> <span class="ruby-ivar">@cursor</span> <span class="ruby-keyword">unless</span> <span class="ruby-ivar">@file</span>.<span class="ruby-identifier">eof?</span> <span class="ruby-identifier">contents</span> = <span class="ruby-ivar">@file</span>.<span class="ruby-identifier">read</span> <span class="ruby-ivar">@cursor</span> = <span class="ruby-ivar">@file</span>.<span class="ruby-identifier">tell</span> <span class="ruby-identifier">$stdout</span>.<span class="ruby-identifier">print</span> <span class="ruby-identifier">contents</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> </div> </div> </body> </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>R: Wait for a mouse or keyboard event from a graphics window</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="R.css" /> </head><body> <table width="100%" summary="page for getGraphicsEvent {grDevices}"><tr><td>getGraphicsEvent {grDevices}</td><td style="text-align: right;">R Documentation</td></tr></table> <h2>Wait for a mouse or keyboard event from a graphics window</h2> <h3>Description</h3> <p>This function waits for input from a graphics window in the form of a mouse or keyboard event. </p> <h3>Usage</h3> <pre> getGraphicsEvent(prompt = "Waiting for input", onMouseDown = NULL, onMouseMove = NULL, onMouseUp = NULL, onKeybd = NULL, onIdle = NULL, consolePrompt = prompt) setGraphicsEventHandlers(which = dev.cur(), ...) getGraphicsEventEnv(which = dev.cur()) setGraphicsEventEnv(which = dev.cur(), env) </pre> <h3>Arguments</h3> <table summary="R argblock"> <tr valign="top"><td><code>prompt</code></td> <td> <p>prompt to be displayed to the user in the graphics window</p> </td></tr> <tr valign="top"><td><code>onMouseDown</code></td> <td> <p>a function to respond to mouse clicks</p> </td></tr> <tr valign="top"><td><code>onMouseMove</code></td> <td> <p>a function to respond to mouse movement</p> </td></tr> <tr valign="top"><td><code>onMouseUp</code></td> <td> <p>a function to respond to mouse button releases</p> </td></tr> <tr valign="top"><td><code>onKeybd</code></td> <td> <p>a function to respond to key presses</p> </td></tr> <tr valign="top"><td><code>onIdle</code></td> <td> <p>a function to call when no events are pending</p> </td></tr> <tr valign="top"><td><code>consolePrompt</code></td> <td> <p>prompt to be displayed to the user in the console</p> </td></tr> <tr valign="top"><td><code>which</code></td> <td> <p>which graphics device does the call apply to?</p> </td></tr> <tr valign="top"><td><code>...</code></td> <td> <p>items including handlers to be placed in the event environment</p> </td></tr> <tr valign="top"><td><code>env</code></td> <td> <p>an environment to be used as the event environment</p> </td></tr> </table> <h3>Details</h3> <p>These functions allow user input from some graphics devices (currently only the <code>windows()</code>, <code>X11(type = "Xlib")</code> and <code>X11(type = "cairo")</code> screen displays in base <span style="font-family: Courier New, Courier; color: #666666;"><b>R</b></span>). Event handlers may be installed to respond to events involving the mouse or keyboard. </p> <p>The functions are related as follows. If any of the first six arguments to <code>getGraphicsEvent</code> are given, then it uses those in a call to <code>setGraphicsEventHandlers</code> to replace any existing handlers in the current device. This is for compatibility with pre-2.12.0 <span style="font-family: Courier New, Courier; color: #666666;"><b>R</b></span> versions. The current normal way to set up event handlers is to set them using <code>setGraphicsEventHandlers</code> or <code>setGraphicsEventEnv</code> on one or more graphics devices, and then use <code>getGraphicsEvent()</code> with no arguments to retrieve event data. <code>getGraphicsEventEnv()</code> may be used to save the event environment for use later. </p> <p>The names of the arguments in <code>getGraphicsEvent</code> are special. When handling events, the graphics system will look through the event environment for functions named <code>onMouseDown</code>, <code>onMouseMove</code>, <code>onMouseUp</code>, <code>onKeybd</code>, and <code>onIdle</code>, and use them as event handlers. It will use <code>prompt</code> for a label on the graphics device. Two other special names are <code>which</code>, which will identify the graphics device, and <code>result</code>, where the result of the last event handler will be stored before being returned by <code>getGraphicsEvent()</code>. </p> <p>The mouse event handlers should be functions with header <code>function(buttons, x, y)</code>. The coordinates <code>x</code> and <code>y</code> will be passed to mouse event handlers in device independent coordinates (i.e., the lower left corner of the window is <code>(0,0)</code>, the upper right is <code>(1,1)</code>). The <code>buttons</code> argument will be a vector listing the buttons that are pressed at the time of the event, with 0 for left, 1 for middle, and 2 for right. </p> <p>The keyboard event handler should be a function with header <code>function(key)</code>. A single element character vector will be passed to this handler, corresponding to the key press. Shift and other modifier keys will have been processed, so <code>shift-a</code> will be passed as <code>"A"</code>. The following special keys may also be passed to the handler: </p> <ul> <li><p> Control keys, passed as <code>"Ctrl-A"</code>, etc. </p> </li> <li><p> Navigation keys, passed as one of<br /> <code>"Left", "Up", "Right", "Down", "PgUp", "PgDn", "End", "Home"</code> </p> </li> <li><p> Edit keys, passed as one of <code>"Ins", "Del"</code> </p> </li> <li><p> Function keys, passed as one of <code>"F1", "F2", ...</code> </p> </li></ul> <p>The idle event handler <code>onIdle</code> should be a function with no arguments. If the function is undefined or <code>NULL</code>, then R will typically call a system function which (efficiently) waits for the next event to appear on a filehandle. Otherwise, the idle event handler will be called whenever the event queue of the graphics device was found to be empty, i.e. in an infinite loop. This feature is intended to allow animations to respond to user input, and could be CPU-intensive. Currently, <code>onIdle</code> is only implemented for <code>X11()</code> devices. </p> <p>Note that calling <code>Sys.sleep()</code> is not recommended within an idle handler - <code>Sys.sleep()</code> removes pending graphics events in order to allow users to move, close, or resize windows while it is executing. Events such as mouse and keyboard events occurring during <code>Sys.sleep()</code> are lost, and currently do not trigger the event handlers registered via <code>getGraphicsEvent</code> or <code>setGraphicsEventHandlers</code>. </p> <p>The event handlers are standard R functions, and will be executed as though called from the event environment. </p> <p>In an interactive session, events will be processed until </p> <ul> <li><p> one of the event handlers returns a non-<code>NULL</code> value which will be returned as the value of <code>getGraphicsEvent</code>, or </p> </li> <li><p> the user interrupts the function from the console. </p> </li></ul> <h3>Value</h3> <p>When run interactively, <code>getGraphicsEvent</code> returns a non-<code>NULL</code> value returned from one of the event handlers. In a non-interactive session, <code>getGraphicsEvent</code> will return <code>NULL</code> immediately. It will also return <code>NULL</code> if the user closes the last window that has graphics handlers. </p> <p><code>getGraphicsEventEnv</code> returns the current event environment for the graphics device, or <code>NULL</code> if none has been set. </p> <p><code>setGraphicsEventEnv</code> and <code>setGraphicsEventHandlers</code> return the previous event environment for the graphics device. </p> <h3>Author(s)</h3> <p>Duncan Murdoch</p> <h3>Examples</h3> <pre> # This currently only works on the Windows, X11(type = "Xlib"), and # X11(type = "cairo") screen devices... ## Not run: savepar &lt;- par(ask = FALSE) dragplot &lt;- function(..., xlim = NULL, ylim = NULL, xaxs = "r", yaxs = "r") { plot(..., xlim = xlim, ylim = ylim, xaxs = xaxs, yaxs = yaxs) startx &lt;- NULL starty &lt;- NULL prevx &lt;- NULL prevy &lt;- NULL usr &lt;- NULL devset &lt;- function() if (dev.cur() != eventEnv$which) dev.set(eventEnv$which) dragmousedown &lt;- function(buttons, x, y) { startx &lt;&lt;- x starty &lt;&lt;- y prevx &lt;&lt;- 0 prevy &lt;&lt;- 0 devset() usr &lt;&lt;- par("usr") eventEnv$onMouseMove &lt;- dragmousemove NULL } dragmousemove &lt;- function(buttons, x, y) { devset() deltax &lt;- diff(grconvertX(c(startx, x), "ndc", "user")) deltay &lt;- diff(grconvertY(c(starty, y), "ndc", "user")) if (abs(deltax-prevx) + abs(deltay-prevy) &gt; 0) { plot(..., xlim = usr[1:2]-deltax, xaxs = "i", ylim = usr[3:4]-deltay, yaxs = "i") prevx &lt;&lt;- deltax prevy &lt;&lt;- deltay } NULL } mouseup &lt;- function(buttons, x, y) { eventEnv$onMouseMove &lt;- NULL } keydown &lt;- function(key) { if (key == "q") return(invisible(1)) eventEnv$onMouseMove &lt;- NULL NULL } setGraphicsEventHandlers(prompt = "Click and drag, hit q to quit", onMouseDown = dragmousedown, onMouseUp = mouseup, onKeybd = keydown) eventEnv &lt;- getGraphicsEventEnv() } dragplot(rnorm(1000), rnorm(1000)) getGraphicsEvent() par(savepar) ## End(Not run) </pre> <hr /><div style="text-align: center;">[Package <em>grDevices</em> version 3.6.1 <a href="00Index.html">Index</a>]</div> </body></html>
# Copyright (c) 2012 OpenStack Foundation. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import sys import time import mock from oslo_config import cfg from oslo_log import log import oslo_messaging import testtools from neutron.agent.common import ovs_lib from neutron.agent.common import utils from neutron.agent.linux import async_process from neutron.agent.linux import ip_lib from neutron.common import constants as n_const from neutron.plugins.common import constants as p_const from neutron.plugins.ml2.drivers.l2pop import rpc as l2pop_rpc from neutron.plugins.ml2.drivers.openvswitch.agent.common import constants from neutron.plugins.ml2.drivers.openvswitch.agent import ovs_neutron_agent \ as ovs_agent from neutron.tests import base from neutron.tests.unit.plugins.ml2.drivers.openvswitch.agent \ import ovs_test_base NOTIFIER = 'neutron.plugins.ml2.rpc.AgentNotifierApi' OVS_LINUX_KERN_VERS_WITHOUT_VXLAN = "3.12.0" FAKE_MAC = '00:11:22:33:44:55' FAKE_IP1 = '10.0.0.1' FAKE_IP2 = '10.0.0.2' class FakeVif(object): ofport = 99 port_name = 'name' class MockFixedIntervalLoopingCall(object): def __init__(self, f): self.f = f def start(self, interval=0): self.f() class CreateAgentConfigMap(ovs_test_base.OVSAgentConfigTestBase): def test_create_agent_config_map_succeeds(self): self.assertTrue(self.mod_agent.create_agent_config_map(cfg.CONF)) def test_create_agent_config_map_fails_for_invalid_tunnel_config(self): # An ip address is required for tunneling but there is no default, # verify this for both gre and vxlan tunnels. cfg.CONF.set_override('tunnel_types', [p_const.TYPE_GRE], group='AGENT') with testtools.ExpectedException(ValueError): self.mod_agent.create_agent_config_map(cfg.CONF) cfg.CONF.set_override('tunnel_types', [p_const.TYPE_VXLAN], group='AGENT') with testtools.ExpectedException(ValueError): self.mod_agent.create_agent_config_map(cfg.CONF) def test_create_agent_config_map_fails_no_local_ip(self): # An ip address is required for tunneling but there is no default cfg.CONF.set_override('tunnel_types', [p_const.TYPE_VXLAN], group='AGENT') with testtools.ExpectedException(ValueError): self.mod_agent.create_agent_config_map(cfg.CONF) def test_create_agent_config_map_fails_for_invalid_tunnel_type(self): cfg.CONF.set_override('tunnel_types', ['foobar'], group='AGENT') with testtools.ExpectedException(ValueError): self.mod_agent.create_agent_config_map(cfg.CONF) def test_create_agent_config_map_multiple_tunnel_types(self): cfg.CONF.set_override('local_ip', '10.10.10.10', group='OVS') cfg.CONF.set_override('tunnel_types', [p_const.TYPE_GRE, p_const.TYPE_VXLAN], group='AGENT') cfgmap = self.mod_agent.create_agent_config_map(cfg.CONF) self.assertEqual(cfgmap['tunnel_types'], [p_const.TYPE_GRE, p_const.TYPE_VXLAN]) def test_create_agent_config_map_enable_distributed_routing(self): self.addCleanup(cfg.CONF.reset) # Verify setting only enable_tunneling will default tunnel_type to GRE cfg.CONF.set_override('enable_distributed_routing', True, group='AGENT') cfgmap = self.mod_agent.create_agent_config_map(cfg.CONF) self.assertEqual(cfgmap['enable_distributed_routing'], True) class TestOvsNeutronAgent(object): def setUp(self): super(TestOvsNeutronAgent, self).setUp() notifier_p = mock.patch(NOTIFIER) notifier_cls = notifier_p.start() self.notifier = mock.Mock() notifier_cls.return_value = self.notifier cfg.CONF.set_default('firewall_driver', 'neutron.agent.firewall.NoopFirewallDriver', group='SECURITYGROUP') cfg.CONF.set_default('quitting_rpc_timeout', 10, 'AGENT') cfg.CONF.set_default('prevent_arp_spoofing', False, 'AGENT') kwargs = self.mod_agent.create_agent_config_map(cfg.CONF) mock.patch( 'neutron.agent.common.ovs_lib.OVSBridge.get_ports_attributes', return_value=[]).start() with mock.patch.object(self.mod_agent.OVSNeutronAgent, 'setup_integration_br'),\ mock.patch.object(self.mod_agent.OVSNeutronAgent, 'setup_ancillary_bridges', return_value=[]),\ mock.patch('neutron.agent.linux.utils.get_interface_mac', return_value='00:00:00:00:00:01'),\ mock.patch( 'neutron.agent.common.ovs_lib.BaseOVS.get_bridges'),\ mock.patch('oslo_service.loopingcall.FixedIntervalLoopingCall', new=MockFixedIntervalLoopingCall),\ mock.patch( 'neutron.agent.common.ovs_lib.OVSBridge.' 'get_vif_ports', return_value=[]): self.agent = self.mod_agent.OVSNeutronAgent(self._bridge_classes(), **kwargs) # set back to true because initial report state will succeed due # to mocked out RPC calls self.agent.use_call = True self.agent.tun_br = self.br_tun_cls(br_name='br-tun') self.agent.sg_agent = mock.Mock() def _mock_port_bound(self, ofport=None, new_local_vlan=None, old_local_vlan=None): port = mock.Mock() port.ofport = ofport net_uuid = 'my-net-uuid' fixed_ips = [{'subnet_id': 'my-subnet-uuid', 'ip_address': '1.1.1.1'}] if old_local_vlan is not None: self.agent.local_vlan_map[net_uuid] = ( self.mod_agent.LocalVLANMapping( old_local_vlan, None, None, None)) with mock.patch.object(self.agent, 'int_br', autospec=True) as int_br: int_br.db_get_val.return_value = {} int_br.set_db_attribute.return_value = True self.agent.port_bound(port, net_uuid, 'local', None, None, fixed_ips, "compute:None", False) vlan_mapping = {'net_uuid': net_uuid, 'network_type': 'local', 'physical_network': None, 'segmentation_id': None} int_br.set_db_attribute.assert_called_once_with( "Port", mock.ANY, "other_config", vlan_mapping) def _test_restore_local_vlan_maps(self, tag): port = mock.Mock() port.port_name = 'fake_port' local_vlan_map = {'net_uuid': 'fake_network_id', 'network_type': 'vlan', 'physical_network': 'fake_network', 'segmentation_id': 1} with mock.patch.object(self.agent, 'int_br') as int_br, \ mock.patch.object(self.agent, 'provision_local_vlan') as \ provision_local_vlan: int_br.get_vif_ports.return_value = [port] int_br.get_ports_attributes.return_value = [{ 'name': port.port_name, 'other_config': local_vlan_map, 'tag': tag }] self.agent._restore_local_vlan_map() if tag: self.assertTrue(provision_local_vlan.called) else: self.assertFalse(provision_local_vlan.called) def test_datapath_type_system(self): # verify kernel datapath is default expected = constants.OVS_DATAPATH_SYSTEM self.assertEqual(expected, self.agent.int_br.datapath_type) def test_datapath_type_netdev(self): with mock.patch.object(self.mod_agent.OVSNeutronAgent, 'setup_integration_br'), \ mock.patch.object(self.mod_agent.OVSNeutronAgent, 'setup_ancillary_bridges', return_value=[]), \ mock.patch('neutron.agent.linux.utils.get_interface_mac', return_value='00:00:00:00:00:01'), \ mock.patch( 'neutron.agent.common.ovs_lib.BaseOVS.get_bridges'), \ mock.patch('oslo_service.loopingcall.FixedIntervalLoopingCall', new=MockFixedIntervalLoopingCall), \ mock.patch( 'neutron.agent.common.ovs_lib.OVSBridge.' 'get_vif_ports', return_value=[]): # validate setting non default datapath expected = constants.OVS_DATAPATH_NETDEV cfg.CONF.set_override('datapath_type', expected, group='OVS') kwargs = self.mod_agent.create_agent_config_map(cfg.CONF) self.agent = self.mod_agent.OVSNeutronAgent(self._bridge_classes(), **kwargs) self.assertEqual(expected, self.agent.int_br.datapath_type) def test_restore_local_vlan_map_with_device_has_tag(self): self._test_restore_local_vlan_maps(2) def test_restore_local_vlan_map_with_device_no_tag(self): self._test_restore_local_vlan_maps([]) def test_check_agent_configurations_for_dvr_raises(self): self.agent.enable_distributed_routing = True self.agent.enable_tunneling = True self.agent.l2_pop = False self.assertRaises(ValueError, self.agent._check_agent_configurations) def test_check_agent_configurations_for_dvr(self): self.agent.enable_distributed_routing = True self.agent.enable_tunneling = True self.agent.l2_pop = True self.assertIsNone(self.agent._check_agent_configurations()) def test_check_agent_configurations_for_dvr_with_vlan(self): self.agent.enable_distributed_routing = True self.agent.enable_tunneling = False self.agent.l2_pop = False self.assertIsNone(self.agent._check_agent_configurations()) def test_port_bound_deletes_flows_for_valid_ofport(self): self._mock_port_bound(ofport=1, new_local_vlan=1) def test_port_bound_ignores_flows_for_invalid_ofport(self): self._mock_port_bound(ofport=-1, new_local_vlan=1) def test_port_bound_does_not_rewire_if_already_bound(self): self._mock_port_bound(ofport=-1, new_local_vlan=1, old_local_vlan=1) def _test_port_dead(self, cur_tag=None): port = mock.Mock() port.ofport = 1 with mock.patch.object(self.agent, 'int_br') as int_br: int_br.db_get_val.return_value = cur_tag self.agent.port_dead(port) if cur_tag == self.mod_agent.DEAD_VLAN_TAG: self.assertFalse(int_br.set_db_attribute.called) self.assertFalse(int_br.drop_port.called) else: int_br.assert_has_calls([ mock.call.set_db_attribute("Port", mock.ANY, "tag", self.mod_agent.DEAD_VLAN_TAG, log_errors=True), mock.call.drop_port(in_port=port.ofport), ]) def test_port_dead(self): self._test_port_dead() def test_port_dead_with_port_already_dead(self): self._test_port_dead(self.mod_agent.DEAD_VLAN_TAG) def mock_scan_ports(self, vif_port_set=None, registered_ports=None, updated_ports=None, port_tags_dict=None): if port_tags_dict is None: # Because empty dicts evaluate as False. port_tags_dict = {} with mock.patch.object(self.agent.int_br, 'get_vif_port_set', return_value=vif_port_set),\ mock.patch.object(self.agent.int_br, 'get_port_tag_dict', return_value=port_tags_dict): return self.agent.scan_ports(registered_ports, updated_ports) def test_scan_ports_returns_current_only_for_unchanged_ports(self): vif_port_set = set([1, 3]) registered_ports = set([1, 3]) expected = {'current': vif_port_set} actual = self.mock_scan_ports(vif_port_set, registered_ports) self.assertEqual(expected, actual) def test_scan_ports_returns_port_changes(self): vif_port_set = set([1, 3]) registered_ports = set([1, 2]) expected = dict(current=vif_port_set, added=set([3]), removed=set([2])) actual = self.mock_scan_ports(vif_port_set, registered_ports) self.assertEqual(expected, actual) def _test_scan_ports_with_updated_ports(self, updated_ports): vif_port_set = set([1, 3, 4]) registered_ports = set([1, 2, 4]) expected = dict(current=vif_port_set, added=set([3]), removed=set([2]), updated=set([4])) actual = self.mock_scan_ports(vif_port_set, registered_ports, updated_ports) self.assertEqual(expected, actual) def test_scan_ports_finds_known_updated_ports(self): self._test_scan_ports_with_updated_ports(set([4])) def test_scan_ports_ignores_unknown_updated_ports(self): # the port '5' was not seen on current ports. Hence it has either # never been wired or already removed and should be ignored self._test_scan_ports_with_updated_ports(set([4, 5])) def test_scan_ports_ignores_updated_port_if_removed(self): vif_port_set = set([1, 3]) registered_ports = set([1, 2]) updated_ports = set([1, 2]) expected = dict(current=vif_port_set, added=set([3]), removed=set([2]), updated=set([1])) actual = self.mock_scan_ports(vif_port_set, registered_ports, updated_ports) self.assertEqual(expected, actual) def test_scan_ports_no_vif_changes_returns_updated_port_only(self): vif_port_set = set([1, 2, 3]) registered_ports = set([1, 2, 3]) updated_ports = set([2]) expected = dict(current=vif_port_set, updated=set([2])) actual = self.mock_scan_ports(vif_port_set, registered_ports, updated_ports) self.assertEqual(expected, actual) def test_update_ports_returns_changed_vlan(self): br = self.br_int_cls('br-int') mac = "ca:fe:de:ad:be:ef" port = ovs_lib.VifPort(1, 1, 1, mac, br) lvm = self.mod_agent.LocalVLANMapping( 1, '1', None, 1, {port.vif_id: port}) local_vlan_map = {'1': lvm} vif_port_set = set([1, 3]) registered_ports = set([1, 2]) port_tags_dict = {1: []} expected = dict( added=set([3]), current=vif_port_set, removed=set([2]), updated=set([1]) ) with mock.patch.dict(self.agent.local_vlan_map, local_vlan_map),\ mock.patch.object(self.agent, 'tun_br', autospec=True): actual = self.mock_scan_ports( vif_port_set, registered_ports, port_tags_dict=port_tags_dict) self.assertEqual(expected, actual) def test_bind_devices(self): devices_up = ['tap1'] devices_down = ['tap2'] self.agent.local_vlan_map["net1"] = mock.Mock() port_details = [ {'network_id': 'net1', 'vif_port': mock.Mock(), 'device': devices_up[0], 'admin_state_up': True}, {'network_id': 'net1', 'vif_port': mock.Mock(), 'device': devices_down[0], 'admin_state_up': False}] with mock.patch.object( self.agent.plugin_rpc, 'update_device_list', return_value={'devices_up': devices_up, 'devices_down': devices_down, 'failed_devices_up': [], 'failed_devices_down': []}) as update_devices, \ mock.patch.object(self.agent, 'int_br') as int_br: int_br.db_list.return_value = [] self.agent._bind_devices(port_details) update_devices.assert_called_once_with(mock.ANY, devices_up, devices_down, mock.ANY, mock.ANY) def _test_arp_spoofing(self, enable_prevent_arp_spoofing): self.agent.prevent_arp_spoofing = enable_prevent_arp_spoofing ovs_db_list = [{'name': 'fake_device', 'tag': []}] self.agent.local_vlan_map = { 'fake_network': ovs_agent.LocalVLANMapping(1, None, None, 1)} vif_port = mock.Mock() vif_port.port_name = 'fake_device' vif_port.ofport = 1 need_binding_ports = [{'network_id': 'fake_network', 'vif_port': vif_port, 'device': 'fake_device', 'admin_state_up': True}] with mock.patch.object( self.agent.plugin_rpc, 'update_device_list', return_value={'devices_up': [], 'devices_down': [], 'failed_devices_up': [], 'failed_devices_down': []}), \ mock.patch.object(self.agent, 'int_br') as int_br, \ mock.patch.object( self.agent, 'setup_arp_spoofing_protection') as setup_arp: int_br.db_list.return_value = ovs_db_list self.agent._bind_devices(need_binding_ports) self.assertEqual(enable_prevent_arp_spoofing, setup_arp.called) def test_setup_arp_spoofing_protection_enable(self): self._test_arp_spoofing(True) def test_setup_arp_spoofing_protection_disabled(self): self._test_arp_spoofing(False) def _mock_treat_devices_added_updated(self, details, port, func_name): """Mock treat devices added or updated. :param details: the details to return for the device :param port: the port that get_vif_port_by_id should return :param func_name: the function that should be called :returns: whether the named function was called """ with mock.patch.object(self.agent.plugin_rpc, 'get_devices_details_list_and_failed_devices', return_value={'devices': [details], 'failed_devices': None}),\ mock.patch.object(self.agent.int_br, 'get_vifs_by_ids', return_value={details['device']: port}),\ mock.patch.object(self.agent.plugin_rpc, 'update_device_list', return_value={'devices_up': [], 'devices_down': details, 'failed_devices_up': [], 'failed_devices_down': []}),\ mock.patch.object(self.agent.int_br, 'get_port_tag_dict', return_value={}),\ mock.patch.object(self.agent, func_name) as func: skip_devs, need_bound_devices, insecure_ports = ( self.agent.treat_devices_added_or_updated([{}], False)) # The function should not raise self.assertFalse(skip_devs) return func.called def test_treat_devices_added_updated_ignores_invalid_ofport(self): port = mock.Mock() port.ofport = -1 self.assertFalse(self._mock_treat_devices_added_updated( mock.MagicMock(), port, 'port_dead')) def test_treat_devices_added_updated_marks_unknown_port_as_dead(self): port = mock.Mock() port.ofport = 1 self.assertTrue(self._mock_treat_devices_added_updated( mock.MagicMock(), port, 'port_dead')) def test_treat_devices_added_does_not_process_missing_port(self): with mock.patch.object( self.agent.plugin_rpc, 'get_devices_details_list_and_failed_devices') as get_dev_fn,\ mock.patch.object(self.agent.int_br, 'get_vif_port_by_id', return_value=None): self.assertFalse(get_dev_fn.called) def test_treat_devices_added_updated_updates_known_port(self): details = mock.MagicMock() details.__contains__.side_effect = lambda x: True self.assertTrue(self._mock_treat_devices_added_updated( details, mock.Mock(), 'treat_vif_port')) def test_treat_devices_added_updated_sends_vif_port_into_extension_manager( self, *args): details = mock.MagicMock() details.__contains__.side_effect = lambda x: True port = mock.MagicMock() def fake_handle_port(context, port): self.assertIn('vif_port', port) with mock.patch.object(self.agent.plugin_rpc, 'get_devices_details_list_and_failed_devices', return_value={'devices': [details], 'failed_devices': None}),\ mock.patch.object(self.agent.ext_manager, 'handle_port', new=fake_handle_port),\ mock.patch.object(self.agent.int_br, 'get_vifs_by_ids', return_value={details['device']: port}),\ mock.patch.object(self.agent, 'treat_vif_port', return_value=False): self.agent.treat_devices_added_or_updated([{}], False) def test_treat_devices_added_updated_skips_if_port_not_found(self): dev_mock = mock.MagicMock() dev_mock.__getitem__.return_value = 'the_skipped_one' with mock.patch.object(self.agent.plugin_rpc, 'get_devices_details_list_and_failed_devices', return_value={'devices': [dev_mock], 'failed_devices': None}),\ mock.patch.object(self.agent.int_br, 'get_port_tag_dict', return_value={}),\ mock.patch.object(self.agent.int_br, 'get_vifs_by_ids', return_value={}),\ mock.patch.object(self.agent, 'treat_vif_port') as treat_vif_port: skip_devs = self.agent.treat_devices_added_or_updated([{}], False) # The function should return False for resync and no device # processed self.assertEqual((['the_skipped_one'], [], []), skip_devs) self.assertFalse(treat_vif_port.called) def test_treat_devices_added_updated_put_port_down(self): fake_details_dict = {'admin_state_up': False, 'port_id': 'xxx', 'device': 'xxx', 'network_id': 'yyy', 'physical_network': 'foo', 'segmentation_id': 'bar', 'network_type': 'baz', 'fixed_ips': [{'subnet_id': 'my-subnet-uuid', 'ip_address': '1.1.1.1'}], 'device_owner': 'compute:None', 'port_security_enabled': True } with mock.patch.object(self.agent.plugin_rpc, 'get_devices_details_list_and_failed_devices', return_value={'devices': [fake_details_dict], 'failed_devices': None}),\ mock.patch.object(self.agent.int_br, 'get_vifs_by_ids', return_value={'xxx': mock.MagicMock()}),\ mock.patch.object(self.agent.int_br, 'get_port_tag_dict', return_value={}),\ mock.patch.object(self.agent, 'treat_vif_port') as treat_vif_port: skip_devs, need_bound_devices, insecure_ports = ( self.agent.treat_devices_added_or_updated([{}], False)) # The function should return False for resync self.assertFalse(skip_devs) self.assertTrue(treat_vif_port.called) def _mock_treat_devices_removed(self, port_exists): details = dict(exists=port_exists) with mock.patch.object(self.agent.plugin_rpc, 'update_device_list', return_value={'devices_up': [], 'devices_down': details, 'failed_devices_up': [], 'failed_devices_down': []}): with mock.patch.object(self.agent, 'port_unbound') as port_unbound: self.assertFalse(self.agent.treat_devices_removed([{}])) self.assertTrue(port_unbound.called) def test_treat_devices_removed_unbinds_port(self): self._mock_treat_devices_removed(True) def test_treat_devices_removed_ignores_missing_port(self): self._mock_treat_devices_removed(False) def test_bind_port_with_missing_network(self): vif_port = mock.Mock() vif_port.name.return_value = 'port' self.agent._bind_devices([{'network_id': 'non-existent', 'vif_port': vif_port}]) def _test_process_network_ports(self, port_info): with mock.patch.object(self.agent.sg_agent, "setup_port_filters") as setup_port_filters,\ mock.patch.object( self.agent, "treat_devices_added_or_updated", return_value=([], [], [])) as device_added_updated,\ mock.patch.object(self.agent.int_br, "get_ports_attributes", return_value=[]),\ mock.patch.object(self.agent, "treat_devices_removed", return_value=False) as device_removed: self.assertFalse(self.agent.process_network_ports(port_info, False)) setup_port_filters.assert_called_once_with( port_info.get('added', set()), port_info.get('updated', set())) devices_added_updated = (port_info.get('added', set()) | port_info.get('updated', set())) if devices_added_updated: device_added_updated.assert_called_once_with( devices_added_updated, False) if port_info.get('removed', set()): device_removed.assert_called_once_with(port_info['removed']) def test_process_network_ports(self): self._test_process_network_ports( {'current': set(['tap0']), 'removed': set(['eth0']), 'added': set(['eth1'])}) def test_process_network_port_with_updated_ports(self): self._test_process_network_ports( {'current': set(['tap0', 'tap1']), 'updated': set(['tap1', 'eth1']), 'removed': set(['eth0']), 'added': set(['eth1'])}) def test_process_network_port_with_empty_port(self): self._test_process_network_ports({}) def test_process_network_ports_with_insecure_ports(self): port_info = {'current': set(['tap0', 'tap1']), 'updated': set(['tap1']), 'removed': set([]), 'added': set(['eth1'])} with mock.patch.object(self.agent.sg_agent, "setup_port_filters") as setup_port_filters,\ mock.patch.object( self.agent, "treat_devices_added_or_updated", return_value=([], [], ['eth1'])) as device_added_updated: self.assertFalse(self.agent.process_network_ports(port_info, False)) device_added_updated.assert_called_once_with( set(['eth1', 'tap1']), False) setup_port_filters.assert_called_once_with( set(), port_info.get('updated', set())) def test_report_state(self): with mock.patch.object(self.agent.state_rpc, "report_state") as report_st: self.agent.int_br_device_count = 5 self.agent._report_state() report_st.assert_called_with(self.agent.context, self.agent.agent_state, True) self.assertNotIn("start_flag", self.agent.agent_state) self.assertFalse(self.agent.use_call) self.assertEqual( self.agent.agent_state["configurations"]["devices"], self.agent.int_br_device_count ) self.agent._report_state() report_st.assert_called_with(self.agent.context, self.agent.agent_state, False) def test_report_state_fail(self): with mock.patch.object(self.agent.state_rpc, "report_state") as report_st: report_st.side_effect = Exception() self.agent._report_state() report_st.assert_called_with(self.agent.context, self.agent.agent_state, True) self.agent._report_state() report_st.assert_called_with(self.agent.context, self.agent.agent_state, True) def test_port_update(self): port = {"id": "123", "network_id": "124", "admin_state_up": False} self.agent.port_update("unused_context", port=port, network_type="vlan", segmentation_id="1", physical_network="physnet") self.assertEqual(set(['123']), self.agent.updated_ports) def test_port_delete(self): vif = FakeVif() with mock.patch.object(self.agent, 'int_br') as int_br: int_br.get_vif_by_port_id.return_value = vif.port_name int_br.get_vif_port_by_id.return_value = vif self.agent.port_delete("unused_context", port_id='id') self.agent.process_deleted_ports(port_info={}) # the main things we care about are that it gets put in the # dead vlan and gets blocked int_br.set_db_attribute.assert_any_call( 'Port', vif.port_name, 'tag', self.mod_agent.DEAD_VLAN_TAG, log_errors=False) int_br.drop_port.assert_called_once_with(in_port=vif.ofport) def test_port_delete_removed_port(self): with mock.patch.object(self.agent, 'int_br') as int_br: self.agent.port_delete("unused_context", port_id='id') # if it was removed from the bridge, we shouldn't be processing it self.agent.process_deleted_ports(port_info={'removed': {'id', }}) self.assertFalse(int_br.set_db_attribute.called) self.assertFalse(int_br.drop_port.called) def test_setup_physical_bridges(self): with mock.patch.object(ip_lib, "device_exists") as devex_fn,\ mock.patch.object(sys, "exit"),\ mock.patch.object(utils, "execute"),\ mock.patch.object(self.agent, 'br_phys_cls') as phys_br_cls,\ mock.patch.object(self.agent, 'int_br') as int_br: devex_fn.return_value = True parent = mock.MagicMock() phys_br = phys_br_cls() parent.attach_mock(phys_br_cls, 'phys_br_cls') parent.attach_mock(phys_br, 'phys_br') parent.attach_mock(int_br, 'int_br') phys_br.add_patch_port.return_value = "phy_ofport" int_br.add_patch_port.return_value = "int_ofport" self.agent.setup_physical_bridges({"physnet1": "br-eth"}) expected_calls = [ mock.call.phys_br_cls('br-eth'), mock.call.phys_br.setup_controllers(mock.ANY), mock.call.phys_br.setup_default_table(), mock.call.int_br.db_get_val('Interface', 'int-br-eth', 'type'), # Have to use __getattr__ here to avoid mock._Call.__eq__ # method being called mock.call.int_br.db_get_val().__getattr__('__eq__')('veth'), mock.call.int_br.add_patch_port('int-br-eth', constants.NONEXISTENT_PEER), mock.call.phys_br.add_patch_port('phy-br-eth', constants.NONEXISTENT_PEER), mock.call.int_br.drop_port(in_port='int_ofport'), mock.call.phys_br.drop_port(in_port='phy_ofport'), mock.call.int_br.set_db_attribute('Interface', 'int-br-eth', 'options:peer', 'phy-br-eth'), mock.call.phys_br.set_db_attribute('Interface', 'phy-br-eth', 'options:peer', 'int-br-eth'), ] parent.assert_has_calls(expected_calls) self.assertEqual(self.agent.int_ofports["physnet1"], "int_ofport") self.assertEqual(self.agent.phys_ofports["physnet1"], "phy_ofport") def test_setup_physical_bridges_using_veth_interconnection(self): self.agent.use_veth_interconnection = True with mock.patch.object(ip_lib, "device_exists") as devex_fn,\ mock.patch.object(sys, "exit"),\ mock.patch.object(utils, "execute") as utilsexec_fn,\ mock.patch.object(self.agent, 'br_phys_cls') as phys_br_cls,\ mock.patch.object(self.agent, 'int_br') as int_br,\ mock.patch.object(ip_lib.IPWrapper, "add_veth") as addveth_fn,\ mock.patch.object(ip_lib.IpLinkCommand, "delete") as linkdel_fn,\ mock.patch.object(ip_lib.IpLinkCommand, "set_up"),\ mock.patch.object(ip_lib.IpLinkCommand, "set_mtu"),\ mock.patch.object(ovs_lib.BaseOVS, "get_bridges") as get_br_fn: devex_fn.return_value = True parent = mock.MagicMock() parent.attach_mock(utilsexec_fn, 'utils_execute') parent.attach_mock(linkdel_fn, 'link_delete') parent.attach_mock(addveth_fn, 'add_veth') addveth_fn.return_value = (ip_lib.IPDevice("int-br-eth1"), ip_lib.IPDevice("phy-br-eth1")) phys_br = phys_br_cls() phys_br.add_port.return_value = "phys_veth_ofport" int_br.add_port.return_value = "int_veth_ofport" get_br_fn.return_value = ["br-eth"] self.agent.setup_physical_bridges({"physnet1": "br-eth"}) expected_calls = [mock.call.link_delete(), mock.call.utils_execute(['udevadm', 'settle', '--timeout=10']), mock.call.add_veth('int-br-eth', 'phy-br-eth')] parent.assert_has_calls(expected_calls, any_order=False) self.assertEqual(self.agent.int_ofports["physnet1"], "int_veth_ofport") self.assertEqual(self.agent.phys_ofports["physnet1"], "phys_veth_ofport") def test_setup_physical_bridges_change_from_veth_to_patch_conf(self): with mock.patch.object(sys, "exit"),\ mock.patch.object(utils, "execute"),\ mock.patch.object(self.agent, 'br_phys_cls') as phys_br_cls,\ mock.patch.object(self.agent, 'int_br') as int_br,\ mock.patch.object(self.agent.int_br, 'db_get_val', return_value='veth'): phys_br = phys_br_cls() parent = mock.MagicMock() parent.attach_mock(phys_br_cls, 'phys_br_cls') parent.attach_mock(phys_br, 'phys_br') parent.attach_mock(int_br, 'int_br') phys_br.add_patch_port.return_value = "phy_ofport" int_br.add_patch_port.return_value = "int_ofport" self.agent.setup_physical_bridges({"physnet1": "br-eth"}) expected_calls = [ mock.call.phys_br_cls('br-eth'), mock.call.phys_br.setup_controllers(mock.ANY), mock.call.phys_br.setup_default_table(), mock.call.int_br.delete_port('int-br-eth'), mock.call.phys_br.delete_port('phy-br-eth'), mock.call.int_br.add_patch_port('int-br-eth', constants.NONEXISTENT_PEER), mock.call.phys_br.add_patch_port('phy-br-eth', constants.NONEXISTENT_PEER), mock.call.int_br.drop_port(in_port='int_ofport'), mock.call.phys_br.drop_port(in_port='phy_ofport'), mock.call.int_br.set_db_attribute('Interface', 'int-br-eth', 'options:peer', 'phy-br-eth'), mock.call.phys_br.set_db_attribute('Interface', 'phy-br-eth', 'options:peer', 'int-br-eth'), ] parent.assert_has_calls(expected_calls) self.assertEqual(self.agent.int_ofports["physnet1"], "int_ofport") self.assertEqual(self.agent.phys_ofports["physnet1"], "phy_ofport") def test_get_peer_name(self): bridge1 = "A_REALLY_LONG_BRIDGE_NAME1" bridge2 = "A_REALLY_LONG_BRIDGE_NAME2" self.agent.use_veth_interconnection = True self.assertEqual(len(self.agent.get_peer_name('int-', bridge1)), n_const.DEVICE_NAME_MAX_LEN) self.assertEqual(len(self.agent.get_peer_name('int-', bridge2)), n_const.DEVICE_NAME_MAX_LEN) self.assertNotEqual(self.agent.get_peer_name('int-', bridge1), self.agent.get_peer_name('int-', bridge2)) def test_setup_tunnel_br(self): self.tun_br = mock.Mock() with mock.patch.object(self.agent.int_br, "add_patch_port", return_value=1) as int_patch_port,\ mock.patch.object(self.agent.tun_br, "add_patch_port", return_value=1) as tun_patch_port,\ mock.patch.object(self.agent.tun_br, 'bridge_exists', return_value=False),\ mock.patch.object(self.agent.tun_br, 'create') as create_tun,\ mock.patch.object(self.agent.tun_br, 'setup_controllers') as setup_controllers,\ mock.patch.object(self.agent.tun_br, 'port_exists', return_value=False),\ mock.patch.object(self.agent.int_br, 'port_exists', return_value=False),\ mock.patch.object(sys, "exit"): self.agent.setup_tunnel_br(None) self.agent.setup_tunnel_br() self.assertTrue(create_tun.called) self.assertTrue(setup_controllers.called) self.assertTrue(int_patch_port.called) self.assertTrue(tun_patch_port.called) def test_setup_tunnel_br_ports_exits_drop_flows(self): cfg.CONF.set_override('drop_flows_on_start', True, 'AGENT') with mock.patch.object(self.agent.tun_br, 'port_exists', return_value=True),\ mock.patch.object(self.agent, 'tun_br'),\ mock.patch.object(self.agent.int_br, 'port_exists', return_value=True),\ mock.patch.object(self.agent.tun_br, 'setup_controllers'),\ mock.patch.object(self.agent, 'patch_tun_ofport', new=2),\ mock.patch.object(self.agent, 'patch_int_ofport', new=2),\ mock.patch.object(self.agent.tun_br, 'delete_flows') as delete,\ mock.patch.object(self.agent.int_br, "add_patch_port") as int_patch_port,\ mock.patch.object(self.agent.tun_br, "add_patch_port") as tun_patch_port,\ mock.patch.object(sys, "exit"): self.agent.setup_tunnel_br(None) self.agent.setup_tunnel_br() self.assertFalse(int_patch_port.called) self.assertFalse(tun_patch_port.called) self.assertTrue(delete.called) def test_setup_tunnel_port(self): self.agent.tun_br = mock.Mock() self.agent.l2_pop = False self.agent.udp_vxlan_port = 8472 self.agent.tun_br_ofports['vxlan'] = {} with mock.patch.object(self.agent.tun_br, "add_tunnel_port", return_value='6') as add_tun_port_fn,\ mock.patch.object(self.agent.tun_br, "add_flow"): self.agent._setup_tunnel_port(self.agent.tun_br, 'portname', '1.2.3.4', 'vxlan') self.assertTrue(add_tun_port_fn.called) def test_port_unbound(self): with mock.patch.object(self.agent, "reclaim_local_vlan") as reclvl_fn: self.agent.enable_tunneling = True lvm = mock.Mock() lvm.network_type = "gre" lvm.vif_ports = {"vif1": mock.Mock()} self.agent.local_vlan_map["netuid12345"] = lvm self.agent.port_unbound("vif1", "netuid12345") self.assertTrue(reclvl_fn.called) lvm.vif_ports = {} self.agent.port_unbound("vif1", "netuid12345") self.assertEqual(reclvl_fn.call_count, 2) lvm.vif_ports = {"vif1": mock.Mock()} self.agent.port_unbound("vif3", "netuid12345") self.assertEqual(reclvl_fn.call_count, 2) def _prepare_l2_pop_ofports(self): lvm1 = mock.Mock() lvm1.network_type = 'gre' lvm1.vlan = 'vlan1' lvm1.segmentation_id = 'seg1' lvm1.tun_ofports = set(['1']) lvm2 = mock.Mock() lvm2.network_type = 'gre' lvm2.vlan = 'vlan2' lvm2.segmentation_id = 'seg2' lvm2.tun_ofports = set(['1', '2']) self.agent.local_vlan_map = {'net1': lvm1, 'net2': lvm2} self.agent.tun_br_ofports = {'gre': {'1.1.1.1': '1', '2.2.2.2': '2'}} self.agent.arp_responder_enabled = True def test_fdb_ignore_network(self): self._prepare_l2_pop_ofports() fdb_entry = {'net3': {}} with mock.patch.object(self.agent.tun_br, 'add_flow') as add_flow_fn,\ mock.patch.object(self.agent.tun_br, 'delete_flows') as del_flow_fn,\ mock.patch.object(self.agent, '_setup_tunnel_port') as add_tun_fn,\ mock.patch.object(self.agent, 'cleanup_tunnel_port') as clean_tun_fn: self.agent.fdb_add(None, fdb_entry) self.assertFalse(add_flow_fn.called) self.assertFalse(add_tun_fn.called) self.agent.fdb_remove(None, fdb_entry) self.assertFalse(del_flow_fn.called) self.assertFalse(clean_tun_fn.called) def test_fdb_ignore_self(self): self._prepare_l2_pop_ofports() self.agent.local_ip = 'agent_ip' fdb_entry = {'net2': {'network_type': 'gre', 'segment_id': 'tun2', 'ports': {'agent_ip': [l2pop_rpc.PortInfo(FAKE_MAC, FAKE_IP1), n_const.FLOODING_ENTRY]}}} with mock.patch.object(self.agent.tun_br, "deferred") as defer_fn: self.agent.fdb_add(None, fdb_entry) self.assertFalse(defer_fn.called) self.agent.fdb_remove(None, fdb_entry) self.assertFalse(defer_fn.called) def test_fdb_add_flows(self): self._prepare_l2_pop_ofports() fdb_entry = {'net1': {'network_type': 'gre', 'segment_id': 'tun1', 'ports': {'2.2.2.2': [l2pop_rpc.PortInfo(FAKE_MAC, FAKE_IP1), n_const.FLOODING_ENTRY]}}} with mock.patch.object(self.agent, 'tun_br', autospec=True) as tun_br,\ mock.patch.object(self.agent, '_setup_tunnel_port', autospec=True) as add_tun_fn: self.agent.fdb_add(None, fdb_entry) self.assertFalse(add_tun_fn.called) deferred_br_call = mock.call.deferred().__enter__() expected_calls = [ deferred_br_call.install_arp_responder('vlan1', FAKE_IP1, FAKE_MAC), deferred_br_call.install_unicast_to_tun('vlan1', 'seg1', '2', FAKE_MAC), deferred_br_call.install_flood_to_tun('vlan1', 'seg1', set(['1', '2'])), ] tun_br.assert_has_calls(expected_calls) def test_fdb_del_flows(self): self._prepare_l2_pop_ofports() fdb_entry = {'net2': {'network_type': 'gre', 'segment_id': 'tun2', 'ports': {'2.2.2.2': [l2pop_rpc.PortInfo(FAKE_MAC, FAKE_IP1), n_const.FLOODING_ENTRY]}}} with mock.patch.object(self.agent, 'tun_br', autospec=True) as br_tun: self.agent.fdb_remove(None, fdb_entry) deferred_br_call = mock.call.deferred().__enter__() expected_calls = [ mock.call.deferred(), mock.call.deferred().__enter__(), deferred_br_call.delete_arp_responder('vlan2', FAKE_IP1), deferred_br_call.delete_unicast_to_tun('vlan2', FAKE_MAC), deferred_br_call.install_flood_to_tun('vlan2', 'seg2', set(['1'])), deferred_br_call.delete_port('gre-02020202'), deferred_br_call.cleanup_tunnel_port('2'), mock.call.deferred().__exit__(None, None, None), ] br_tun.assert_has_calls(expected_calls) def test_fdb_add_port(self): self._prepare_l2_pop_ofports() fdb_entry = {'net1': {'network_type': 'gre', 'segment_id': 'tun1', 'ports': {'1.1.1.1': [l2pop_rpc.PortInfo(FAKE_MAC, FAKE_IP1)]}}} with mock.patch.object(self.agent, 'tun_br', autospec=True) as tun_br,\ mock.patch.object(self.agent, '_setup_tunnel_port') as add_tun_fn: self.agent.fdb_add(None, fdb_entry) self.assertFalse(add_tun_fn.called) fdb_entry['net1']['ports']['10.10.10.10'] = [ l2pop_rpc.PortInfo(FAKE_MAC, FAKE_IP1)] self.agent.fdb_add(None, fdb_entry) deferred_br = tun_br.deferred().__enter__() add_tun_fn.assert_called_with( deferred_br, 'gre-0a0a0a0a', '10.10.10.10', 'gre') def test_fdb_del_port(self): self._prepare_l2_pop_ofports() fdb_entry = {'net2': {'network_type': 'gre', 'segment_id': 'tun2', 'ports': {'2.2.2.2': [n_const.FLOODING_ENTRY]}}} with mock.patch.object(self.agent.tun_br, 'deferred') as defer_fn,\ mock.patch.object(self.agent.tun_br, 'delete_port') as delete_port_fn: self.agent.fdb_remove(None, fdb_entry) deferred_br = defer_fn().__enter__() deferred_br.delete_port.assert_called_once_with('gre-02020202') self.assertFalse(delete_port_fn.called) def test_fdb_update_chg_ip(self): self._prepare_l2_pop_ofports() fdb_entries = {'chg_ip': {'net1': {'agent_ip': {'before': [l2pop_rpc.PortInfo(FAKE_MAC, FAKE_IP1)], 'after': [l2pop_rpc.PortInfo(FAKE_MAC, FAKE_IP2)]}}}} with mock.patch.object(self.agent.tun_br, 'deferred') as deferred_fn: self.agent.fdb_update(None, fdb_entries) deferred_br = deferred_fn().__enter__() deferred_br.assert_has_calls([ mock.call.install_arp_responder('vlan1', FAKE_IP2, FAKE_MAC), mock.call.delete_arp_responder('vlan1', FAKE_IP1) ]) def test_del_fdb_flow_idempotency(self): lvm = mock.Mock() lvm.network_type = 'gre' lvm.vlan = 'vlan1' lvm.segmentation_id = 'seg1' lvm.tun_ofports = set(['1', '2']) with mock.patch.object(self.agent.tun_br, 'mod_flow') as mod_flow_fn,\ mock.patch.object(self.agent.tun_br, 'delete_flows') as delete_flows_fn: self.agent.del_fdb_flow(self.agent.tun_br, n_const.FLOODING_ENTRY, '1.1.1.1', lvm, '3') self.assertFalse(mod_flow_fn.called) self.assertFalse(delete_flows_fn.called) def test_recl_lv_port_to_preserve(self): self._prepare_l2_pop_ofports() self.agent.l2_pop = True self.agent.enable_tunneling = True with mock.patch.object(self.agent, 'tun_br', autospec=True) as tun_br: self.agent.reclaim_local_vlan('net1') self.assertFalse(tun_br.cleanup_tunnel_port.called) def test_recl_lv_port_to_remove(self): self._prepare_l2_pop_ofports() self.agent.l2_pop = True self.agent.enable_tunneling = True with mock.patch.object(self.agent, 'tun_br', autospec=True) as tun_br: self.agent.reclaim_local_vlan('net2') tun_br.delete_port.assert_called_once_with('gre-02020202') def test_daemon_loop_uses_polling_manager(self): with mock.patch( 'neutron.agent.common.polling.get_polling_manager') as mock_get_pm: with mock.patch.object(self.agent, 'rpc_loop') as mock_loop: self.agent.daemon_loop() mock_get_pm.assert_called_with(True, constants.DEFAULT_OVSDBMON_RESPAWN) mock_loop.assert_called_once_with(polling_manager=mock.ANY) def test_setup_tunnel_port_invalid_ofport(self): with mock.patch.object( self.agent.tun_br, 'add_tunnel_port', return_value=ovs_lib.INVALID_OFPORT) as add_tunnel_port_fn,\ mock.patch.object(self.mod_agent.LOG, 'error') as log_error_fn: ofport = self.agent._setup_tunnel_port( self.agent.tun_br, 'gre-1', 'remote_ip', p_const.TYPE_GRE) add_tunnel_port_fn.assert_called_once_with( 'gre-1', 'remote_ip', self.agent.local_ip, p_const.TYPE_GRE, self.agent.vxlan_udp_port, self.agent.dont_fragment) log_error_fn.assert_called_once_with( _("Failed to set-up %(type)s tunnel port to %(ip)s"), {'type': p_const.TYPE_GRE, 'ip': 'remote_ip'}) self.assertEqual(ofport, 0) def test_setup_tunnel_port_error_negative_df_disabled(self): with mock.patch.object( self.agent.tun_br, 'add_tunnel_port', return_value=ovs_lib.INVALID_OFPORT) as add_tunnel_port_fn,\ mock.patch.object(self.mod_agent.LOG, 'error') as log_error_fn: self.agent.dont_fragment = False ofport = self.agent._setup_tunnel_port( self.agent.tun_br, 'gre-1', 'remote_ip', p_const.TYPE_GRE) add_tunnel_port_fn.assert_called_once_with( 'gre-1', 'remote_ip', self.agent.local_ip, p_const.TYPE_GRE, self.agent.vxlan_udp_port, self.agent.dont_fragment) log_error_fn.assert_called_once_with( _("Failed to set-up %(type)s tunnel port to %(ip)s"), {'type': p_const.TYPE_GRE, 'ip': 'remote_ip'}) self.assertEqual(ofport, 0) def test_tunnel_sync_with_ml2_plugin(self): fake_tunnel_details = {'tunnels': [{'ip_address': '100.101.31.15'}]} with mock.patch.object(self.agent.plugin_rpc, 'tunnel_sync', return_value=fake_tunnel_details),\ mock.patch.object( self.agent, '_setup_tunnel_port') as _setup_tunnel_port_fn,\ mock.patch.object(self.agent, 'cleanup_stale_flows') as cleanup: self.agent.tunnel_types = ['vxlan'] self.agent.tunnel_sync() expected_calls = [mock.call(self.agent.tun_br, 'vxlan-64651f0f', '100.101.31.15', 'vxlan')] _setup_tunnel_port_fn.assert_has_calls(expected_calls) self.assertEqual([], cleanup.mock_calls) def test_tunnel_sync_invalid_ip_address(self): fake_tunnel_details = {'tunnels': [{'ip_address': '300.300.300.300'}, {'ip_address': '100.100.100.100'}]} with mock.patch.object(self.agent.plugin_rpc, 'tunnel_sync', return_value=fake_tunnel_details),\ mock.patch.object( self.agent, '_setup_tunnel_port') as _setup_tunnel_port_fn,\ mock.patch.object(self.agent, 'cleanup_stale_flows') as cleanup: self.agent.tunnel_types = ['vxlan'] self.agent.tunnel_sync() _setup_tunnel_port_fn.assert_called_once_with(self.agent.tun_br, 'vxlan-64646464', '100.100.100.100', 'vxlan') self.assertEqual([], cleanup.mock_calls) def test_tunnel_update(self): kwargs = {'tunnel_ip': '10.10.10.10', 'tunnel_type': 'gre'} self.agent._setup_tunnel_port = mock.Mock() self.agent.enable_tunneling = True self.agent.tunnel_types = ['gre'] self.agent.l2_pop = False self.agent.tunnel_update(context=None, **kwargs) expected_calls = [ mock.call(self.agent.tun_br, 'gre-0a0a0a0a', '10.10.10.10', 'gre')] self.agent._setup_tunnel_port.assert_has_calls(expected_calls) def test_tunnel_delete(self): kwargs = {'tunnel_ip': '10.10.10.10', 'tunnel_type': 'gre'} self.agent.enable_tunneling = True self.agent.tunnel_types = ['gre'] self.agent.tun_br_ofports = {'gre': {'10.10.10.10': '1'}} with mock.patch.object( self.agent, 'cleanup_tunnel_port' ) as clean_tun_fn: self.agent.tunnel_delete(context=None, **kwargs) self.assertTrue(clean_tun_fn.called) def _test_ovs_status(self, *args): reply2 = {'current': set(['tap0']), 'added': set(['tap2']), 'removed': set([])} reply3 = {'current': set(['tap2']), 'added': set([]), 'removed': set(['tap0'])} with mock.patch.object(async_process.AsyncProcess, "_spawn"),\ mock.patch.object(log.KeywordArgumentAdapter, 'exception') as log_exception,\ mock.patch.object(self.mod_agent.OVSNeutronAgent, 'scan_ports') as scan_ports,\ mock.patch.object( self.mod_agent.OVSNeutronAgent, 'process_network_ports') as process_network_ports,\ mock.patch.object(self.mod_agent.OVSNeutronAgent, 'check_ovs_status') as check_ovs_status,\ mock.patch.object(self.mod_agent.OVSNeutronAgent, 'setup_integration_br') as setup_int_br,\ mock.patch.object(self.mod_agent.OVSNeutronAgent, 'setup_physical_bridges') as setup_phys_br,\ mock.patch.object(time, 'sleep'),\ mock.patch.object( self.mod_agent.OVSNeutronAgent, 'update_stale_ofport_rules') as update_stale, \ mock.patch.object(self.mod_agent.OVSNeutronAgent, 'cleanup_stale_flows') as cleanup: log_exception.side_effect = Exception( 'Fake exception to get out of the loop') scan_ports.side_effect = [reply2, reply3] process_network_ports.side_effect = [ False, Exception('Fake exception to get out of the loop')] check_ovs_status.side_effect = args try: self.agent.daemon_loop() except Exception: pass scan_ports.assert_has_calls([ mock.call(set(), set()), mock.call(set(), set()) ]) process_network_ports.assert_has_calls([ mock.call(reply2, False), mock.call(reply3, True) ]) cleanup.assert_called_once_with() self.assertTrue(update_stale.called) # Verify the OVS restart we triggered in the loop # re-setup the bridges setup_int_br.assert_has_calls([mock.call()]) setup_phys_br.assert_has_calls([mock.call({})]) def test_ovs_status(self): self._test_ovs_status(constants.OVS_NORMAL, constants.OVS_DEAD, constants.OVS_RESTARTED) # OVS will not DEAD in some exception, like DBConnectionError. self._test_ovs_status(constants.OVS_NORMAL, constants.OVS_RESTARTED) def test_set_rpc_timeout(self): self.agent._handle_sigterm(None, None) for rpc_client in (self.agent.plugin_rpc.client, self.agent.sg_plugin_rpc.client, self.agent.dvr_plugin_rpc.client, self.agent.state_rpc.client): self.assertEqual(10, rpc_client.timeout) def test_cleanup_stale_flows_iter_0(self): with mock.patch.object(self.agent.int_br, 'agent_uuid_stamp', new=1234),\ mock.patch.object(self.agent.int_br, 'dump_flows_all_tables') as dump_flows,\ mock.patch.object(self.agent.int_br, 'delete_flows') as del_flow: dump_flows.return_value = [ 'cookie=0x4d2, duration=50.156s, table=0,actions=drop', 'cookie=0x4321, duration=54.143s, table=2, priority=0', 'cookie=0x2345, duration=50.125s, table=2, priority=0', 'cookie=0x4d2, duration=52.112s, table=3, actions=drop', ] self.agent.cleanup_stale_flows() expected = [ mock.call(cookie='0x4321/-1', table='2'), mock.call(cookie='0x2345/-1', table='2'), ] self.assertEqual(expected, del_flow.mock_calls) def test_set_rpc_timeout_no_value(self): self.agent.quitting_rpc_timeout = None with mock.patch.object(self.agent, 'set_rpc_timeout') as mock_set_rpc: self.agent._handle_sigterm(None, None) self.assertFalse(mock_set_rpc.called) def test_arp_spoofing_port_security_disabled(self): int_br = mock.create_autospec(self.agent.int_br) self.agent.setup_arp_spoofing_protection( int_br, FakeVif(), {'port_security_enabled': False}) self.assertTrue(int_br.delete_arp_spoofing_protection.called) self.assertFalse(int_br.install_arp_spoofing_protection.called) def test_arp_spoofing_basic_rule_setup_without_ip(self): vif = FakeVif() fake_details = {'fixed_ips': []} self.agent.prevent_arp_spoofing = True int_br = mock.create_autospec(self.agent.int_br) self.agent.setup_arp_spoofing_protection(int_br, vif, fake_details) self.assertEqual( [mock.call(port=vif.ofport)], int_br.delete_arp_spoofing_protection.mock_calls) self.assertFalse(int_br.install_arp_spoofing_protection.called) def test_arp_spoofing_basic_rule_setup_fixed_ip(self): vif = FakeVif() fake_details = {'fixed_ips': [{'ip_address': '192.168.44.100'}]} self.agent.prevent_arp_spoofing = True int_br = mock.create_autospec(self.agent.int_br) self.agent.setup_arp_spoofing_protection(int_br, vif, fake_details) self.assertEqual( [mock.call(port=vif.ofport)], int_br.delete_arp_spoofing_protection.mock_calls) self.assertTrue(int_br.install_arp_spoofing_protection.called) def test_arp_spoofing_fixed_and_allowed_addresses(self): vif = FakeVif() fake_details = { 'fixed_ips': [{'ip_address': '192.168.44.100'}, {'ip_address': '192.168.44.101'}], 'allowed_address_pairs': [{'ip_address': '192.168.44.102/32'}, {'ip_address': '192.168.44.103/32'}] } self.agent.prevent_arp_spoofing = True int_br = mock.create_autospec(self.agent.int_br) self.agent.setup_arp_spoofing_protection(int_br, vif, fake_details) # make sure all addresses are allowed addresses = {'192.168.44.100', '192.168.44.101', '192.168.44.102/32', '192.168.44.103/32'} self.assertEqual( [mock.call(port=vif.ofport, ip_addresses=addresses)], int_br.install_arp_spoofing_protection.mock_calls) def test__get_ofport_moves(self): previous = {'port1': 1, 'port2': 2} current = {'port1': 5, 'port2': 2} # we expect it to tell us port1 moved expected = ['port1'] self.assertEqual(expected, self.agent._get_ofport_moves(current, previous)) def test_update_stale_ofport_rules_clears_old(self): self.agent.prevent_arp_spoofing = True self.agent.vifname_to_ofport_map = {'port1': 1, 'port2': 2} self.agent.int_br = mock.Mock() # simulate port1 was removed newmap = {'port2': 2} self.agent.int_br.get_vif_port_to_ofport_map.return_value = newmap self.agent.update_stale_ofport_rules() # rules matching port 1 should have been deleted self.assertEqual( [mock.call(port=1)], self.agent.int_br.delete_arp_spoofing_protection.mock_calls) # make sure the state was updated with the new map self.assertEqual(self.agent.vifname_to_ofport_map, newmap) def test_update_stale_ofport_rules_treats_moved(self): self.agent.prevent_arp_spoofing = True self.agent.vifname_to_ofport_map = {'port1': 1, 'port2': 2} self.agent.treat_devices_added_or_updated = mock.Mock() self.agent.int_br = mock.Mock() # simulate port1 was moved newmap = {'port2': 2, 'port1': 90} self.agent.int_br.get_vif_port_to_ofport_map.return_value = newmap ofport_changed_ports = self.agent.update_stale_ofport_rules() self.assertEqual(['port1'], ofport_changed_ports) def test__setup_tunnel_port_while_new_mapping_is_added(self): """ Test that _setup_tunnel_port doesn't fail if new vlan mapping is added in a different coroutine while iterating over existing mappings. See bug 1449944 for more info. """ def add_new_vlan_mapping(*args, **kwargs): self.agent.local_vlan_map['bar'] = ( self.mod_agent.LocalVLANMapping(1, 2, 3, 4)) bridge = mock.Mock() tunnel_type = 'vxlan' self.agent.tun_br_ofports = {tunnel_type: dict()} self.agent.l2_pop = False self.agent.local_vlan_map = { 'foo': self.mod_agent.LocalVLANMapping(4, tunnel_type, 2, 1)} bridge.install_flood_to_tun.side_effect = add_new_vlan_mapping self.agent._setup_tunnel_port(bridge, 1, 2, tunnel_type=tunnel_type) self.assertIn('bar', self.agent.local_vlan_map) class TestOvsNeutronAgentOFCtl(TestOvsNeutronAgent, ovs_test_base.OVSOFCtlTestBase): pass class AncillaryBridgesTest(object): def setUp(self): super(AncillaryBridgesTest, self).setUp() notifier_p = mock.patch(NOTIFIER) notifier_cls = notifier_p.start() self.notifier = mock.Mock() notifier_cls.return_value = self.notifier cfg.CONF.set_default('firewall_driver', 'neutron.agent.firewall.NoopFirewallDriver', group='SECURITYGROUP') cfg.CONF.set_override('report_interval', 0, 'AGENT') self.kwargs = self.mod_agent.create_agent_config_map(cfg.CONF) def _test_ancillary_bridges(self, bridges, ancillary): device_ids = ancillary[:] def pullup_side_effect(*args): # Check that the device_id exists, if it does return it # if it does not return None try: device_ids.remove(args[0]) return args[0] except Exception: return None with mock.patch.object(self.mod_agent.OVSNeutronAgent, 'setup_integration_br'),\ mock.patch('neutron.agent.linux.utils.get_interface_mac', return_value='00:00:00:00:00:01'),\ mock.patch('neutron.agent.common.ovs_lib.BaseOVS.get_bridges', return_value=bridges),\ mock.patch('neutron.agent.common.ovs_lib.BaseOVS.' 'get_bridge_external_bridge_id', side_effect=pullup_side_effect),\ mock.patch( 'neutron.agent.common.ovs_lib.OVSBridge.' 'get_ports_attributes', return_value=[]),\ mock.patch( 'neutron.agent.common.ovs_lib.OVSBridge.' 'get_vif_ports', return_value=[]): self.agent = self.mod_agent.OVSNeutronAgent(self._bridge_classes(), **self.kwargs) self.assertEqual(len(ancillary), len(self.agent.ancillary_brs)) if ancillary: bridges = [br.br_name for br in self.agent.ancillary_brs] for br in ancillary: self.assertIn(br, bridges) def test_ancillary_bridges_single(self): bridges = ['br-int', 'br-ex'] self._test_ancillary_bridges(bridges, ['br-ex']) def test_ancillary_bridges_none(self): bridges = ['br-int'] self._test_ancillary_bridges(bridges, []) def test_ancillary_bridges_multiple(self): bridges = ['br-int', 'br-ex1', 'br-ex2'] self._test_ancillary_bridges(bridges, ['br-ex1', 'br-ex2']) def mock_scan_ancillary_ports(self, vif_port_set=None, registered_ports=None): bridges = ['br-int', 'br-ex'] ancillary = ['br-ex'] with mock.patch.object(self.mod_agent.OVSNeutronAgent, 'setup_integration_br'), \ mock.patch.object(self.mod_agent.OVSNeutronAgent, '_restore_local_vlan_map'), \ mock.patch('neutron.agent.common.ovs_lib.BaseOVS.get_bridges', return_value=bridges), \ mock.patch('neutron.agent.common.ovs_lib.BaseOVS.' 'get_bridge_external_bridge_id', side_effect=ancillary), \ mock.patch('neutron.agent.common.ovs_lib.OVSBridge.' 'get_vif_port_set', return_value=vif_port_set): self.agent = self.mod_agent.OVSNeutronAgent(self._bridge_classes(), **self.kwargs) return self.agent.scan_ancillary_ports(registered_ports) def test_scan_ancillary_ports_returns_cur_only_for_unchanged_ports(self): vif_port_set = set([1, 2]) registered_ports = set([1, 2]) expected = dict(current=vif_port_set) actual = self.mock_scan_ancillary_ports(vif_port_set, registered_ports) self.assertEqual(expected, actual) def test_scan_ancillary_ports_returns_port_changes(self): vif_port_set = set([1, 3]) registered_ports = set([1, 2]) expected = dict(current=vif_port_set, added=set([3]), removed=set([2])) actual = self.mock_scan_ancillary_ports(vif_port_set, registered_ports) self.assertEqual(expected, actual) class AncillaryBridgesTestOFCtl(AncillaryBridgesTest, ovs_test_base.OVSOFCtlTestBase): pass class TestOvsDvrNeutronAgent(object): def setUp(self): super(TestOvsDvrNeutronAgent, self).setUp() notifier_p = mock.patch(NOTIFIER) notifier_cls = notifier_p.start() self.notifier = mock.Mock() notifier_cls.return_value = self.notifier cfg.CONF.set_default('firewall_driver', 'neutron.agent.firewall.NoopFirewallDriver', group='SECURITYGROUP') kwargs = self.mod_agent.create_agent_config_map(cfg.CONF) with mock.patch.object(self.mod_agent.OVSNeutronAgent, 'setup_integration_br'),\ mock.patch.object(self.mod_agent.OVSNeutronAgent, 'setup_ancillary_bridges', return_value=[]),\ mock.patch('neutron.agent.linux.utils.get_interface_mac', return_value='00:00:00:00:00:01'),\ mock.patch( 'neutron.agent.common.ovs_lib.BaseOVS.get_bridges'),\ mock.patch('oslo_service.loopingcall.' 'FixedIntervalLoopingCall', new=MockFixedIntervalLoopingCall),\ mock.patch( 'neutron.agent.common.ovs_lib.OVSBridge.' 'get_ports_attributes', return_value=[]),\ mock.patch( 'neutron.agent.common.ovs_lib.OVSBridge.' 'get_vif_ports', return_value=[]): self.agent = self.mod_agent.OVSNeutronAgent(self._bridge_classes(), **kwargs) # set back to true because initial report state will succeed due # to mocked out RPC calls self.agent.use_call = True self.agent.tun_br = self.br_tun_cls(br_name='br-tun') self.agent.sg_agent = mock.Mock() def _setup_for_dvr_test(self): self._port = mock.Mock() self._port.ofport = 10 self._port.vif_id = "1234-5678-90" self._physical_network = 'physeth1' self._old_local_vlan = None self._segmentation_id = 2001 self.agent.enable_distributed_routing = True self.agent.enable_tunneling = True self.agent.patch_tun_ofport = 1 self.agent.patch_int_ofport = 2 self.agent.dvr_agent.local_ports = {} self.agent.local_vlan_map = {} self.agent.dvr_agent.enable_distributed_routing = True self.agent.dvr_agent.enable_tunneling = True self.agent.dvr_agent.patch_tun_ofport = 1 self.agent.dvr_agent.patch_int_ofport = 2 self.agent.dvr_agent.tun_br = mock.Mock() self.agent.dvr_agent.phys_brs[self._physical_network] = mock.Mock() self.agent.dvr_agent.bridge_mappings = {self._physical_network: 'br-eth1'} self.agent.dvr_agent.int_ofports[self._physical_network] = 30 self.agent.dvr_agent.phys_ofports[self._physical_network] = 40 self.agent.dvr_agent.local_dvr_map = {} self.agent.dvr_agent.registered_dvr_macs = set() self.agent.dvr_agent.dvr_mac_address = 'aa:22:33:44:55:66' self._net_uuid = 'my-net-uuid' self._fixed_ips = [{'subnet_id': 'my-subnet-uuid', 'ip_address': '1.1.1.1'}] self._compute_port = mock.Mock() self._compute_port.ofport = 20 self._compute_port.vif_id = "1234-5678-91" self._compute_fixed_ips = [{'subnet_id': 'my-subnet-uuid', 'ip_address': '1.1.1.3'}] @staticmethod def _expected_port_bound(port, lvid, is_dvr=True): resp = [ mock.call.db_get_val('Port', port.port_name, 'other_config'), mock.call.set_db_attribute('Port', port.port_name, 'other_config', mock.ANY), ] if is_dvr: resp = [mock.call.get_vifs_by_ids([])] + resp return resp def _expected_install_dvr_process(self, lvid, port, ip_version, gateway_ip, gateway_mac): if ip_version == 4: ipvx_calls = [ mock.call.install_dvr_process_ipv4( vlan_tag=lvid, gateway_ip=gateway_ip), ] else: ipvx_calls = [ mock.call.install_dvr_process_ipv6( vlan_tag=lvid, gateway_mac=gateway_mac), ] return ipvx_calls + [ mock.call.install_dvr_process( vlan_tag=lvid, dvr_mac_address=self.agent.dvr_agent.dvr_mac_address, vif_mac=port.vif_mac, ), ] def _test_port_bound_for_dvr_on_vlan_network(self, device_owner, ip_version=4): self._setup_for_dvr_test() if ip_version == 4: gateway_ip = '1.1.1.1' cidr = '1.1.1.0/24' else: gateway_ip = '2001:100::1' cidr = '2001:100::0/64' self._port.vif_mac = gateway_mac = 'aa:bb:cc:11:22:33' self._compute_port.vif_mac = '77:88:99:00:11:22' physical_network = self._physical_network segmentation_id = self._segmentation_id network_type = p_const.TYPE_VLAN int_br = mock.create_autospec(self.agent.int_br) tun_br = mock.create_autospec(self.agent.tun_br) phys_br = mock.create_autospec(self.br_phys_cls('br-phys')) int_br.set_db_attribute.return_value = True int_br.db_get_val.return_value = {} with mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_subnet_for_dvr', return_value={'gateway_ip': gateway_ip, 'cidr': cidr, 'ip_version': ip_version, 'gateway_mac': gateway_mac}),\ mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_ports_on_host_by_subnet', return_value=[]),\ mock.patch.object(self.agent.dvr_agent.int_br, 'get_vif_port_by_id', return_value=self._port),\ mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent, 'tun_br', new=tun_br),\ mock.patch.dict(self.agent.phys_brs, {physical_network: phys_br}),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'tun_br', new=tun_br),\ mock.patch.dict(self.agent.dvr_agent.phys_brs, {physical_network: phys_br}): self.agent.port_bound( self._port, self._net_uuid, network_type, physical_network, segmentation_id, self._fixed_ips, n_const.DEVICE_OWNER_DVR_INTERFACE, False) phy_ofp = self.agent.dvr_agent.phys_ofports[physical_network] int_ofp = self.agent.dvr_agent.int_ofports[physical_network] lvid = self.agent.local_vlan_map[self._net_uuid].vlan expected_on_phys_br = [ mock.call.provision_local_vlan( port=phy_ofp, lvid=lvid, segmentation_id=segmentation_id, distributed=True, ), ] + self._expected_install_dvr_process( port=self._port, lvid=lvid, ip_version=ip_version, gateway_ip=gateway_ip, gateway_mac=gateway_mac) expected_on_int_br = [ mock.call.provision_local_vlan( port=int_ofp, lvid=lvid, segmentation_id=segmentation_id, ), ] + self._expected_port_bound(self._port, lvid) self.assertEqual(expected_on_int_br, int_br.mock_calls) self.assertEqual([], tun_br.mock_calls) self.assertEqual(expected_on_phys_br, phys_br.mock_calls) int_br.reset_mock() tun_br.reset_mock() phys_br.reset_mock() self.agent.port_bound(self._compute_port, self._net_uuid, network_type, physical_network, segmentation_id, self._compute_fixed_ips, device_owner, False) expected_on_int_br = [ mock.call.install_dvr_to_src_mac( network_type=network_type, gateway_mac=gateway_mac, dst_mac=self._compute_port.vif_mac, dst_port=self._compute_port.ofport, vlan_tag=segmentation_id, ), ] + self._expected_port_bound(self._compute_port, lvid, False) self.assertEqual(expected_on_int_br, int_br.mock_calls) self.assertFalse([], tun_br.mock_calls) self.assertFalse([], phys_br.mock_calls) def _test_port_bound_for_dvr_on_vxlan_network(self, device_owner, ip_version=4): self._setup_for_dvr_test() if ip_version == 4: gateway_ip = '1.1.1.1' cidr = '1.1.1.0/24' else: gateway_ip = '2001:100::1' cidr = '2001:100::0/64' network_type = p_const.TYPE_VXLAN self._port.vif_mac = gateway_mac = 'aa:bb:cc:11:22:33' self._compute_port.vif_mac = '77:88:99:00:11:22' physical_network = self._physical_network segmentation_id = self._segmentation_id int_br = mock.create_autospec(self.agent.int_br) tun_br = mock.create_autospec(self.agent.tun_br) phys_br = mock.create_autospec(self.br_phys_cls('br-phys')) int_br.set_db_attribute.return_value = True int_br.db_get_val.return_value = {} with mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_subnet_for_dvr', return_value={'gateway_ip': gateway_ip, 'cidr': cidr, 'ip_version': ip_version, 'gateway_mac': gateway_mac}),\ mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_ports_on_host_by_subnet', return_value=[]),\ mock.patch.object(self.agent.dvr_agent.int_br, 'get_vif_port_by_id', return_value=self._port),\ mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent, 'tun_br', new=tun_br),\ mock.patch.dict(self.agent.phys_brs, {physical_network: phys_br}),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'tun_br', new=tun_br),\ mock.patch.dict(self.agent.dvr_agent.phys_brs, {physical_network: phys_br}): self.agent.port_bound( self._port, self._net_uuid, network_type, physical_network, segmentation_id, self._fixed_ips, n_const.DEVICE_OWNER_DVR_INTERFACE, False) lvid = self.agent.local_vlan_map[self._net_uuid].vlan expected_on_int_br = self._expected_port_bound( self._port, lvid) expected_on_tun_br = [ mock.call.provision_local_vlan( network_type=network_type, segmentation_id=segmentation_id, lvid=lvid, distributed=True), ] + self._expected_install_dvr_process( port=self._port, lvid=lvid, ip_version=ip_version, gateway_ip=gateway_ip, gateway_mac=gateway_mac) self.assertEqual(expected_on_int_br, int_br.mock_calls) self.assertEqual(expected_on_tun_br, tun_br.mock_calls) self.assertEqual([], phys_br.mock_calls) int_br.reset_mock() tun_br.reset_mock() phys_br.reset_mock() self.agent.port_bound(self._compute_port, self._net_uuid, network_type, physical_network, segmentation_id, self._compute_fixed_ips, device_owner, False) expected_on_int_br = [ mock.call.install_dvr_to_src_mac( network_type=network_type, gateway_mac=gateway_mac, dst_mac=self._compute_port.vif_mac, dst_port=self._compute_port.ofport, vlan_tag=lvid, ), ] + self._expected_port_bound(self._compute_port, lvid, False) self.assertEqual(expected_on_int_br, int_br.mock_calls) self.assertEqual([], tun_br.mock_calls) self.assertEqual([], phys_br.mock_calls) def test_port_bound_for_dvr_with_compute_ports(self): self._test_port_bound_for_dvr_on_vlan_network( device_owner="compute:None") self._test_port_bound_for_dvr_on_vlan_network( device_owner="compute:None", ip_version=6) self._test_port_bound_for_dvr_on_vxlan_network( device_owner="compute:None") self._test_port_bound_for_dvr_on_vxlan_network( device_owner="compute:None", ip_version=6) def test_port_bound_for_dvr_with_lbaas_vip_ports(self): self._test_port_bound_for_dvr_on_vlan_network( device_owner=n_const.DEVICE_OWNER_LOADBALANCER) self._test_port_bound_for_dvr_on_vlan_network( device_owner=n_const.DEVICE_OWNER_LOADBALANCER, ip_version=6) self._test_port_bound_for_dvr_on_vxlan_network( device_owner=n_const.DEVICE_OWNER_LOADBALANCER) self._test_port_bound_for_dvr_on_vxlan_network( device_owner=n_const.DEVICE_OWNER_LOADBALANCER, ip_version=6) def test_port_bound_for_dvr_with_dhcp_ports(self): self._test_port_bound_for_dvr_on_vlan_network( device_owner=n_const.DEVICE_OWNER_DHCP) self._test_port_bound_for_dvr_on_vlan_network( device_owner=n_const.DEVICE_OWNER_DHCP, ip_version=6) self._test_port_bound_for_dvr_on_vxlan_network( device_owner=n_const.DEVICE_OWNER_DHCP) self._test_port_bound_for_dvr_on_vxlan_network( device_owner=n_const.DEVICE_OWNER_DHCP, ip_version=6) def test_port_bound_for_dvr_with_csnat_ports(self): self._setup_for_dvr_test() int_br = mock.create_autospec(self.agent.int_br) tun_br = mock.create_autospec(self.agent.tun_br) int_br.set_db_attribute.return_value = True int_br.db_get_val.return_value = {} with mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_subnet_for_dvr', return_value={'gateway_ip': '1.1.1.1', 'cidr': '1.1.1.0/24', 'ip_version': 4, 'gateway_mac': 'aa:bb:cc:11:22:33'}),\ mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_ports_on_host_by_subnet', return_value=[]),\ mock.patch.object(self.agent.dvr_agent.int_br, 'get_vif_port_by_id', return_value=self._port),\ mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent, 'tun_br', new=tun_br),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'tun_br', new=tun_br): self.agent.port_bound( self._port, self._net_uuid, 'vxlan', None, None, self._fixed_ips, n_const.DEVICE_OWNER_ROUTER_SNAT, False) lvid = self.agent.local_vlan_map[self._net_uuid].vlan expected_on_int_br = [ mock.call.install_dvr_to_src_mac( network_type='vxlan', gateway_mac='aa:bb:cc:11:22:33', dst_mac=self._port.vif_mac, dst_port=self._port.ofport, vlan_tag=lvid, ), ] + self._expected_port_bound(self._port, lvid, is_dvr=False) self.assertEqual(expected_on_int_br, int_br.mock_calls) expected_on_tun_br = [ mock.call.provision_local_vlan( network_type='vxlan', lvid=lvid, segmentation_id=None, distributed=True, ), ] self.assertEqual(expected_on_tun_br, tun_br.mock_calls) def test_treat_devices_removed_for_dvr_interface(self): self._test_treat_devices_removed_for_dvr_interface() self._test_treat_devices_removed_for_dvr_interface(ip_version=6) self._test_treat_devices_removed_for_dvr_interface(network_type='vlan') self._test_treat_devices_removed_for_dvr_interface(ip_version=6, network_type='vlan') def _test_treat_devices_removed_for_dvr_interface( self, ip_version=4, network_type='vxlan'): self._setup_for_dvr_test() if ip_version == 4: gateway_ip = '1.1.1.1' cidr = '1.1.1.0/24' else: gateway_ip = '2001:100::1' cidr = '2001:100::0/64' gateway_mac = 'aa:bb:cc:11:22:33' int_br = mock.create_autospec(self.agent.int_br) tun_br = mock.create_autospec(self.agent.tun_br) int_br.set_db_attribute.return_value = True int_br.db_get_val.return_value = {} with mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_subnet_for_dvr', return_value={'gateway_ip': gateway_ip, 'cidr': cidr, 'ip_version': ip_version, 'gateway_mac': gateway_mac}),\ mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_ports_on_host_by_subnet', return_value=[]),\ mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent, 'tun_br', new=tun_br),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'tun_br', new=tun_br),\ mock.patch.object(self.agent.dvr_agent.int_br, 'get_vif_port_by_id', return_value=self._port): if network_type == 'vlan': self.agent.port_bound(self._port, self._net_uuid, network_type, self._physical_network, self._segmentation_id, self._compute_fixed_ips, n_const.DEVICE_OWNER_DVR_INTERFACE, False) else: self.agent.port_bound( self._port, self._net_uuid, 'vxlan', None, None, self._fixed_ips, n_const.DEVICE_OWNER_DVR_INTERFACE, False) lvid = self.agent.local_vlan_map[self._net_uuid].vlan self.assertEqual(self._expected_port_bound(self._port, lvid), int_br.mock_calls) expected_on_tun_br = [ mock.call.provision_local_vlan(network_type='vxlan', lvid=lvid, segmentation_id=None, distributed=True), ] + self._expected_install_dvr_process( port=self._port, lvid=lvid, ip_version=ip_version, gateway_ip=gateway_ip, gateway_mac=gateway_mac) self.assertEqual(expected_on_tun_br, tun_br.mock_calls) int_br.reset_mock() tun_br.reset_mock() phys_br = mock.create_autospec(self.br_phys_cls('br-phys')) with mock.patch.object(self.agent, 'reclaim_local_vlan'),\ mock.patch.object(self.agent.plugin_rpc, 'update_device_list', return_value={ 'devices_up': [], 'devices_down': [self._port.vif_id], 'failed_devices_up': [], 'failed_devices_down': []}),\ mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent, 'tun_br', new=tun_br),\ mock.patch.dict(self.agent.phys_brs, {self._physical_network: phys_br}),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'tun_br', new=tun_br),\ mock.patch.dict(self.agent.dvr_agent.phys_brs, {self._physical_network: phys_br}): self.agent.treat_devices_removed([self._port.vif_id]) lvid = self.agent.local_vlan_map[self._net_uuid].vlan if ip_version == 4: expected = [ mock.call.delete_dvr_process_ipv4( vlan_tag=lvid, gateway_ip=gateway_ip), ] else: expected = [ mock.call.delete_dvr_process_ipv6( vlan_tag=lvid, gateway_mac=gateway_mac), ] expected.extend([ mock.call.delete_dvr_process( vlan_tag=lvid, vif_mac=self._port.vif_mac), ]) if network_type == 'vlan': self.assertEqual([], int_br.mock_calls) self.assertEqual([], tun_br.mock_calls) self.assertEqual(expected, phys_br.mock_calls) self.assertEqual({}, self.agent.dvr_agent.local_ports) else: self.assertEqual([], int_br.mock_calls) self.assertEqual(expected, tun_br.mock_calls) self.assertEqual([], phys_br.mock_calls) def _test_treat_devices_removed_for_dvr(self, device_owner, ip_version=4): self._setup_for_dvr_test() if ip_version == 4: gateway_ip = '1.1.1.1' cidr = '1.1.1.0/24' else: gateway_ip = '2001:100::1' cidr = '2001:100::0/64' gateway_mac = 'aa:bb:cc:11:22:33' int_br = mock.create_autospec(self.agent.int_br) tun_br = mock.create_autospec(self.agent.tun_br) int_br.set_db_attribute.return_value = True int_br.db_get_val.return_value = {} with mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_subnet_for_dvr', return_value={'gateway_ip': gateway_ip, 'cidr': cidr, 'ip_version': ip_version, 'gateway_mac': gateway_mac}),\ mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_ports_on_host_by_subnet', return_value=[]),\ mock.patch.object(self.agent.dvr_agent.int_br, 'get_vif_port_by_id', return_value=self._port),\ mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent, 'tun_br', new=tun_br),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'tun_br', new=tun_br): self.agent.port_bound( self._port, self._net_uuid, 'vxlan', None, None, self._fixed_ips, n_const.DEVICE_OWNER_DVR_INTERFACE, False) lvid = self.agent.local_vlan_map[self._net_uuid].vlan self.assertEqual( self._expected_port_bound(self._port, lvid), int_br.mock_calls) expected_on_tun_br = [ mock.call.provision_local_vlan( network_type='vxlan', segmentation_id=None, lvid=lvid, distributed=True), ] + self._expected_install_dvr_process( port=self._port, lvid=lvid, ip_version=ip_version, gateway_ip=gateway_ip, gateway_mac=gateway_mac) self.assertEqual(expected_on_tun_br, tun_br.mock_calls) int_br.reset_mock() tun_br.reset_mock() self.agent.port_bound(self._compute_port, self._net_uuid, 'vxlan', None, None, self._compute_fixed_ips, device_owner, False) self.assertEqual( [ mock.call.install_dvr_to_src_mac( network_type='vxlan', gateway_mac='aa:bb:cc:11:22:33', dst_mac=self._compute_port.vif_mac, dst_port=self._compute_port.ofport, vlan_tag=lvid, ), ] + self._expected_port_bound(self._compute_port, lvid, False), int_br.mock_calls) self.assertEqual([], tun_br.mock_calls) int_br.reset_mock() tun_br.reset_mock() with mock.patch.object(self.agent, 'reclaim_local_vlan'),\ mock.patch.object(self.agent.plugin_rpc, 'update_device_list', return_value={ 'devices_up': [], 'devices_down': [ self._compute_port.vif_id], 'failed_devices_up': [], 'failed_devices_down': []}),\ mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent, 'tun_br', new=tun_br),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'tun_br', new=tun_br): self.agent.treat_devices_removed([self._compute_port.vif_id]) int_br.assert_has_calls([ mock.call.delete_dvr_to_src_mac( network_type='vxlan', vlan_tag=lvid, dst_mac=self._compute_port.vif_mac, ), ]) self.assertEqual([], tun_br.mock_calls) def test_treat_devices_removed_for_dvr_with_compute_ports(self): self._test_treat_devices_removed_for_dvr( device_owner="compute:None") self._test_treat_devices_removed_for_dvr( device_owner="compute:None", ip_version=6) def test_treat_devices_removed_for_dvr_with_lbaas_vip_ports(self): self._test_treat_devices_removed_for_dvr( device_owner=n_const.DEVICE_OWNER_LOADBALANCER) self._test_treat_devices_removed_for_dvr( device_owner=n_const.DEVICE_OWNER_LOADBALANCER, ip_version=6) def test_treat_devices_removed_for_dvr_with_dhcp_ports(self): self._test_treat_devices_removed_for_dvr( device_owner=n_const.DEVICE_OWNER_DHCP) self._test_treat_devices_removed_for_dvr( device_owner=n_const.DEVICE_OWNER_DHCP, ip_version=6) def test_treat_devices_removed_for_dvr_csnat_port(self): self._setup_for_dvr_test() gateway_mac = 'aa:bb:cc:11:22:33' int_br = mock.create_autospec(self.agent.int_br) tun_br = mock.create_autospec(self.agent.tun_br) int_br.set_db_attribute.return_value = True int_br.db_get_val.return_value = {} with mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_subnet_for_dvr', return_value={'gateway_ip': '1.1.1.1', 'cidr': '1.1.1.0/24', 'ip_version': 4, 'gateway_mac': gateway_mac}),\ mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_ports_on_host_by_subnet', return_value=[]),\ mock.patch.object(self.agent.dvr_agent.int_br, 'get_vif_port_by_id', return_value=self._port),\ mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent, 'tun_br', new=tun_br),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'tun_br', new=tun_br): self.agent.port_bound( self._port, self._net_uuid, 'vxlan', None, None, self._fixed_ips, n_const.DEVICE_OWNER_ROUTER_SNAT, False) lvid = self.agent.local_vlan_map[self._net_uuid].vlan expected_on_int_br = [ mock.call.install_dvr_to_src_mac( network_type='vxlan', gateway_mac=gateway_mac, dst_mac=self._port.vif_mac, dst_port=self._port.ofport, vlan_tag=lvid, ), ] + self._expected_port_bound(self._port, lvid, is_dvr=False) self.assertEqual(expected_on_int_br, int_br.mock_calls) expected_on_tun_br = [ mock.call.provision_local_vlan( network_type='vxlan', lvid=lvid, segmentation_id=None, distributed=True, ), ] self.assertEqual(expected_on_tun_br, tun_br.mock_calls) int_br.reset_mock() tun_br.reset_mock() with mock.patch.object(self.agent, 'reclaim_local_vlan'),\ mock.patch.object(self.agent.plugin_rpc, 'update_device_list', return_value={ 'devices_up': [], 'devices_down': [self._port.vif_id], 'failed_devices_up': [], 'failed_devices_down': []}),\ mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent, 'tun_br', new=tun_br),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'tun_br', new=tun_br): self.agent.treat_devices_removed([self._port.vif_id]) expected_on_int_br = [ mock.call.delete_dvr_to_src_mac( network_type='vxlan', dst_mac=self._port.vif_mac, vlan_tag=lvid, ), ] self.assertEqual(expected_on_int_br, int_br.mock_calls) expected_on_tun_br = [] self.assertEqual(expected_on_tun_br, tun_br.mock_calls) def test_setup_dvr_flows_on_int_br(self): self._setup_for_dvr_test() int_br = mock.create_autospec(self.agent.int_br) tun_br = mock.create_autospec(self.agent.tun_br) with mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent, 'tun_br', new=tun_br),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'tun_br', new=tun_br),\ mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_dvr_mac_address_list', return_value=[{'host': 'cn1', 'mac_address': 'aa:bb:cc:dd:ee:ff'}, {'host': 'cn2', 'mac_address': '11:22:33:44:55:66'}]): self.agent.dvr_agent.setup_dvr_flows_on_integ_br() self.assertTrue(self.agent.dvr_agent.in_distributed_mode()) physical_networks = list( self.agent.dvr_agent.bridge_mappings.keys()) ioport = self.agent.dvr_agent.int_ofports[physical_networks[0]] expected_on_int_br = [ # setup_dvr_flows_on_integ_br mock.call.setup_canary_table(), mock.call.install_drop(table_id=constants.DVR_TO_SRC_MAC, priority=1), mock.call.install_drop(table_id=constants.DVR_TO_SRC_MAC_VLAN, priority=1), mock.call.install_normal(table_id=constants.LOCAL_SWITCHING, priority=1), mock.call.install_drop(table_id=constants.LOCAL_SWITCHING, priority=2, in_port=ioport), ] self.assertEqual(expected_on_int_br, int_br.mock_calls) self.assertEqual([], tun_br.mock_calls) def test_get_dvr_mac_address(self): self._setup_for_dvr_test() self.agent.dvr_agent.dvr_mac_address = None with mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_dvr_mac_address_by_host', return_value={'host': 'cn1', 'mac_address': 'aa:22:33:44:55:66'}): self.agent.dvr_agent.get_dvr_mac_address() self.assertEqual('aa:22:33:44:55:66', self.agent.dvr_agent.dvr_mac_address) self.assertTrue(self.agent.dvr_agent.in_distributed_mode()) def test_get_dvr_mac_address_exception(self): self._setup_for_dvr_test() self.agent.dvr_agent.dvr_mac_address = None int_br = mock.create_autospec(self.agent.int_br) with mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_dvr_mac_address_by_host', side_effect=oslo_messaging.RemoteError),\ mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br): self.agent.dvr_agent.get_dvr_mac_address() self.assertIsNone(self.agent.dvr_agent.dvr_mac_address) self.assertFalse(self.agent.dvr_agent.in_distributed_mode()) self.assertEqual([mock.call.install_normal()], int_br.mock_calls) def test_get_dvr_mac_address_retried(self): valid_entry = {'host': 'cn1', 'mac_address': 'aa:22:33:44:55:66'} raise_timeout = oslo_messaging.MessagingTimeout() # Raise a timeout the first 2 times it calls get_dvr_mac_address() self._setup_for_dvr_test() self.agent.dvr_agent.dvr_mac_address = None with mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_dvr_mac_address_by_host', side_effect=(raise_timeout, raise_timeout, valid_entry)): self.agent.dvr_agent.get_dvr_mac_address() self.assertEqual('aa:22:33:44:55:66', self.agent.dvr_agent.dvr_mac_address) self.assertTrue(self.agent.dvr_agent.in_distributed_mode()) self.assertEqual(self.agent.dvr_agent.plugin_rpc. get_dvr_mac_address_by_host.call_count, 3) def test_get_dvr_mac_address_retried_max(self): raise_timeout = oslo_messaging.MessagingTimeout() # Raise a timeout every time until we give up, currently 5 tries self._setup_for_dvr_test() self.agent.dvr_agent.dvr_mac_address = None int_br = mock.create_autospec(self.agent.int_br) with mock.patch.object(self.agent.dvr_agent.plugin_rpc, 'get_dvr_mac_address_by_host', side_effect=raise_timeout),\ mock.patch.object(utils, "execute"),\ mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br): self.agent.dvr_agent.get_dvr_mac_address() self.assertIsNone(self.agent.dvr_agent.dvr_mac_address) self.assertFalse(self.agent.dvr_agent.in_distributed_mode()) self.assertEqual(self.agent.dvr_agent.plugin_rpc. get_dvr_mac_address_by_host.call_count, 5) def test_dvr_mac_address_update(self): self._setup_for_dvr_test() newhost = 'cn2' newmac = 'aa:bb:cc:dd:ee:ff' int_br = mock.create_autospec(self.agent.int_br) tun_br = mock.create_autospec(self.agent.tun_br) phys_br = mock.create_autospec(self.br_phys_cls('br-phys')) physical_network = 'physeth1' with mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent, 'tun_br', new=tun_br),\ mock.patch.dict(self.agent.phys_brs, {physical_network: phys_br}),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'tun_br', new=tun_br),\ mock.patch.dict(self.agent.dvr_agent.phys_brs, {physical_network: phys_br}): self.agent.dvr_agent.\ dvr_mac_address_update( dvr_macs=[{'host': newhost, 'mac_address': newmac}]) expected_on_int_br = [ mock.call.add_dvr_mac_vlan( mac=newmac, port=self.agent.int_ofports[physical_network]), mock.call.add_dvr_mac_tun( mac=newmac, port=self.agent.patch_tun_ofport), ] expected_on_tun_br = [ mock.call.add_dvr_mac_tun( mac=newmac, port=self.agent.patch_int_ofport), ] expected_on_phys_br = [ mock.call.add_dvr_mac_vlan( mac=newmac, port=self.agent.phys_ofports[physical_network]), ] self.assertEqual(expected_on_int_br, int_br.mock_calls) self.assertEqual(expected_on_tun_br, tun_br.mock_calls) self.assertEqual(expected_on_phys_br, phys_br.mock_calls) int_br.reset_mock() tun_br.reset_mock() phys_br.reset_mock() with mock.patch.object(self.agent, 'int_br', new=int_br),\ mock.patch.object(self.agent, 'tun_br', new=tun_br),\ mock.patch.dict(self.agent.phys_brs, {physical_network: phys_br}),\ mock.patch.object(self.agent.dvr_agent, 'int_br', new=int_br),\ mock.patch.object(self.agent.dvr_agent, 'tun_br', new=tun_br),\ mock.patch.dict(self.agent.dvr_agent.phys_brs, {physical_network: phys_br}): self.agent.dvr_agent.dvr_mac_address_update(dvr_macs=[]) expected_on_int_br = [ mock.call.remove_dvr_mac_vlan( mac=newmac), mock.call.remove_dvr_mac_tun( mac=newmac, port=self.agent.patch_tun_ofport), ] expected_on_tun_br = [ mock.call.remove_dvr_mac_tun( mac=newmac), ] expected_on_phys_br = [ mock.call.remove_dvr_mac_vlan( mac=newmac), ] self.assertEqual(expected_on_int_br, int_br.mock_calls) self.assertEqual(expected_on_tun_br, tun_br.mock_calls) self.assertEqual(expected_on_phys_br, phys_br.mock_calls) def test_ovs_restart(self): self._setup_for_dvr_test() reset_methods = ( 'reset_ovs_parameters', 'reset_dvr_parameters', 'setup_dvr_flows_on_integ_br', 'setup_dvr_flows_on_tun_br', 'setup_dvr_flows_on_phys_br', 'setup_dvr_mac_flows_on_all_brs') reset_mocks = [mock.patch.object(self.agent.dvr_agent, method).start() for method in reset_methods] tun_br = mock.create_autospec(self.agent.tun_br) with mock.patch.object(self.agent, 'check_ovs_status', return_value=constants.OVS_RESTARTED),\ mock.patch.object(self.agent, '_agent_has_updates', side_effect=TypeError('loop exit')),\ mock.patch.object(self.agent, 'tun_br', new=tun_br): # block RPC calls and bridge calls self.agent.setup_physical_bridges = mock.Mock() self.agent.setup_integration_br = mock.Mock() self.agent.setup_tunnel_br = mock.Mock() self.agent.state_rpc = mock.Mock() try: self.agent.rpc_loop(polling_manager=mock.Mock()) except TypeError: pass self.assertTrue(all([x.called for x in reset_mocks])) def _test_scan_ports_failure(self, scan_method_name): with mock.patch.object(self.agent, 'check_ovs_status', return_value=constants.OVS_RESTARTED),\ mock.patch.object(self.agent, scan_method_name, side_effect=TypeError('broken')),\ mock.patch.object(self.agent, '_agent_has_updates', return_value=True),\ mock.patch.object(self.agent, '_check_and_handle_signal', side_effect=[True, False]): # block RPC calls and bridge calls self.agent.setup_physical_bridges = mock.Mock() self.agent.setup_integration_br = mock.Mock() self.agent.reset_tunnel_br = mock.Mock() self.agent.state_rpc = mock.Mock() self.agent.rpc_loop(polling_manager=mock.Mock()) def test_scan_ports_failure(self): self._test_scan_ports_failure('scan_ports') def test_scan_ancillary_ports_failure(self): with mock.patch.object(self.agent, 'scan_ports'): with mock.patch.object(self.agent, 'update_stale_ofport_rules'): self.agent.ancillary_brs = mock.Mock() self._test_scan_ports_failure('scan_ancillary_ports') class TestOvsDvrNeutronAgentOFCtl(TestOvsDvrNeutronAgent, ovs_test_base.OVSOFCtlTestBase): pass class TestValidateTunnelLocalIP(base.BaseTestCase): def test_validate_local_ip_no_tunneling(self): cfg.CONF.set_override('tunnel_types', [], group='AGENT') # The test will pass simply if no exception is raised by the next call: ovs_agent.validate_local_ip(FAKE_IP1) def test_validate_local_ip_with_valid_ip(self): cfg.CONF.set_override('tunnel_types', ['vxlan'], group='AGENT') mock_get_device_by_ip = mock.patch.object( ip_lib.IPWrapper, 'get_device_by_ip').start() ovs_agent.validate_local_ip(FAKE_IP1) mock_get_device_by_ip.assert_called_once_with(FAKE_IP1) def test_validate_local_ip_with_invalid_ip(self): cfg.CONF.set_override('tunnel_types', ['vxlan'], group='AGENT') mock_get_device_by_ip = mock.patch.object( ip_lib.IPWrapper, 'get_device_by_ip').start() mock_get_device_by_ip.return_value = None with testtools.ExpectedException(SystemExit): ovs_agent.validate_local_ip(FAKE_IP1) mock_get_device_by_ip.assert_called_once_with(FAKE_IP1)
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.util import java.time.{DateTimeException, LocalDate, ZoneOffset} import org.apache.spark.{SparkFunSuite, SparkUpgradeException} import org.apache.spark.sql.catalyst.plans.SQLHelper import org.apache.spark.sql.catalyst.util._ import org.apache.spark.sql.catalyst.util.DateTimeUtils.{getZoneId, localDateToDays} import org.apache.spark.sql.internal.SQLConf class DateFormatterSuite extends SparkFunSuite with SQLHelper { test("parsing dates") { DateTimeTestUtils.outstandingTimezonesIds.foreach { timeZone => withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> timeZone) { val formatter = DateFormatter(getZoneId(timeZone)) val daysSinceEpoch = formatter.parse("2018-12-02") assert(daysSinceEpoch === 17867) } } } test("format dates") { DateTimeTestUtils.outstandingTimezonesIds.foreach { timeZone => withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> timeZone) { val formatter = DateFormatter(getZoneId(timeZone)) val date = formatter.format(17867) assert(date === "2018-12-02") } } } test("roundtrip date -> days -> date") { Seq( "0050-01-01", "0953-02-02", "1423-03-08", "1969-12-31", "1972-08-25", "1975-09-26", "2018-12-12", "2038-01-01", "5010-11-17").foreach { date => DateTimeTestUtils.outstandingTimezonesIds.foreach { timeZone => withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> timeZone) { val formatter = DateFormatter(getZoneId(timeZone)) val days = formatter.parse(date) val formatted = formatter.format(days) assert(date === formatted) } } } } test("roundtrip days -> date -> days") { Seq( -701265, -371419, -199722, -1, 0, 967, 2094, 17877, 24837, 1110657).foreach { days => DateTimeTestUtils.outstandingTimezonesIds.foreach { timeZone => withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> timeZone) { val formatter = DateFormatter(getZoneId(timeZone)) val date = formatter.format(days) val parsed = formatter.parse(date) assert(days === parsed) } } } } test("parsing date without explicit day") { val formatter = DateFormatter("yyyy MMM", ZoneOffset.UTC) val daysSinceEpoch = formatter.parse("2018 Dec") assert(daysSinceEpoch === LocalDate.of(2018, 12, 1).toEpochDay) } test("formatting negative years with default pattern") { val epochDays = LocalDate.of(-99, 1, 1).toEpochDay.toInt assert(DateFormatter(ZoneOffset.UTC).format(epochDays) === "-0099-01-01") } test("special date values") { testSpecialDatetimeValues { zoneId => val formatter = DateFormatter(zoneId) assert(formatter.parse("EPOCH") === 0) val today = localDateToDays(LocalDate.now(zoneId)) assert(formatter.parse("Yesterday") === today - 1) assert(formatter.parse("now") === today) assert(formatter.parse("today ") === today) assert(formatter.parse("tomorrow UTC") === today + 1) } } test("SPARK-30958: parse date with negative year") { val formatter1 = DateFormatter("yyyy-MM-dd", ZoneOffset.UTC) assert(formatter1.parse("-1234-02-22") === localDateToDays(LocalDate.of(-1234, 2, 22))) def assertParsingError(f: => Unit): Unit = { intercept[Exception](f) match { case e: SparkUpgradeException => assert(e.getCause.isInstanceOf[DateTimeException]) case e => assert(e.isInstanceOf[DateTimeException]) } } // "yyyy" with "G" can't parse negative year or year 0000. val formatter2 = DateFormatter("G yyyy-MM-dd", ZoneOffset.UTC) assertParsingError(formatter2.parse("BC -1234-02-22")) assertParsingError(formatter2.parse("AD 0000-02-22")) assert(formatter2.parse("BC 1234-02-22") === localDateToDays(LocalDate.of(-1233, 2, 22))) assert(formatter2.parse("AD 1234-02-22") === localDateToDays(LocalDate.of(1234, 2, 22))) } }
""" Indirection layer for PostgreSQL-specific fields, so the tests don't fail when run with a backend other than PostgreSQL. """ import enum from django.db import models try: from django.contrib.postgres.fields import ( ArrayField, BigIntegerRangeField, CICharField, CIEmailField, CITextField, DateRangeField, DateTimeRangeField, DecimalRangeField, HStoreField, IntegerRangeField, JSONField, ) from django.contrib.postgres.search import SearchVectorField except ImportError: class DummyArrayField(models.Field): def __init__(self, base_field, size=None, **kwargs): super().__init__(**kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() kwargs.update({ 'base_field': '', 'size': 1, }) return name, path, args, kwargs class DummyJSONField(models.Field): def __init__(self, encoder=None, **kwargs): super().__init__(**kwargs) ArrayField = DummyArrayField BigIntegerRangeField = models.Field CICharField = models.Field CIEmailField = models.Field CITextField = models.Field DateRangeField = models.Field DateTimeRangeField = models.Field DecimalRangeField = models.Field HStoreField = models.Field IntegerRangeField = models.Field JSONField = DummyJSONField SearchVectorField = models.Field class EnumField(models.CharField): def get_prep_value(self, value): return value.value if isinstance(value, enum.Enum) else value
##################################################### #This program uses the internal Keras library of #TensorFlow for the training of the neural network. #The architecture of the NN is 24-6-3. # Autor: Detlef Heinze # Version: 1.0 Use TensorFlow Version >= 2.0.0 # Tested with Tensorflow 2.3.0 # This programm needs the following installation for # saving the checkpoints: pip3 install h5py ##################################################### #### Load dependencies import tensorflow as tf from tensorflow.keras import layers from numpy import loadtxt, savetxt, reshape import datetime as dt print("TensorFlow Version: " + tf.__version__) print("TF Keras Version: " + tf.keras.__version__) #### Load data start= dt.datetime.now() # Step 1: Import Training Data (xTrain und yTrain) print('Lese xTrain- und yTrain-Daten') xTrain= loadtxt('xTrain_TwoCubesCylinder375-24.csv') yTrain= loadtxt('yTrain_TwoCubesCylinder375-3.csv') # Step 2: Import Test Data (xTest und yTest) print('Lese xTest und yTest-Daten') xTest= loadtxt('xTest_TwoCubesCylinder300-24.csv') yTest= loadtxt('yTest_TwoCubesCylinder300-3.csv') #Parameter für das 24 - 6 - 3 neuronale Netz n_input = 24 #24 Neuronen für die gemessene Daten n_hidden_1 = 6 #Größe der versteckten Neuronenschicht n_classes = 3 #Größe der ausgebenden Neuronenschicht #ist gleich der Anzahl der Klassen print('NN-Architektur: ' + repr(n_input) +' - ' + repr(n_hidden_1) + ' - ' + repr(n_classes)) # Design neural network architecture model = tf.keras.Sequential() #One layer after the other model.add(layers.Dense(n_hidden_1, activation='relu', input_shape=(n_input,))) #Dense= fully connected model.add(layers.Dense(n_classes, activation='softmax')) model.summary() # Configure model model.compile(loss='categorical_crossentropy', optimizer=tf.optimizers.Adam(0.001), metrics=['accuracy']) # Create a Callback for checking the model's value accuracy after each epoch # If the accuracy has improved the model is saved (overwriten) for later use filepath= 'bestModel.hdf5' checkpoint = tf.keras.callbacks.ModelCheckpoint(filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max') callbacks_list = [checkpoint] # Training #Adapt number of epochs to get eventually better results (recommended: 100 to 300) model.fit(xTrain, yTrain, batch_size=1, epochs=150, verbose=0, validation_data=(xTest, yTest), callbacks=callbacks_list) duration = (dt.datetime.now() - start) print("\nDuration: " + str(duration)) # Load best model of training to evaluate it model.load_weights(filepath) # Compile model (required to evaluate the model) model.compile(loss='categorical_crossentropy', optimizer=tf.optimizers.Adam(0.001), metrics=['accuracy']) # Evaluation model.evaluate(xTest, yTest) # Access model result= model.get_weights() weights_h1 = result[0] biases_b1= result[1] weights_out= result[2] biases_out= result[3] # Save model files (csv) print('\n--------------Saving model(csv)-------------') print('Saving NNweights_h1.csv') savetxt('NNweights_h1.csv', weights_h1, fmt='%10.8f', delimiter=' ') print('Saving NNbiases_b1.csv') savetxt('NNbiases_b1.csv', biases_b1, fmt='%10.8f', delimiter=' ') print('Saving NNweights_out.csv') savetxt('NNweights_out.csv', weights_out, fmt='%10.8f', delimiter=' ') print('Saving NNbiases_out.csv') savetxt('NNbiases_out.csv', biases_out, fmt='%10.8f', delimiter=' ') # Save model files for Lego Mindstorms robot (rtf) print('\n--Saving model (rtf for Lego Mindstorms EV3)--') #Format: <number of rows>CR<number of columns>CR<{<aReal>CR}* print('Saving NNweights_h1.rtf') tmpArray = reshape(weights_h1, (weights_h1.shape[0] * weights_h1.shape[1],)) result= [weights_h1.shape[0],weights_h1.shape[1]] + tmpArray.tolist() savetxt('NNweights_h1.rtf', result, fmt='%10.8f', delimiter='\r', newline='\r') print('Saving NNbiases_b1.rtf') result= [1,biases_b1.shape[0]] + biases_b1.tolist() savetxt('NNbiases_b1.rtf', result, fmt='%10.8f', delimiter='\r', newline='\r') print('Saving NNweights_out.rtf') tmpArray = reshape(weights_out, (weights_out.shape[0] * weights_out.shape[1],)) result= [weights_out.shape[0],weights_out.shape[1]] + tmpArray.tolist() savetxt('NNweights_out.rtf', result, fmt='%10.8f', delimiter='\r', newline='\r') print('Saving NNbiases_out.rtf') result= [1,biases_out.shape[0]] + biases_out.tolist() savetxt('NNbiases_out.rtf', result, fmt='%10.8f', delimiter='\r', newline='\r') print('Model saved.')
require "rjava" # Copyright (c) 2000, 2009 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 module Org::Eclipse::Swt::Widgets module ControlImports #:nodoc: class_module.module_eval { include ::Java::Lang include ::Org::Eclipse::Swt::Widgets include ::Org::Eclipse::Swt::Internal::Gdip include ::Org::Eclipse::Swt::Internal::Win32 include ::Org::Eclipse::Swt::Graphics include ::Org::Eclipse::Swt include ::Org::Eclipse::Swt::Events include ::Org::Eclipse::Swt::Accessibility } end # Control is the abstract superclass of all windowed user interface classes. # <p> # <dl> # <dt><b>Styles:</b> # <dd>BORDER</dd> # <dd>LEFT_TO_RIGHT, RIGHT_TO_LEFT</dd> # <dt><b>Events:</b> # <dd>DragDetect, FocusIn, FocusOut, Help, KeyDown, KeyUp, MenuDetect, MouseDoubleClick, MouseDown, MouseEnter, # MouseExit, MouseHover, MouseUp, MouseMove, Move, Paint, Resize, Traverse</dd> # </dl> # </p><p> # Only one of LEFT_TO_RIGHT or RIGHT_TO_LEFT may be specified. # </p><p> # IMPORTANT: This class is intended to be subclassed <em>only</em> # within the SWT implementation. # </p> # # @see <a href="http://www.eclipse.org/swt/snippets/#control">Control snippets</a> # @see <a href="http://www.eclipse.org/swt/examples.php">SWT Example: ControlExample</a> # @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. class Control < ControlImports.const_get :Widget include_class_members ControlImports overload_protected { include Drawable } # the handle to the OS resource # (Warning: This field is platform dependent) # <p> # <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT # public API. It is marked public only so that it can be shared # within the packages provided by SWT. It is not available on all # platforms and should never be accessed from application code. # </p> # # long attr_accessor :handle alias_method :attr_handle, :handle undef_method :handle alias_method :attr_handle=, :handle= undef_method :handle= attr_accessor :parent alias_method :attr_parent, :parent undef_method :parent alias_method :attr_parent=, :parent= undef_method :parent= attr_accessor :cursor alias_method :attr_cursor, :cursor undef_method :cursor alias_method :attr_cursor=, :cursor= undef_method :cursor= attr_accessor :menu alias_method :attr_menu, :menu undef_method :menu alias_method :attr_menu=, :menu= undef_method :menu= attr_accessor :tool_tip_text alias_method :attr_tool_tip_text, :tool_tip_text undef_method :tool_tip_text alias_method :attr_tool_tip_text=, :tool_tip_text= undef_method :tool_tip_text= attr_accessor :layout_data alias_method :attr_layout_data, :layout_data undef_method :layout_data alias_method :attr_layout_data=, :layout_data= undef_method :layout_data= attr_accessor :accessible alias_method :attr_accessible, :accessible undef_method :accessible alias_method :attr_accessible=, :accessible= undef_method :accessible= attr_accessor :background_image alias_method :attr_background_image, :background_image undef_method :background_image alias_method :attr_background_image=, :background_image= undef_method :background_image= attr_accessor :region alias_method :attr_region, :region undef_method :region alias_method :attr_region=, :region= undef_method :region= attr_accessor :font alias_method :attr_font, :font undef_method :font alias_method :attr_font=, :font= undef_method :font= attr_accessor :draw_count alias_method :attr_draw_count, :draw_count undef_method :draw_count alias_method :attr_draw_count=, :draw_count= undef_method :draw_count= attr_accessor :foreground alias_method :attr_foreground, :foreground undef_method :foreground alias_method :attr_foreground=, :foreground= undef_method :foreground= attr_accessor :background alias_method :attr_background, :background undef_method :background alias_method :attr_background=, :background= undef_method :background= typesig { [] } # Prevents uninitialized instances from being created outside the package. def initialize @handle = 0 @parent = nil @cursor = nil @menu = nil @tool_tip_text = nil @layout_data = nil @accessible = nil @background_image = nil @region = nil @font = nil @draw_count = 0 @foreground = 0 @background = 0 super() end typesig { [Composite, ::Java::Int] } # 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#LEFT_TO_RIGHT # @see SWT#RIGHT_TO_LEFT # @see Widget#checkSubclass # @see Widget#getStyle def initialize(parent, style) @handle = 0 @parent = nil @cursor = nil @menu = nil @tool_tip_text = nil @layout_data = nil @accessible = nil @background_image = nil @region = nil @font = nil @draw_count = 0 @foreground = 0 @background = 0 super(parent, style) @parent = parent create_widget end typesig { [ControlListener] } # Adds the listener to the collection of listeners who will # be notified when the control is moved or resized, by sending # it one of the messages defined in the <code>ControlListener</code> # interface. # # @param listener the listener which should be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see ControlListener # @see #removeControlListener def add_control_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end typed_listener = TypedListener.new(listener) add_listener(SWT::Resize, typed_listener) add_listener(SWT::Move, typed_listener) end typesig { [DragDetectListener] } # Adds the listener to the collection of listeners who will # be notified when a drag gesture occurs, by sending it # one of the messages defined in the <code>DragDetectListener</code> # interface. # # @param listener the listener which should be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see DragDetectListener # @see #removeDragDetectListener # # @since 3.3 def add_drag_detect_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end typed_listener = TypedListener.new(listener) add_listener(SWT::DragDetect, typed_listener) end typesig { [FocusListener] } # Adds the listener to the collection of listeners who will # be notified when the control gains or loses focus, by sending # it one of the messages defined in the <code>FocusListener</code> # interface. # # @param listener the listener which should be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see FocusListener # @see #removeFocusListener def add_focus_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end typed_listener = TypedListener.new(listener) add_listener(SWT::FocusIn, typed_listener) add_listener(SWT::FocusOut, typed_listener) end typesig { [HelpListener] } # Adds the listener to the collection of listeners who will # be notified when help events are generated for the control, # by sending it one of the messages defined in the # <code>HelpListener</code> interface. # # @param listener the listener which should be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see HelpListener # @see #removeHelpListener def add_help_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end typed_listener = TypedListener.new(listener) add_listener(SWT::Help, typed_listener) end typesig { [KeyListener] } # Adds the listener to the collection of listeners who will # be notified when keys are pressed and released on the system keyboard, by sending # it one of the messages defined in the <code>KeyListener</code> # interface. # <p> # When a key listener is added to a control, the control # will take part in widget traversal. By default, all # traversal keys (such as the tab key and so on) are # delivered to the control. In order for a control to take # part in traversal, it should listen for traversal events. # Otherwise, the user can traverse into a control but not # out. Note that native controls such as table and tree # implement key traversal in the operating system. It is # not necessary to add traversal listeners for these controls, # unless you want to override the default traversal. # </p> # @param listener the listener which should be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see KeyListener # @see #removeKeyListener def add_key_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end typed_listener = TypedListener.new(listener) add_listener(SWT::KeyUp, typed_listener) add_listener(SWT::KeyDown, typed_listener) end typesig { [MenuDetectListener] } # Adds the listener to the collection of listeners who will # be notified when the platform-specific context menu trigger # has occurred, by sending it one of the messages defined in # the <code>MenuDetectListener</code> interface. # # @param listener the listener which should be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see MenuDetectListener # @see #removeMenuDetectListener # # @since 3.3 def add_menu_detect_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end typed_listener = TypedListener.new(listener) add_listener(SWT::MenuDetect, typed_listener) end typesig { [MouseListener] } # Adds the listener to the collection of listeners who will # be notified when mouse buttons are pressed and released, by sending # it one of the messages defined in the <code>MouseListener</code> # interface. # # @param listener the listener which should be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see MouseListener # @see #removeMouseListener def add_mouse_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end typed_listener = TypedListener.new(listener) add_listener(SWT::MouseDown, typed_listener) add_listener(SWT::MouseUp, typed_listener) add_listener(SWT::MouseDoubleClick, typed_listener) end typesig { [MouseTrackListener] } # Adds the listener to the collection of listeners who will # be notified when the mouse passes or hovers over controls, by sending # it one of the messages defined in the <code>MouseTrackListener</code> # interface. # # @param listener the listener which should be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see MouseTrackListener # @see #removeMouseTrackListener def add_mouse_track_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end typed_listener = TypedListener.new(listener) add_listener(SWT::MouseEnter, typed_listener) add_listener(SWT::MouseExit, typed_listener) add_listener(SWT::MouseHover, typed_listener) end typesig { [MouseMoveListener] } # Adds the listener to the collection of listeners who will # be notified when the mouse moves, by sending it one of the # messages defined in the <code>MouseMoveListener</code> # interface. # # @param listener the listener which should be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see MouseMoveListener # @see #removeMouseMoveListener def add_mouse_move_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end typed_listener = TypedListener.new(listener) add_listener(SWT::MouseMove, typed_listener) end typesig { [MouseWheelListener] } # Adds the listener to the collection of listeners who will # be notified when the mouse wheel is scrolled, by sending # it one of the messages defined in the # <code>MouseWheelListener</code> interface. # # @param listener the listener which should be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see MouseWheelListener # @see #removeMouseWheelListener # # @since 3.3 def add_mouse_wheel_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end typed_listener = TypedListener.new(listener) add_listener(SWT::MouseWheel, typed_listener) end typesig { [PaintListener] } # Adds the listener to the collection of listeners who will # be notified when the receiver needs to be painted, by sending it # one of the messages defined in the <code>PaintListener</code> # interface. # # @param listener the listener which should be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see PaintListener # @see #removePaintListener def add_paint_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end typed_listener = TypedListener.new(listener) add_listener(SWT::Paint, typed_listener) end typesig { [TraverseListener] } # Adds the listener to the collection of listeners who will # be notified when traversal events occur, by sending it # one of the messages defined in the <code>TraverseListener</code> # interface. # # @param listener the listener which should be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see TraverseListener # @see #removeTraverseListener def add_traverse_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end typed_listener = TypedListener.new(listener) add_listener(SWT::Traverse, typed_listener) end typesig { [] } # long def border_handle return @handle end typesig { [] } def check_background shell = get_shell if ((self).equal?(shell)) return end self.attr_state &= ~PARENT_BACKGROUND composite = @parent begin mode = composite.attr_background_mode if (!(mode).equal?(0)) if ((mode).equal?(SWT::INHERIT_DEFAULT)) control = self begin if (((control.attr_state & THEME_BACKGROUND)).equal?(0)) return end control = control.attr_parent end while (!(control).equal?(composite)) end self.attr_state |= PARENT_BACKGROUND return end if ((composite).equal?(shell)) break end composite = composite.attr_parent end while (true) end typesig { [] } def check_border if ((get_border_width).equal?(0)) self.attr_style &= ~SWT::BORDER end end typesig { [] } def check_buffered self.attr_style &= ~SWT::DOUBLE_BUFFERED end typesig { [] } def check_composited # Do nothing end typesig { [::Java::Int] } # long def check_handle(hwnd) return (hwnd).equal?(@handle) end typesig { [] } def check_mirrored if (!((self.attr_style & SWT::RIGHT_TO_LEFT)).equal?(0)) bits = OS._get_window_long(@handle, OS::GWL_EXSTYLE) if (!((bits & OS::WS_EX_LAYOUTRTL)).equal?(0)) self.attr_style |= SWT::MIRRORED end end end typesig { [::Java::Int, ::Java::Int] } # Returns the preferred size of the receiver. # <p> # The <em>preferred size</em> of a control is the size that it would # best be displayed at. The width hint and height hint arguments # allow the caller to ask a control questions such as "Given a particular # width, how high does the control need to be to show all of the contents?" # To indicate that the caller does not wish to constrain a particular # dimension, the constant <code>SWT.DEFAULT</code> is passed for the hint. # </p> # # @param wHint the width hint (can be <code>SWT.DEFAULT</code>) # @param hHint the height hint (can be <code>SWT.DEFAULT</code>) # @return the preferred size of the control # # @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 Layout # @see #getBorderWidth # @see #getBounds # @see #getSize # @see #pack(boolean) # @see "computeTrim, getClientArea for controls that implement them" def compute_size(w_hint, h_hint) return compute_size(w_hint, h_hint, true) end typesig { [::Java::Int, ::Java::Int, ::Java::Boolean] } # Returns the preferred size of the receiver. # <p> # The <em>preferred size</em> of a control is the size that it would # best be displayed at. The width hint and height hint arguments # allow the caller to ask a control questions such as "Given a particular # width, how high does the control need to be to show all of the contents?" # To indicate that the caller does not wish to constrain a particular # dimension, the constant <code>SWT.DEFAULT</code> is passed for the hint. # </p><p> # If the changed flag is <code>true</code>, it indicates that the receiver's # <em>contents</em> have changed, therefore any caches that a layout manager # containing the control may have been keeping need to be flushed. When the # control is resized, the changed flag will be <code>false</code>, so layout # manager caches can be retained. # </p> # # @param wHint the width hint (can be <code>SWT.DEFAULT</code>) # @param hHint the height hint (can be <code>SWT.DEFAULT</code>) # @param changed <code>true</code> if the control's contents have changed, and <code>false</code> otherwise # @return the preferred size of the control. # # @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 Layout # @see #getBorderWidth # @see #getBounds # @see #getSize # @see #pack(boolean) # @see "computeTrim, getClientArea for controls that implement them" def compute_size(w_hint, h_hint, changed) check_widget width = DEFAULT_WIDTH height = DEFAULT_HEIGHT if (!(w_hint).equal?(SWT::DEFAULT)) width = w_hint end if (!(h_hint).equal?(SWT::DEFAULT)) height = h_hint end border = get_border_width width += border * 2 height += border * 2 return Point.new(width, height) end typesig { [] } def compute_tab_group if (is_tab_group) return self end return @parent.compute_tab_group end typesig { [] } def compute_tab_root tab_list = @parent.__get_tab_list if (!(tab_list).nil?) index = 0 while (index < tab_list.attr_length) if ((tab_list[index]).equal?(self)) break end index += 1 end if ((index).equal?(tab_list.attr_length)) if (is_tab_group) return self end end end return @parent.compute_tab_root end typesig { [] } def compute_tab_list if (is_tab_group) if (get_visible && get_enabled) return Array.typed(Widget).new([self]) end end return Array.typed(Widget).new(0) { nil } end typesig { [] } def create_handle # long hwnd_parent = widget_parent @handle = OS._create_window_ex(widget_ext_style, window_class, nil, widget_style, OS::CW_USEDEFAULT, 0, OS::CW_USEDEFAULT, 0, hwnd_parent, 0, OS._get_module_handle(nil), widget_create_struct) if ((@handle).equal?(0)) error(SWT::ERROR_NO_HANDLES) end bits = OS._get_window_long(@handle, OS::GWL_STYLE) if (!((bits & OS::WS_CHILD)).equal?(0)) OS._set_window_long_ptr(@handle, OS::GWLP_ID, @handle) end if (OS::IsDBLocale && !(hwnd_parent).equal?(0)) # long h_imc = OS._imm_get_context(hwnd_parent) OS._imm_associate_context(@handle, h_imc) OS._imm_release_context(hwnd_parent, h_imc) end end typesig { [] } def create_widget self.attr_state |= DRAG_DETECT @foreground = @background = -1 check_orientation(@parent) create_handle check_background check_buffered check_composited register subclass set_default_font check_mirrored check_border if (!((self.attr_state & PARENT_BACKGROUND)).equal?(0)) set_background end end typesig { [] } def default_background if (OS::IsWinCE) return OS._get_sys_color(OS::COLOR_WINDOW) end return OS._get_sys_color(OS::COLOR_BTNFACE) end typesig { [] } # long def default_font return self.attr_display.get_system_font.attr_handle end typesig { [] } def default_foreground return OS._get_sys_color(OS::COLOR_WINDOWTEXT) end typesig { [] } def deregister self.attr_display.remove_control(@handle) end typesig { [] } def destroy_widget # long hwnd = top_handle release_handle if (!(hwnd).equal?(0)) OS._destroy_window(hwnd) end end typesig { [Event] } # Detects a drag and drop gesture. This method is used # to detect a drag gesture when called from within a mouse # down listener. # # <p>By default, a drag is detected when the gesture # occurs anywhere within the client area of a control. # Some controls, such as tables and trees, override this # behavior. In addition to the operating system specific # drag gesture, they require the mouse to be inside an # item. Custom widget writers can use <code>setDragDetect</code> # to disable the default detection, listen for mouse down, # and then call <code>dragDetect()</code> from within the # listener to conditionally detect a drag. # </p> # # @param event the mouse down event # # @return <code>true</code> if the gesture occurred, and <code>false</code> otherwise. # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT when the event 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> # # @see DragDetectListener # @see #addDragDetectListener # # @see #getDragDetect # @see #setDragDetect # # @since 3.3 def drag_detect(event) check_widget if ((event).nil?) error(SWT::ERROR_NULL_ARGUMENT) end return drag_detect(event.attr_button, event.attr_count, event.attr_state_mask, event.attr_x, event.attr_y) end typesig { [MouseEvent] } # Detects a drag and drop gesture. This method is used # to detect a drag gesture when called from within a mouse # down listener. # # <p>By default, a drag is detected when the gesture # occurs anywhere within the client area of a control. # Some controls, such as tables and trees, override this # behavior. In addition to the operating system specific # drag gesture, they require the mouse to be inside an # item. Custom widget writers can use <code>setDragDetect</code> # to disable the default detection, listen for mouse down, # and then call <code>dragDetect()</code> from within the # listener to conditionally detect a drag. # </p> # # @param event the mouse down event # # @return <code>true</code> if the gesture occurred, and <code>false</code> otherwise. # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT when the event 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> # # @see DragDetectListener # @see #addDragDetectListener # # @see #getDragDetect # @see #setDragDetect # # @since 3.3 def drag_detect(event) check_widget if ((event).nil?) error(SWT::ERROR_NULL_ARGUMENT) end return drag_detect(event.attr_button, event.attr_count, event.attr_state_mask, event.attr_x, event.attr_y) end typesig { [::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int] } def drag_detect(button, count, state_mask, x, y) if (!(button).equal?(1) || !(count).equal?(1)) return false end dragging = drag_detect(@handle, x, y, false, nil, nil) if (OS._get_key_state(OS::VK_LBUTTON) < 0) if (!(OS._get_capture).equal?(@handle)) OS._set_capture(@handle) end end if (!dragging) # Feature in Windows. DragDetect() captures the mouse # and tracks its movement until the user releases the # left mouse button, presses the ESC key, or moves the # mouse outside the drag rectangle. If the user moves # the mouse outside of the drag rectangle, DragDetect() # returns true and a drag and drop operation can be # started. When the left mouse button is released or # the ESC key is pressed, these events are consumed by # DragDetect() so that application code that matches # mouse down/up pairs or looks for the ESC key will not # function properly. The fix is to send the missing # events when the drag has not started. # # NOTE: For now, don't send a fake WM_KEYDOWN/WM_KEYUP # events for the ESC key. This would require computing # wParam (the key) and lParam (the repeat count, scan code, # extended-key flag, context code, previous key-state flag, # and transition-state flag) which is non-trivial. if ((button).equal?(1) && OS._get_key_state(OS::VK_ESCAPE) >= 0) w_param = 0 if (!((state_mask & SWT::CTRL)).equal?(0)) w_param |= OS::MK_CONTROL end if (!((state_mask & SWT::SHIFT)).equal?(0)) w_param |= OS::MK_SHIFT end if (!((state_mask & SWT::ALT)).equal?(0)) w_param |= OS::MK_ALT end if (!((state_mask & SWT::BUTTON1)).equal?(0)) w_param |= OS::MK_LBUTTON end if (!((state_mask & SWT::BUTTON2)).equal?(0)) w_param |= OS::MK_MBUTTON end if (!((state_mask & SWT::BUTTON3)).equal?(0)) w_param |= OS::MK_RBUTTON end if (!((state_mask & SWT::BUTTON4)).equal?(0)) w_param |= OS::MK_XBUTTON1 end if (!((state_mask & SWT::BUTTON5)).equal?(0)) w_param |= OS::MK_XBUTTON2 end # long l_param = OS._makelparam(x, y) OS._send_message(@handle, OS::WM_LBUTTONUP, w_param, l_param) end return false end return send_drag_event(button, state_mask, x, y) end typesig { [::Java::Int] } # long def draw_background(h_dc) rect = RECT.new OS._get_client_rect(@handle, rect) draw_background(h_dc, rect) end typesig { [::Java::Int, RECT] } # long def draw_background(h_dc, rect) draw_background(h_dc, rect, -1) end typesig { [::Java::Int, RECT, ::Java::Int] } # long def draw_background(h_dc, rect, pixel) control = find_background_control if (!(control).nil?) if (!(control.attr_background_image).nil?) fill_image_background(h_dc, control, rect) return end pixel = control.get_background_pixel end if ((pixel).equal?(-1)) if (!((self.attr_state & THEME_BACKGROUND)).equal?(0)) if (OS::COMCTL32_MAJOR >= 6 && OS._is_app_themed) control = find_theme_control if (!(control).nil?) fill_theme_background(h_dc, control, rect) return end end end end if ((pixel).equal?(-1)) pixel = get_background_pixel end fill_background(h_dc, pixel, rect) end typesig { [::Java::Int, ::Java::Int, ::Java::Int, RECT] } # long # long # long def draw_image_background(h_dc, hwnd, h_bitmap, rect) rect2 = RECT.new OS._get_client_rect(hwnd, rect2) OS._map_window_points(hwnd, @handle, rect2, 2) # long h_brush = find_brush(h_bitmap, OS::BS_PATTERN) lp_point = POINT.new OS._get_window_org_ex(h_dc, lp_point) OS._set_brush_org_ex(h_dc, -rect2.attr_left - lp_point.attr_x, -rect2.attr_top - lp_point.attr_y, lp_point) # long h_old_brush = OS._select_object(h_dc, h_brush) OS._pat_blt(h_dc, rect.attr_left, rect.attr_top, rect.attr_right - rect.attr_left, rect.attr_bottom - rect.attr_top, OS::PATCOPY) OS._set_brush_org_ex(h_dc, lp_point.attr_x, lp_point.attr_y, nil) OS._select_object(h_dc, h_old_brush) end typesig { [::Java::Int, ::Java::Int, RECT] } # long # long def draw_theme_background(h_dc, hwnd, rect) # Do nothing end typesig { [::Java::Boolean] } def enable_drag(enabled) # Do nothing end typesig { [::Java::Boolean] } def enable_widget(enabled) OS._enable_window(@handle, enabled) end typesig { [::Java::Int, ::Java::Int, RECT] } # long def fill_background(h_dc, pixel, rect) if (rect.attr_left > rect.attr_right || rect.attr_top > rect.attr_bottom) return end # long h_palette = self.attr_display.attr_h_palette if (!(h_palette).equal?(0)) OS._select_palette(h_dc, h_palette, false) OS._realize_palette(h_dc) end OS._fill_rect(h_dc, rect, find_brush(pixel, OS::BS_SOLID)) end typesig { [::Java::Int, Control, RECT] } # long def fill_image_background(h_dc, control, rect) if (rect.attr_left > rect.attr_right || rect.attr_top > rect.attr_bottom) return end if (!(control).nil?) image = control.attr_background_image if (!(image).nil?) control.draw_image_background(h_dc, @handle, image.attr_handle, rect) end end end typesig { [::Java::Int, Control, RECT] } # long def fill_theme_background(h_dc, control, rect) if (rect.attr_left > rect.attr_right || rect.attr_top > rect.attr_bottom) return end if (!(control).nil?) control.draw_theme_background(h_dc, @handle, rect) end end typesig { [] } def find_background_control if (!(@background).equal?(-1) || !(@background_image).nil?) return self end return !((self.attr_state & PARENT_BACKGROUND)).equal?(0) ? @parent.find_background_control : nil end typesig { [::Java::Int, ::Java::Int] } # long # long def find_brush(value, lb_style) return @parent.find_brush(value, lb_style) end typesig { [] } def find_cursor if (!(@cursor).nil?) return @cursor end return @parent.find_cursor end typesig { [] } def find_image_control control = find_background_control return !(control).nil? && !(control.attr_background_image).nil? ? control : nil end typesig { [] } def find_theme_control return (@background).equal?(-1) && (@background_image).nil? ? @parent.find_theme_control : nil end typesig { [Control] } def find_menus(control) if (!(@menu).nil? && !(self).equal?(control)) return Array.typed(Menu).new([@menu]) end return Array.typed(Menu).new(0) { nil } end typesig { [String] } def find_mnemonic(string) index = 0 length_ = string.length begin while (index < length_ && !(string.char_at(index)).equal?(Character.new(?&.ord))) index += 1 end if ((index += 1) >= length_) return Character.new(?\0.ord) end if (!(string.char_at(index)).equal?(Character.new(?&.ord))) return string.char_at(index) end index += 1 end while (index < length_) return Character.new(?\0.ord) end typesig { [Shell, Shell, Decorations, Decorations, Array.typed(Menu)] } def fix_children(new_shell, old_shell, new_decorations, old_decorations, menus) old_shell.fix_shell(new_shell, self) old_decorations.fix_decorations(new_decorations, self, menus) end typesig { [Control] } def fix_focus(focus_control) shell = get_shell control = self while (!(control).equal?(shell) && !((control = control.attr_parent)).nil?) if (control.set_fixed_focus) return end end shell.set_saved_focus(focus_control) OS._set_focus(0) end typesig { [] } # Forces the receiver to have the <em>keyboard focus</em>, causing # all keyboard events to be delivered to it. # # @return <code>true</code> if the control got focus, and <code>false</code> if it was unable to. # # @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 #setFocus def force_focus check_widget if ((self.attr_display.attr_focus_event).equal?(SWT::FocusOut)) return false end shell = menu_shell shell.set_saved_focus(self) if (!is_enabled || !is_visible || !is_active) return false end if (is_focus_control) return true end shell.set_saved_focus(nil) # This code is intentionally commented. # # When setting focus to a control, it is # possible that application code can set # the focus to another control inside of # WM_SETFOCUS. In this case, the original # control will no longer have the focus # and the call to setFocus() will return # false indicating failure. # # We are still working on a solution at # this time. # # if (OS.GetFocus () != OS.SetFocus (handle)) return false; OS._set_focus(@handle) if (is_disposed) return false end shell.set_saved_focus(self) return is_focus_control end typesig { [] } def force_resize if ((@parent).nil?) return end lpwp = @parent.attr_lpwp if ((lpwp).nil?) return end i = 0 while i < lpwp.attr_length wp = lpwp[i] if (!(wp).nil? && (wp.attr_hwnd).equal?(@handle)) # This code is intentionally commented. All widgets that # are created by SWT have WS_CLIPSIBLINGS to ensure that # application code does not draw outside of the control. # # int count = parent.getChildrenCount (); # if (count > 1) { # int bits = OS.GetWindowLong (handle, OS.GWL_STYLE); # if ((bits & OS.WS_CLIPSIBLINGS) == 0) wp.flags |= OS.SWP_NOCOPYBITS; # } _set_window_pos(wp.attr_hwnd, 0, wp.attr_x, wp.attr_y, wp.attr_cx, wp.attr_cy, wp.attr_flags) lpwp[i] = nil return end i += 1 end end typesig { [] } # Returns the accessible object for the receiver. # If this is the first time this object is requested, # then the object is created and returned. # # @return the accessible object # # @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 Accessible#addAccessibleListener # @see Accessible#addAccessibleControlListener # # @since 2.0 def get_accessible check_widget if ((@accessible).nil?) @accessible = new__accessible(self) end return @accessible end typesig { [] } # Returns the receiver's background color. # <p> # Note: This operation is a hint and may be overridden by the platform. # For example, on some versions of Windows the background of a TabFolder, # is a gradient rather than a solid color. # </p> # @return the background color # # @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> def get_background check_widget control = find_background_control if ((control).nil?) control = self end return Color.win32_new(self.attr_display, control.get_background_pixel) end typesig { [] } # Returns the receiver's background image. # # @return the background 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> # # @since 3.2 def get_background_image check_widget control = find_background_control if ((control).nil?) control = self end return control.attr_background_image end typesig { [] } def get_background_pixel return !(@background).equal?(-1) ? @background : default_background end typesig { [] } # Returns the receiver's border width. # # @return the border width # # @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> def get_border_width check_widget # long border_handle_ = border_handle bits1 = OS._get_window_long(border_handle_, OS::GWL_EXSTYLE) if (!((bits1 & OS::WS_EX_CLIENTEDGE)).equal?(0)) return OS._get_system_metrics(OS::SM_CXEDGE) end if (!((bits1 & OS::WS_EX_STATICEDGE)).equal?(0)) return OS._get_system_metrics(OS::SM_CXBORDER) end bits2 = OS._get_window_long(border_handle_, OS::GWL_STYLE) if (!((bits2 & OS::WS_BORDER)).equal?(0)) return OS._get_system_metrics(OS::SM_CXBORDER) end return 0 end typesig { [] } # Returns a rectangle describing the receiver's size and location # relative to its parent (or its display if its parent is null), # unless the receiver is a shell. In this case, the location is # relative to the display. # # @return the receiver's bounding rectangle # # @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> def get_bounds check_widget force_resize rect = RECT.new OS._get_window_rect(top_handle, rect) # long hwnd_parent = (@parent).nil? ? 0 : @parent.attr_handle OS._map_window_points(0, hwnd_parent, rect, 2) width = rect.attr_right - rect.attr_left height = rect.attr_bottom - rect.attr_top return Rectangle.new(rect.attr_left, rect.attr_top, width, height) end typesig { [] } def get_code_page if (OS::IsUnicode) return OS::CP_ACP end # long h_font = OS._send_message(@handle, OS::WM_GETFONT, 0, 0) log_font = OS::IsUnicode ? LOGFONTW.new : LOGFONTA.new OS._get_object(h_font, LOGFONT.attr_sizeof, log_font) cs = log_font.attr_lf_char_set & 0xff lp_cs = Array.typed(::Java::Int).new(8) { 0 } if (OS._translate_charset_info(cs, lp_cs, OS::TCI_SRCCHARSET)) return lp_cs[1] end return OS._get_acp end typesig { [] } def get_clipboard_text string = "" if (OS._open_clipboard(0)) # long h_mem = OS._get_clipboard_data(OS::IsUnicode ? OS::CF_UNICODETEXT : OS::CF_TEXT) if (!(h_mem).equal?(0)) # Ensure byteCount is a multiple of 2 bytes on UNICODE platforms byte_count = OS._global_size(h_mem) / TCHAR.attr_sizeof * TCHAR.attr_sizeof # long ptr = OS._global_lock(h_mem) if (!(ptr).equal?(0)) # Use the character encoding for the default locale buffer = TCHAR.new(0, byte_count / TCHAR.attr_sizeof) OS._move_memory(buffer, ptr, byte_count) string = RJava.cast_to_string(buffer.to_s(0, buffer.strlen)) OS._global_unlock(h_mem) end end OS._close_clipboard end return string end typesig { [] } # Returns the receiver's cursor, or null if it has not been set. # <p> # When the mouse pointer passes over a control its appearance # is changed to match the control's cursor. # </p> # # @return the receiver's cursor or <code>null</code> # # @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.3 def get_cursor check_widget return @cursor end typesig { [] } # Returns <code>true</code> if the receiver is detecting # drag gestures, and <code>false</code> otherwise. # # @return the receiver's drag detect 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> # # @since 3.3 def get_drag_detect check_widget return !((self.attr_state & DRAG_DETECT)).equal?(0) end typesig { [] } def get_drawing return @draw_count <= 0 end typesig { [] } # Returns <code>true</code> if the receiver is enabled, and # <code>false</code> otherwise. A disabled control is typically # not selectable from the user interface and draws with an # inactive or "grayed" look. # # @return the receiver's enabled 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 #isEnabled def get_enabled check_widget return OS._is_window_enabled(@handle) end typesig { [] } # Returns the font that the receiver will use to paint textual information. # # @return the receiver's font # # @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> def get_font check_widget if (!(@font).nil?) return @font end # long h_font = OS._send_message(@handle, OS::WM_GETFONT, 0, 0) if ((h_font).equal?(0)) h_font = default_font end return Font.win32_new(self.attr_display, h_font) end typesig { [] } # Returns the foreground color that the receiver will use to draw. # # @return the receiver's foreground color # # @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> def get_foreground check_widget return Color.win32_new(self.attr_display, get_foreground_pixel) end typesig { [] } def get_foreground_pixel return !(@foreground).equal?(-1) ? @foreground : default_foreground end typesig { [] } # Returns layout data which is associated with the receiver. # # @return the receiver's layout data # # @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> def get_layout_data check_widget return @layout_data end typesig { [] } # Returns a point describing the receiver's location relative # to its parent (or its display if its parent is null), unless # the receiver is a shell. In this case, the point is # relative to the display. # # @return the receiver's location # # @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> def get_location check_widget force_resize rect = RECT.new OS._get_window_rect(top_handle, rect) # long hwnd_parent = (@parent).nil? ? 0 : @parent.attr_handle OS._map_window_points(0, hwnd_parent, rect, 2) return Point.new(rect.attr_left, rect.attr_top) end typesig { [] } # Returns the receiver's pop up menu if it has one, or null # if it does not. All controls may optionally have a pop up # menu that is displayed when the user requests one for # the control. The sequence of key strokes, button presses # and/or button releases that are used to request a pop up # menu is platform specific. # # @return the receiver's menu # # @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> def get_menu check_widget return @menu end typesig { [] } # Returns the receiver's monitor. # # @return the receiver's monitor # # @since 3.0 def get_monitor check_widget if (OS::IsWinCE || OS::WIN32_VERSION < OS._version(4, 10)) return self.attr_display.get_primary_monitor end # long hmonitor = OS._monitor_from_window(@handle, OS::MONITOR_DEFAULTTONEAREST) lpmi = MONITORINFO.new lpmi.attr_cb_size = MONITORINFO.attr_sizeof OS._get_monitor_info(hmonitor, lpmi) monitor = SwtMonitor.new monitor.attr_handle = hmonitor monitor.attr_x = lpmi.attr_rc_monitor_left monitor.attr_y = lpmi.attr_rc_monitor_top monitor.attr_width = lpmi.attr_rc_monitor_right - lpmi.attr_rc_monitor_left monitor.attr_height = lpmi.attr_rc_monitor_bottom - lpmi.attr_rc_monitor_top monitor.attr_client_x = lpmi.attr_rc_work_left monitor.attr_client_y = lpmi.attr_rc_work_top monitor.attr_client_width = lpmi.attr_rc_work_right - lpmi.attr_rc_work_left monitor.attr_client_height = lpmi.attr_rc_work_bottom - lpmi.attr_rc_work_top return monitor end typesig { [] } # Returns the receiver's parent, which must be a <code>Composite</code> # or null when the receiver is a shell that was created with null or # a display for a parent. # # @return the receiver's parent # # @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> def get_parent check_widget return @parent end typesig { [] } def get_path count = 0 shell = get_shell control = self while (!(control).equal?(shell)) count += 1 control = control.attr_parent end control = self result = Array.typed(Control).new(count) { nil } while (!(control).equal?(shell)) result[(count -= 1)] = control control = control.attr_parent end return result end typesig { [] } # Returns the region that defines the shape of the control, # or null if the control has the default shape. # # @return the region that defines the shape of the shell (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> # # @since 3.4 def get_region check_widget return @region end typesig { [] } # Returns the receiver's shell. For all controls other than # shells, this simply returns the control's nearest ancestor # shell. Shells return themselves, even if they are children # of other shells. # # @return the receiver's shell # # @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 #getParent def get_shell check_widget return @parent.get_shell end typesig { [] } # Returns a point describing the receiver's size. The # x coordinate of the result is the width of the receiver. # The y coordinate of the result is the height of the # receiver. # # @return the receiver's size # # @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> def get_size check_widget force_resize rect = RECT.new OS._get_window_rect(top_handle, rect) width = rect.attr_right - rect.attr_left height = rect.attr_bottom - rect.attr_top return Point.new(width, height) end typesig { [] } # Returns the receiver's tool tip text, or null if it has # not been set. # # @return the receiver's tool tip 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> def get_tool_tip_text check_widget return @tool_tip_text end typesig { [] } # Returns <code>true</code> if the receiver is visible, and # <code>false</code> otherwise. # <p> # If one of the receiver's ancestors is not visible or some # other condition makes the receiver not visible, this method # may still indicate that it is considered visible even though # it may not actually be showing. # </p> # # @return the receiver's visibility 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> def get_visible check_widget if (!get_drawing) return ((self.attr_state & HIDDEN)).equal?(0) end bits = OS._get_window_long(@handle, OS::GWL_STYLE) return !((bits & OS::WS_VISIBLE)).equal?(0) end typesig { [] } def has_cursor rect = RECT.new if (!OS._get_client_rect(@handle, rect)) return false end OS._map_window_points(@handle, 0, rect, 2) pt = POINT.new return OS._get_cursor_pos(pt) && OS._pt_in_rect(rect, pt) end typesig { [] } def has_focus # If a non-SWT child of the control has focus, # then this control is considered to have focus # even though it does not have focus in Windows. # # long hwnd_focus = OS._get_focus while (!(hwnd_focus).equal?(0)) if ((hwnd_focus).equal?(@handle)) return true end if (!(self.attr_display.get_control(hwnd_focus)).nil?) return false end hwnd_focus = OS._get_parent(hwnd_focus) end return false end typesig { [SwtGCData] } # Invokes platform specific functionality to allocate a new GC handle. # <p> # <b>IMPORTANT:</b> This method is <em>not</em> part of the public # API for <code>Control</code>. It is marked public only so that it # can be shared within the packages provided by SWT. It is not # available on all platforms, and should never be called from # application code. # </p> # # @param data the platform specific GC data # @return the platform specific GC handle # # long def internal_new__gc(data) check_widget # long hwnd = @handle if (!(data).nil? && !(data.attr_hwnd).equal?(0)) hwnd = data.attr_hwnd end if (!(data).nil?) data.attr_hwnd = hwnd end # long h_dc = 0 if ((data).nil? || (data.attr_ps).nil?) h_dc = OS._get_dc(hwnd) else h_dc = OS._begin_paint(hwnd, data.attr_ps) end if ((h_dc).equal?(0)) SWT.error(SWT::ERROR_NO_HANDLES) end if (!(data).nil?) if (!OS::IsWinCE && OS::WIN32_VERSION >= OS._version(4, 10)) mask = SWT::LEFT_TO_RIGHT | SWT::RIGHT_TO_LEFT if (!((data.attr_style & mask)).equal?(0)) data.attr_layout = !((data.attr_style & SWT::RIGHT_TO_LEFT)).equal?(0) ? OS::LAYOUT_RTL : 0 else flags = OS._get_layout(h_dc) if (!((flags & OS::LAYOUT_RTL)).equal?(0)) data.attr_style |= SWT::RIGHT_TO_LEFT | SWT::MIRRORED else data.attr_style |= SWT::LEFT_TO_RIGHT end end else data.attr_style |= SWT::LEFT_TO_RIGHT end data.attr_device = self.attr_display foreground = get_foreground_pixel if (!(foreground).equal?(OS._get_text_color(h_dc))) data.attr_foreground = foreground end control = find_background_control if ((control).nil?) control = self end background = control.get_background_pixel if (!(background).equal?(OS._get_bk_color(h_dc))) data.attr_background = background end data.attr_font = !(@font).nil? ? @font : Font.win32_new(self.attr_display, OS._send_message(hwnd, OS::WM_GETFONT, 0, 0)) # 64 data.attr_ui_state = RJava.cast_to_int(OS._send_message(hwnd, OS::WM_QUERYUISTATE, 0, 0)) end return h_dc end typesig { [::Java::Int, SwtGCData] } # Invokes platform specific functionality to dispose a GC handle. # <p> # <b>IMPORTANT:</b> This method is <em>not</em> part of the public # API for <code>Control</code>. It is marked public only so that it # can be shared within the packages provided by SWT. It is not # available on all platforms, and should never be called from # application code. # </p> # # @param hDC the platform specific GC handle # @param data the platform specific GC data # # long def internal_dispose__gc(h_dc, data) check_widget # long hwnd = @handle if (!(data).nil? && !(data.attr_hwnd).equal?(0)) hwnd = data.attr_hwnd end if ((data).nil? || (data.attr_ps).nil?) OS._release_dc(hwnd, h_dc) else OS._end_paint(hwnd, data.attr_ps) end end typesig { [] } def is_active dialog = self.attr_display.get_modal_dialog if (!(dialog).nil?) dialog_shell = dialog.attr_parent if (!(dialog_shell).nil? && !dialog_shell.is_disposed) if (!(dialog_shell).equal?(get_shell)) return false end end end shell = nil modal_shells = self.attr_display.attr_modal_shells if (!(modal_shells).nil?) bits = SWT::APPLICATION_MODAL | SWT::SYSTEM_MODAL index = modal_shells.attr_length while ((index -= 1) >= 0) modal = modal_shells[index] if (!(modal).nil?) if (!((modal.attr_style & bits)).equal?(0)) control = self while (!(control).nil?) if ((control).equal?(modal)) break end control = control.attr_parent end if (!(control).equal?(modal)) return false end break end if (!((modal.attr_style & SWT::PRIMARY_MODAL)).equal?(0)) if ((shell).nil?) shell = get_shell end if ((modal.attr_parent).equal?(shell)) return false end end end end end if ((shell).nil?) shell = get_shell end return shell.get_enabled end typesig { [] } # Returns <code>true</code> if the receiver is enabled and all # ancestors up to and including the receiver's nearest ancestor # shell are enabled. Otherwise, <code>false</code> is returned. # A disabled control is typically not selectable from the user # interface and draws with an inactive or "grayed" look. # # @return the receiver's enabled 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 #getEnabled def is_enabled check_widget return get_enabled && @parent.is_enabled end typesig { [] } # Returns <code>true</code> if the receiver has the user-interface # focus, and <code>false</code> otherwise. # # @return the receiver's focus 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> def is_focus_control check_widget focus_control = self.attr_display.attr_focus_control if (!(focus_control).nil? && !focus_control.is_disposed) return (self).equal?(focus_control) end return has_focus end typesig { [Control] } def is_focus_ancestor(control) while (!(control).nil? && !(control).equal?(self) && !(control.is_a?(Shell))) control = control.attr_parent end return (control).equal?(self) end typesig { [] } # Returns <code>true</code> if the underlying operating # system supports this reparenting, otherwise <code>false</code> # # @return <code>true</code> if the widget can be reparented, otherwise <code>false</code> # # @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> def is_reparentable check_widget return true end typesig { [] } def is_showing # This is not complete. Need to check if the # widget is obscured by a parent or sibling. if (!is_visible) return false end control = self while (!(control).nil?) size = control.get_size if ((size.attr_x).equal?(0) || (size.attr_y).equal?(0)) return false end control = control.attr_parent end return true # Check to see if current damage is included. # # if (!OS.IsWindowVisible (handle)) return false; # int flags = OS.DCX_CACHE | OS.DCX_CLIPCHILDREN | OS.DCX_CLIPSIBLINGS; # int /*long*/ hDC = OS.GetDCEx (handle, 0, flags); # int result = OS.GetClipBox (hDC, new RECT ()); # OS.ReleaseDC (handle, hDC); # return result != OS.NULLREGION; end typesig { [] } def is_tab_group tab_list = @parent.__get_tab_list if (!(tab_list).nil?) i = 0 while i < tab_list.attr_length if ((tab_list[i]).equal?(self)) return true end i += 1 end end bits = OS._get_window_long(@handle, OS::GWL_STYLE) return !((bits & OS::WS_TABSTOP)).equal?(0) end typesig { [] } def is_tab_item tab_list = @parent.__get_tab_list if (!(tab_list).nil?) i = 0 while i < tab_list.attr_length if ((tab_list[i]).equal?(self)) return false end i += 1 end end bits = OS._get_window_long(@handle, OS::GWL_STYLE) if (!((bits & OS::WS_TABSTOP)).equal?(0)) return false end # long code = OS._send_message(@handle, OS::WM_GETDLGCODE, 0, 0) if (!((code & OS::DLGC_STATIC)).equal?(0)) return false end if (!((code & OS::DLGC_WANTALLKEYS)).equal?(0)) return false end if (!((code & OS::DLGC_WANTARROWS)).equal?(0)) return false end if (!((code & OS::DLGC_WANTTAB)).equal?(0)) return false end return true end typesig { [] } # Returns <code>true</code> if the receiver is visible and all # ancestors up to and including the receiver's nearest ancestor # shell are visible. Otherwise, <code>false</code> is returned. # # @return the receiver's visibility 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 #getVisible def is_visible check_widget if (OS._is_window_visible(@handle)) return true end return get_visible && @parent.is_visible end typesig { [::Java::Int, Event] } # long def map_event(hwnd, event) if (!(hwnd).equal?(@handle)) point = POINT.new point.attr_x = event.attr_x point.attr_y = event.attr_y OS._map_window_points(hwnd, @handle, point, 1) event.attr_x = point.attr_x event.attr_y = point.attr_y end end typesig { [::Java::Boolean, ::Java::Boolean] } def mark_layout(changed, all) # Do nothing end typesig { [] } def menu_shell return @parent.menu_shell end typesig { [::Java::Char] } def mnemonic_hit(key) return false end typesig { [::Java::Char] } def mnemonic_match(key) return false end typesig { [Control] } # Moves the receiver above the specified control in the # drawing order. If the argument is null, then the receiver # is moved to the top of the drawing order. The control at # the top of the drawing order will not be covered by other # controls even if they occupy intersecting areas. # # @param control the sibling control (or null) # # @exception IllegalArgumentException <ul> # <li>ERROR_INVALID_ARGUMENT - if the control 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> # # @see Control#moveBelow # @see Composite#getChildren def move_above(control) check_widget # long top_handle_ = top_handle hwnd_above = OS::HWND_TOP if (!(control).nil?) if (control.is_disposed) error(SWT::ERROR_INVALID_ARGUMENT) end if (!(@parent).equal?(control.attr_parent)) return end # long hwnd = control.top_handle if ((hwnd).equal?(0) || (hwnd).equal?(top_handle_)) return end hwnd_above = OS._get_window(hwnd, OS::GW_HWNDPREV) # Bug in Windows. For some reason, when GetWindow () # with GW_HWNDPREV is used to query the previous window # in the z-order with the first child, Windows returns # the first child instead of NULL. The fix is to detect # this case and move the control to the top. if ((hwnd_above).equal?(0) || (hwnd_above).equal?(hwnd)) hwnd_above = OS::HWND_TOP end end flags = OS::SWP_NOSIZE | OS::SWP_NOMOVE | OS::SWP_NOACTIVATE _set_window_pos(top_handle_, hwnd_above, 0, 0, 0, 0, flags) end typesig { [Control] } # Moves the receiver below the specified control in the # drawing order. If the argument is null, then the receiver # is moved to the bottom of the drawing order. The control at # the bottom of the drawing order will be covered by all other # controls which occupy intersecting areas. # # @param control the sibling control (or null) # # @exception IllegalArgumentException <ul> # <li>ERROR_INVALID_ARGUMENT - if the control 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> # # @see Control#moveAbove # @see Composite#getChildren def move_below(control) check_widget # long top_handle_ = top_handle hwnd_above = OS::HWND_BOTTOM if (!(control).nil?) if (control.is_disposed) error(SWT::ERROR_INVALID_ARGUMENT) end if (!(@parent).equal?(control.attr_parent)) return end hwnd_above = control.top_handle else # Bug in Windows. When SetWindowPos() is called # with HWND_BOTTOM on a dialog shell, the dialog # and the parent are moved to the bottom of the # desktop stack. The fix is to move the dialog # to the bottom of the dialog window stack by # moving behind the first dialog child. shell = get_shell if ((self).equal?(shell) && !(@parent).nil?) # Bug in Windows. For some reason, when GetWindow () # with GW_HWNDPREV is used to query the previous window # in the z-order with the first child, Windows returns # the first child instead of NULL. The fix is to detect # this case and do nothing because the control is already # at the bottom. # # long hwnd_parent = @parent.attr_handle hwnd = hwnd_parent hwnd_above = OS._get_window(hwnd, OS::GW_HWNDPREV) while (!(hwnd_above).equal?(0) && !(hwnd_above).equal?(hwnd)) if ((OS._get_window(hwnd_above, OS::GW_OWNER)).equal?(hwnd_parent)) break end hwnd_above = OS._get_window(hwnd = hwnd_above, OS::GW_HWNDPREV) end if ((hwnd_above).equal?(hwnd)) return end end end if ((hwnd_above).equal?(0) || (hwnd_above).equal?(top_handle_)) return end flags = OS::SWP_NOSIZE | OS::SWP_NOMOVE | OS::SWP_NOACTIVATE _set_window_pos(top_handle_, hwnd_above, 0, 0, 0, 0, flags) end typesig { [Control] } def new__accessible(control) return Accessible.internal_new__accessible(self) end typesig { [SwtGCData] } def new__gc(data) return SwtGC.win32_new(self, data) end typesig { [] } # Causes the receiver to be resized to its preferred size. # For a composite, this involves computing the preferred size # from its layout, if there is one. # # @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 #computeSize(int, int, boolean) def pack check_widget pack(true) end typesig { [::Java::Boolean] } # Causes the receiver to be resized to its preferred size. # For a composite, this involves computing the preferred size # from its layout, if there is one. # <p> # If the changed flag is <code>true</code>, it indicates that the receiver's # <em>contents</em> have changed, therefore any caches that a layout manager # containing the control may have been keeping need to be flushed. When the # control is resized, the changed flag will be <code>false</code>, so layout # manager caches can be retained. # </p> # # @param changed whether or not the receiver's contents have changed # # @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 #computeSize(int, int, boolean) def pack(changed) check_widget set_size(compute_size(SWT::DEFAULT, SWT::DEFAULT, changed)) end typesig { [SwtGC] } # Prints the receiver and all children. # # @param gc the gc where the drawing occurs # @return <code>true</code> if the operation was successful and <code>false</code> otherwise # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the gc is null</li> # <li>ERROR_INVALID_ARGUMENT - if the gc 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.4 def print(gc) check_widget if ((gc).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if (gc.is_disposed) error(SWT::ERROR_INVALID_ARGUMENT) end if (!OS::IsWinCE && OS::WIN32_VERSION >= OS._version(5, 1)) # long top_handle_ = top_handle # long hdc = gc.attr_handle state = 0 # long gdip_graphics = gc.get_gcdata.attr_gdip_graphics if (!(gdip_graphics).equal?(0)) # long clip_rgn = 0 SwtGdip._graphics_set_pixel_offset_mode(gdip_graphics, SwtGdip::PixelOffsetModeNone) # long rgn = SwtGdip._region_new if ((rgn).equal?(0)) SWT.error(SWT::ERROR_NO_HANDLES) end SwtGdip._graphics_get_clip(gdip_graphics, rgn) if (!SwtGdip._region_is_infinite(rgn, gdip_graphics)) clip_rgn = SwtGdip._region_get_hrgn(rgn, gdip_graphics) end SwtGdip._region_delete(rgn) SwtGdip._graphics_set_pixel_offset_mode(gdip_graphics, SwtGdip::PixelOffsetModeHalf) lp_xform = nil # long matrix = SwtGdip._matrix_new(1, 0, 0, 1, 0, 0) if ((matrix).equal?(0)) SWT.error(SWT::ERROR_NO_HANDLES) end SwtGdip._graphics_get_transform(gdip_graphics, matrix) if (!SwtGdip._matrix_is_identity(matrix)) lp_xform = Array.typed(::Java::Float).new(6) { 0.0 } SwtGdip._matrix_get_elements(matrix, lp_xform) end SwtGdip._matrix_delete(matrix) hdc = SwtGdip._graphics_get_hdc(gdip_graphics) state = OS._save_dc(hdc) if (!(lp_xform).nil?) OS._set_graphics_mode(hdc, OS::GM_ADVANCED) OS._set_world_transform(hdc, lp_xform) end if (!(clip_rgn).equal?(0)) OS._select_clip_rgn(hdc, clip_rgn) OS._delete_object(clip_rgn) end end if (OS::IsWinCE) OS._update_window(top_handle_) else flags = OS::RDW_UPDATENOW | OS::RDW_ALLCHILDREN OS._redraw_window(top_handle_, nil, 0, flags) end print_widget(top_handle_, hdc, gc) if (!(gdip_graphics).equal?(0)) OS._restore_dc(hdc, state) SwtGdip._graphics_release_hdc(gdip_graphics, hdc) end return true end return false end typesig { [::Java::Int, ::Java::Int, SwtGC] } # long # long def print_widget(hwnd, hdc, gc) # Bug in Windows. For some reason, PrintWindow() # returns success but does nothing when it is called # on a printer. The fix is to just go directly to # WM_PRINT in this case. success = false if (!((OS._get_device_caps(gc.attr_handle, OS::TECHNOLOGY)).equal?(OS::DT_RASPRINTER))) # Bug in Windows. When PrintWindow() will only draw that # portion of a control that is not obscured by the shell. # The fix is temporarily reparent the window to the desktop, # call PrintWindow() then reparent the window back. # # long hwnd_parent = OS._get_parent(hwnd) # long hwnd_shell = hwnd_parent while (!(OS._get_parent(hwnd_shell)).equal?(0)) if (!(OS._get_window(hwnd_shell, OS::GW_OWNER)).equal?(0)) break end hwnd_shell = OS._get_parent(hwnd_shell) end rect1 = RECT.new OS._get_window_rect(hwnd, rect1) fix_print_window = !OS._is_window_visible(hwnd) if (!fix_print_window) rect2 = RECT.new OS._get_window_rect(hwnd_shell, rect2) OS._intersect_rect(rect2, rect1, rect2) fix_print_window = !OS._equal_rect(rect2, rect1) end # Bug in Windows. PrintWindow() does not print portions # of the receiver that are clipped out using SetWindowRgn() # in a parent. The fix is temporarily reparent the window # to the desktop, call PrintWindow() then reparent the window # back. if (!fix_print_window) # long rgn = OS._create_rect_rgn(0, 0, 0, 0) # long parent = OS._get_parent(hwnd) while (!(parent).equal?(hwnd_shell) && !fix_print_window) if (!(OS._get_window_rgn(parent, rgn)).equal?(0)) fix_print_window = true end parent = OS._get_parent(parent) end OS._delete_object(rgn) end bits = OS._get_window_long(hwnd, OS::GWL_STYLE) # long hwnd_insert_after = OS._get_window(hwnd, OS::GW_HWNDPREV) # Bug in Windows. For some reason, when GetWindow () # with GW_HWNDPREV is used to query the previous window # in the z-order with the first child, Windows returns # the first child instead of NULL. The fix is to detect # this case and move the control to the top. if ((hwnd_insert_after).equal?(0) || (hwnd_insert_after).equal?(hwnd)) hwnd_insert_after = OS::HWND_TOP end if (fix_print_window) x = OS._get_system_metrics(OS::SM_XVIRTUALSCREEN) y = OS._get_system_metrics(OS::SM_YVIRTUALSCREEN) width = OS._get_system_metrics(OS::SM_CXVIRTUALSCREEN) height = OS._get_system_metrics(OS::SM_CYVIRTUALSCREEN) flags = OS::SWP_NOSIZE | OS::SWP_NOZORDER | OS::SWP_NOACTIVATE | OS::SWP_DRAWFRAME if (!((bits & OS::WS_VISIBLE)).equal?(0)) OS._def_window_proc(hwnd, OS::WM_SETREDRAW, 0, 0) end _set_window_pos(hwnd, 0, x + width, y + height, 0, 0, flags) OS._set_parent(hwnd, 0) if (!((bits & OS::WS_VISIBLE)).equal?(0)) OS._def_window_proc(hwnd, OS::WM_SETREDRAW, 1, 0) end end if (((bits & OS::WS_VISIBLE)).equal?(0)) OS._def_window_proc(hwnd, OS::WM_SETREDRAW, 1, 0) end success = OS._print_window(hwnd, hdc, 0) if (((bits & OS::WS_VISIBLE)).equal?(0)) OS._def_window_proc(hwnd, OS::WM_SETREDRAW, 0, 0) end if (fix_print_window) if (!((bits & OS::WS_VISIBLE)).equal?(0)) OS._def_window_proc(hwnd, OS::WM_SETREDRAW, 0, 0) end OS._set_parent(hwnd, hwnd_parent) OS._map_window_points(0, hwnd_parent, rect1, 2) flags = OS::SWP_NOSIZE | OS::SWP_NOACTIVATE | OS::SWP_DRAWFRAME _set_window_pos(hwnd, hwnd_insert_after, rect1.attr_left, rect1.attr_top, rect1.attr_right - rect1.attr_left, rect1.attr_bottom - rect1.attr_top, flags) if (!((bits & OS::WS_VISIBLE)).equal?(0)) OS._def_window_proc(hwnd, OS::WM_SETREDRAW, 1, 0) end end end # Bug in Windows. For some reason, PrintWindow() fails # when it is called on a push button. The fix is to # detect the failure and use WM_PRINT instead. Note # that WM_PRINT cannot be used all the time because it # fails for browser controls when the browser has focus. if (!success) flags = OS::PRF_CLIENT | OS::PRF_NONCLIENT | OS::PRF_ERASEBKGND | OS::PRF_CHILDREN OS._send_message(hwnd, OS::WM_PRINT, hdc, flags) end end typesig { [] } # Causes the entire bounds of the receiver to be marked # as needing to be redrawn. The next time a paint request # is processed, the control will be completely painted, # including the background. # # @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 #update() # @see PaintListener # @see SWT#Paint # @see SWT#NO_BACKGROUND # @see SWT#NO_REDRAW_RESIZE # @see SWT#NO_MERGE_PAINTS # @see SWT#DOUBLE_BUFFERED def redraw check_widget redraw(false) end typesig { [::Java::Boolean] } def redraw(all) # checkWidget (); if (!OS._is_window_visible(@handle)) return end if (OS::IsWinCE) OS._invalidate_rect(@handle, nil, true) else flags = OS::RDW_ERASE | OS::RDW_FRAME | OS::RDW_INVALIDATE if (all) flags |= OS::RDW_ALLCHILDREN end OS._redraw_window(@handle, nil, 0, flags) end end typesig { [::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int, ::Java::Boolean] } # Causes the rectangular area of the receiver specified by # the arguments to be marked as needing to be redrawn. # The next time a paint request is processed, that area of # the receiver will be painted, including the background. # If the <code>all</code> flag is <code>true</code>, any # children of the receiver which intersect with the specified # area will also paint their intersecting areas. If the # <code>all</code> flag is <code>false</code>, the children # will not be painted. # # @param x the x coordinate of the area to draw # @param y the y coordinate of the area to draw # @param width the width of the area to draw # @param height the height of the area to draw # @param all <code>true</code> if children should redraw, and <code>false</code> otherwise # # @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 #update() # @see PaintListener # @see SWT#Paint # @see SWT#NO_BACKGROUND # @see SWT#NO_REDRAW_RESIZE # @see SWT#NO_MERGE_PAINTS # @see SWT#DOUBLE_BUFFERED def redraw(x, y, width, height, all) check_widget if (width <= 0 || height <= 0) return end if (!OS._is_window_visible(@handle)) return end rect = RECT.new OS._set_rect(rect, x, y, x + width, y + height) if (OS::IsWinCE) OS._invalidate_rect(@handle, rect, true) else flags = OS::RDW_ERASE | OS::RDW_FRAME | OS::RDW_INVALIDATE if (all) flags |= OS::RDW_ALLCHILDREN end OS._redraw_window(@handle, rect, 0, flags) end end typesig { [] } def redraw_children if (!OS._is_window_visible(@handle)) return false end control = find_background_control if ((control).nil?) if (!((self.attr_state & THEME_BACKGROUND)).equal?(0)) if (OS::COMCTL32_MAJOR >= 6 && OS._is_app_themed) OS._invalidate_rect(@handle, nil, true) return true end end else if (!(control.attr_background_image).nil?) OS._invalidate_rect(@handle, nil, true) return true end end return false end typesig { [] } def register self.attr_display.add_control(@handle, self) end typesig { [] } def release_handle super @handle = 0 @parent = nil end typesig { [] } def release_parent @parent.remove_control(self) end typesig { [] } def release_widget super if (OS::IsDBLocale) OS._imm_associate_context(@handle, 0) end if (!(@tool_tip_text).nil?) set_tool_tip_text(get_shell, nil) end @tool_tip_text = RJava.cast_to_string(nil) if (!(@menu).nil? && !@menu.is_disposed) @menu.dispose end @background_image = nil @menu = nil @cursor = nil unsubclass deregister @layout_data = nil if (!(@accessible).nil?) @accessible.internal_dispose__accessible end @accessible = nil @region = nil @font = nil end typesig { [ControlListener] } # Removes the listener from the collection of listeners who will # be notified when the control is moved or resized. # # @param listener the listener which should no longer be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see ControlListener # @see #addControlListener def remove_control_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if ((self.attr_event_table).nil?) return end self.attr_event_table.unhook(SWT::Move, listener) self.attr_event_table.unhook(SWT::Resize, listener) end typesig { [DragDetectListener] } # Removes the listener from the collection of listeners who will # be notified when a drag gesture occurs. # # @param listener the listener which should no longer be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see DragDetectListener # @see #addDragDetectListener # # @since 3.3 def remove_drag_detect_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if ((self.attr_event_table).nil?) return end self.attr_event_table.unhook(SWT::DragDetect, listener) end typesig { [FocusListener] } # Removes the listener from the collection of listeners who will # be notified when the control gains or loses focus. # # @param listener the listener which should no longer be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see FocusListener # @see #addFocusListener def remove_focus_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if ((self.attr_event_table).nil?) return end self.attr_event_table.unhook(SWT::FocusIn, listener) self.attr_event_table.unhook(SWT::FocusOut, listener) end typesig { [HelpListener] } # Removes the listener from the collection of listeners who will # be notified when the help events are generated for the control. # # @param listener the listener which should no longer be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see HelpListener # @see #addHelpListener def remove_help_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if ((self.attr_event_table).nil?) return end self.attr_event_table.unhook(SWT::Help, listener) end typesig { [KeyListener] } # Removes the listener from the collection of listeners who will # be notified when keys are pressed and released on the system keyboard. # # @param listener the listener which should no longer be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see KeyListener # @see #addKeyListener def remove_key_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if ((self.attr_event_table).nil?) return end self.attr_event_table.unhook(SWT::KeyUp, listener) self.attr_event_table.unhook(SWT::KeyDown, listener) end typesig { [MenuDetectListener] } # Removes the listener from the collection of listeners who will # be notified when the platform-specific context menu trigger has # occurred. # # @param listener the listener which should no longer be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see MenuDetectListener # @see #addMenuDetectListener # # @since 3.3 def remove_menu_detect_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if ((self.attr_event_table).nil?) return end self.attr_event_table.unhook(SWT::MenuDetect, listener) end typesig { [MouseTrackListener] } # Removes the listener from the collection of listeners who will # be notified when the mouse passes or hovers over controls. # # @param listener the listener which should no longer be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see MouseTrackListener # @see #addMouseTrackListener def remove_mouse_track_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if ((self.attr_event_table).nil?) return end self.attr_event_table.unhook(SWT::MouseEnter, listener) self.attr_event_table.unhook(SWT::MouseExit, listener) self.attr_event_table.unhook(SWT::MouseHover, listener) end typesig { [MouseListener] } # Removes the listener from the collection of listeners who will # be notified when mouse buttons are pressed and released. # # @param listener the listener which should no longer be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see MouseListener # @see #addMouseListener def remove_mouse_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if ((self.attr_event_table).nil?) return end self.attr_event_table.unhook(SWT::MouseDown, listener) self.attr_event_table.unhook(SWT::MouseUp, listener) self.attr_event_table.unhook(SWT::MouseDoubleClick, listener) end typesig { [MouseMoveListener] } # Removes the listener from the collection of listeners who will # be notified when the mouse moves. # # @param listener the listener which should no longer be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see MouseMoveListener # @see #addMouseMoveListener def remove_mouse_move_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if ((self.attr_event_table).nil?) return end self.attr_event_table.unhook(SWT::MouseMove, listener) end typesig { [MouseWheelListener] } # Removes the listener from the collection of listeners who will # be notified when the mouse wheel is scrolled. # # @param listener the listener which should no longer be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see MouseWheelListener # @see #addMouseWheelListener # # @since 3.3 def remove_mouse_wheel_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if ((self.attr_event_table).nil?) return end self.attr_event_table.unhook(SWT::MouseWheel, listener) end typesig { [PaintListener] } # Removes the listener from the collection of listeners who will # be notified when the receiver needs to be painted. # # @param listener the listener which should no longer be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see PaintListener # @see #addPaintListener def remove_paint_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if ((self.attr_event_table).nil?) return end self.attr_event_table.unhook(SWT::Paint, listener) end typesig { [TraverseListener] } # Removes the listener from the collection of listeners who will # be notified when traversal events occur. # # @param listener the listener which should no longer be notified # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the listener 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> # # @see TraverseListener # @see #addTraverseListener def remove_traverse_listener(listener) check_widget if ((listener).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if ((self.attr_event_table).nil?) return end self.attr_event_table.unhook(SWT::Traverse, listener) end typesig { [::Java::Boolean] } def show_widget(visible) # long top_handle_ = top_handle OS._show_window(top_handle_, visible ? OS::SW_SHOW : OS::SW_HIDE) if (!(@handle).equal?(top_handle_)) OS._show_window(@handle, visible ? OS::SW_SHOW : OS::SW_HIDE) end end typesig { [::Java::Int] } def send_focus_event(type) shell = get_shell # Feature in Windows. During the processing of WM_KILLFOCUS, # when the focus window is queried using GetFocus(), it has # already been assigned to the new window. The fix is to # remember the control that is losing or gaining focus and # answer it during WM_KILLFOCUS. If a WM_SETFOCUS occurs # during WM_KILLFOCUS, the focus control needs to be updated # to the current control. At any other time, the focus # control matches Windows. display = self.attr_display display.attr_focus_event = type display.attr_focus_control = self send_event___org_eclipse_swt_widgets_control_1(type) # widget could be disposed at this point display.attr_focus_event = SWT::None display.attr_focus_control = nil # It is possible that the shell may be # disposed at this point. If this happens # don't send the activate and deactivate # events. if (!shell.is_disposed) case (type) when SWT::FocusIn shell.set_active_control(self) when SWT::FocusOut if (!(shell).equal?(display.get_active_shell)) shell.set_active_control(nil) end end end return true end typesig { [] } def send_move send_event___org_eclipse_swt_widgets_control_3(SWT::Move) end typesig { [] } def send_resize send_event___org_eclipse_swt_widgets_control_5(SWT::Resize) end typesig { [] } def set_background control = find_background_control if ((control).nil?) control = self end if (!(control.attr_background_image).nil?) shell = get_shell shell.release_brushes set_background_image(control.attr_background_image.attr_handle) else set_background_pixel((control.attr_background).equal?(-1) ? control.default_background : control.attr_background) end end typesig { [Color] } # Sets the receiver's background color to the color specified # by the argument, or to the default system color for the control # if the argument is null. # <p> # Note: This operation is a hint and may be overridden by the platform. # For example, on Windows the background of a Button cannot be changed. # </p> # @param color the new color (or null) # # @exception IllegalArgumentException <ul> # <li>ERROR_INVALID_ARGUMENT - if the argument 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> def set_background(color) check_widget pixel = -1 if (!(color).nil?) if (color.is_disposed) SWT.error(SWT::ERROR_INVALID_ARGUMENT) end pixel = color.attr_handle end if ((pixel).equal?(@background)) return end @background = pixel update_background_color end typesig { [Image] } # Sets the receiver's background image to the image specified # by the argument, or to the default system color for the control # if the argument is null. The background image is tiled to fill # the available space. # <p> # Note: This operation is a hint and may be overridden by the platform. # For example, on Windows the background of a Button cannot be changed. # </p> # @param image the new image (or null) # # @exception IllegalArgumentException <ul> # <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> # <li>ERROR_INVALID_ARGUMENT - if the argument is not a bitmap</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.2 def set_background_image(image) check_widget if (!(image).nil?) if (image.is_disposed) error(SWT::ERROR_INVALID_ARGUMENT) end if (!(image.attr_type).equal?(SWT::BITMAP)) error(SWT::ERROR_INVALID_ARGUMENT) end end if ((@background_image).equal?(image)) return end @background_image = image shell = get_shell shell.release_brushes update_background_image end typesig { [::Java::Int] } # long def set_background_image(h_bitmap) if (OS::IsWinCE) OS._invalidate_rect(@handle, nil, true) else flags = OS::RDW_ERASE | OS::RDW_FRAME | OS::RDW_INVALIDATE OS._redraw_window(@handle, nil, 0, flags) end end typesig { [::Java::Int] } def set_background_pixel(pixel) if (OS::IsWinCE) OS._invalidate_rect(@handle, nil, true) else flags = OS::RDW_ERASE | OS::RDW_FRAME | OS::RDW_INVALIDATE OS._redraw_window(@handle, nil, 0, flags) end end typesig { [::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int] } # Sets the receiver's size and location to the rectangular # area specified by the arguments. The <code>x</code> and # <code>y</code> arguments are relative to the receiver's # parent (or its display if its parent is null), unless # the receiver is a shell. In this case, the <code>x</code> # and <code>y</code> arguments are relative to the display. # <p> # Note: Attempting to set the width or height of the # receiver to a negative number will cause that # value to be set to zero instead. # </p> # # @param x the new x coordinate for the receiver # @param y the new y coordinate for the receiver # @param width the new width for the receiver # @param height the new height for the receiver # # @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> def set_bounds(x, y, width, height) check_widget flags = OS::SWP_NOZORDER | OS::SWP_DRAWFRAME | OS::SWP_NOACTIVATE set_bounds(x, y, Math.max(0, width), Math.max(0, height), flags) end typesig { [::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int] } def set_bounds(x, y, width, height, flags) set_bounds(x, y, width, height, flags, true) end typesig { [::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int, ::Java::Boolean] } def set_bounds(x, y, width, height, flags, defer) if (!(find_image_control).nil?) if ((@background_image).nil?) flags |= OS::SWP_NOCOPYBITS end else if ((OS._get_window(@handle, OS::GW_CHILD)).equal?(0)) if (OS::COMCTL32_MAJOR >= 6 && OS._is_app_themed) if (!(find_theme_control).nil?) flags |= OS::SWP_NOCOPYBITS end end end end # long top_handle_ = top_handle if (defer && !(@parent).nil?) force_resize if (!(@parent.attr_lpwp).nil?) index = 0 lpwp = @parent.attr_lpwp while (index < lpwp.attr_length) if ((lpwp[index]).nil?) break end index += 1 end if ((index).equal?(lpwp.attr_length)) new_lpwp = Array.typed(WINDOWPOS).new(lpwp.attr_length + 4) { nil } System.arraycopy(lpwp, 0, new_lpwp, 0, lpwp.attr_length) @parent.attr_lpwp = lpwp = new_lpwp end wp = WINDOWPOS.new wp.attr_hwnd = top_handle_ wp.attr_x = x wp.attr_y = y wp.attr_cx = width wp.attr_cy = height wp.attr_flags = flags lpwp[index] = wp return end end _set_window_pos(top_handle_, 0, x, y, width, height, flags) end typesig { [Rectangle] } # Sets the receiver's size and location to the rectangular # area specified by the argument. The <code>x</code> and # <code>y</code> fields of the rectangle are relative to # the receiver's parent (or its display if its parent is null). # <p> # Note: Attempting to set the width or height of the # receiver to a negative number will cause that # value to be set to zero instead. # </p> # # @param rect the new bounds for the receiver # # @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> def set_bounds(rect) check_widget if ((rect).nil?) error(SWT::ERROR_NULL_ARGUMENT) end set_bounds(rect.attr_x, rect.attr_y, rect.attr_width, rect.attr_height) end typesig { [::Java::Boolean] } # If the argument is <code>true</code>, causes the receiver to have # all mouse events delivered to it until the method is called with # <code>false</code> as the argument. Note that on some platforms, # a mouse button must currently be down for capture to be assigned. # # @param capture <code>true</code> to capture the mouse, and <code>false</code> to release it # # @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> def set_capture(capture) check_widget if (capture) OS._set_capture(@handle) else if ((OS._get_capture).equal?(@handle)) OS._release_capture end end end typesig { [] } def set_cursor # long l_param = OS._makelparam(OS::HTCLIENT, OS::WM_MOUSEMOVE) OS._send_message(@handle, OS::WM_SETCURSOR, @handle, l_param) end typesig { [Cursor] } # Sets the receiver's cursor to the cursor specified by the # argument, or to the default cursor for that kind of control # if the argument is null. # <p> # When the mouse pointer passes over a control its appearance # is changed to match the control's cursor. # </p> # # @param cursor the new cursor (or null) # # @exception IllegalArgumentException <ul> # <li>ERROR_INVALID_ARGUMENT - if the argument 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> def set_cursor(cursor) check_widget if (!(cursor).nil? && cursor.is_disposed) SWT.error(SWT::ERROR_INVALID_ARGUMENT) end @cursor = cursor if (OS::IsWinCE) # long h_cursor = !(cursor).nil? ? cursor.attr_handle : 0 OS._set_cursor(h_cursor) return end # long hwnd_cursor = OS._get_capture if ((hwnd_cursor).equal?(0)) pt = POINT.new if (!OS._get_cursor_pos(pt)) return end # long hwnd = hwnd_cursor = OS._window_from_point(pt) while (!(hwnd).equal?(0) && !(hwnd).equal?(@handle)) hwnd = OS._get_parent(hwnd) end if ((hwnd).equal?(0)) return end end control = self.attr_display.get_control(hwnd_cursor) if ((control).nil?) control = self end control.set_cursor end typesig { [] } def set_default_font # long h_font = self.attr_display.get_system_font.attr_handle OS._send_message(@handle, OS::WM_SETFONT, h_font, 0) end typesig { [::Java::Boolean] } # Sets the receiver's drag detect state. If the argument is # <code>true</code>, the receiver will detect drag gestures, # otherwise these gestures will be ignored. # # @param dragDetect the new drag detect 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> # # @since 3.3 def set_drag_detect(drag_detect_) check_widget if (drag_detect_) self.attr_state |= DRAG_DETECT else self.attr_state &= ~DRAG_DETECT end enable_drag(drag_detect_) end typesig { [::Java::Boolean] } # Enables the receiver if the argument is <code>true</code>, # and disables it otherwise. A disabled control is typically # not selectable from the user interface and draws with an # inactive or "grayed" look. # # @param enabled the new enabled 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> def set_enabled(enabled) check_widget # Feature in Windows. If the receiver has focus, disabling # the receiver causes no window to have focus. The fix is # to assign focus to the first ancestor window that takes # focus. If no window will take focus, set focus to the # desktop. control = nil fix_focus = false if (!enabled) if (!(self.attr_display.attr_focus_event).equal?(SWT::FocusOut)) control = self.attr_display.get_focus_control fix_focus = is_focus_ancestor(control) end end enable_widget(enabled) if (fix_focus) fix_focus(control) end end typesig { [] } def set_fixed_focus if (!((self.attr_style & SWT::NO_FOCUS)).equal?(0)) return false end return force_focus end typesig { [] } # Causes the receiver to have the <em>keyboard focus</em>, # such that all keyboard events will be delivered to it. Focus # reassignment will respect applicable platform constraints. # # @return <code>true</code> if the control got focus, and <code>false</code> if it was unable to. # # @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 #forceFocus def set_focus check_widget if (!((self.attr_style & SWT::NO_FOCUS)).equal?(0)) return false end return force_focus end typesig { [Font] } # Sets the font that the receiver will use to paint textual information # to the font specified by the argument, or to the default font for that # kind of control if the argument is null. # # @param font the new font (or null) # # @exception IllegalArgumentException <ul> # <li>ERROR_INVALID_ARGUMENT - if the argument 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> def set_font(font) check_widget # long h_font = 0 if (!(font).nil?) if (font.is_disposed) SWT.error(SWT::ERROR_INVALID_ARGUMENT) end h_font = font.attr_handle end @font = font if ((h_font).equal?(0)) h_font = default_font end OS._send_message(@handle, OS::WM_SETFONT, h_font, 1) end typesig { [Color] } # Sets the receiver's foreground color to the color specified # by the argument, or to the default system color for the control # if the argument is null. # <p> # Note: This operation is a hint and may be overridden by the platform. # </p> # @param color the new color (or null) # # @exception IllegalArgumentException <ul> # <li>ERROR_INVALID_ARGUMENT - if the argument 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> def set_foreground(color) check_widget pixel = -1 if (!(color).nil?) if (color.is_disposed) SWT.error(SWT::ERROR_INVALID_ARGUMENT) end pixel = color.attr_handle end if ((pixel).equal?(@foreground)) return end @foreground = pixel set_foreground_pixel(pixel) end typesig { [::Java::Int] } def set_foreground_pixel(pixel) OS._invalidate_rect(@handle, nil, true) end typesig { [Object] } # Sets the layout data associated with the receiver to the argument. # # @param layoutData the new layout data for the receiver. # # @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> def set_layout_data(layout_data) check_widget @layout_data = layout_data end typesig { [::Java::Int, ::Java::Int] } # Sets the receiver's location to the point specified by # the arguments which are relative to the receiver's # parent (or its display if its parent is null), unless # the receiver is a shell. In this case, the point is # relative to the display. # # @param x the new x coordinate for the receiver # @param y the new y coordinate for the receiver # # @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> def set_location(x, y) check_widget flags = OS::SWP_NOSIZE | OS::SWP_NOZORDER | OS::SWP_NOACTIVATE # Feature in WinCE. The SWP_DRAWFRAME flag for SetWindowPos() # causes a WM_SIZE message to be sent even when the SWP_NOSIZE # flag is specified. The fix is to set SWP_DRAWFRAME only when # not running on WinCE. if (!OS::IsWinCE) flags |= OS::SWP_DRAWFRAME end set_bounds(x, y, 0, 0, flags) end typesig { [Point] } # Sets the receiver's location to the point specified by # the arguments which are relative to the receiver's # parent (or its display if its parent is null), unless # the receiver is a shell. In this case, the point is # relative to the display. # # @param location the new location for the receiver # # @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> def set_location(location) check_widget if ((location).nil?) error(SWT::ERROR_NULL_ARGUMENT) end set_location(location.attr_x, location.attr_y) end typesig { [Menu] } # Sets the receiver's pop up menu to the argument. # All controls may optionally have a pop up # menu that is displayed when the user requests one for # the control. The sequence of key strokes, button presses # and/or button releases that are used to request a pop up # menu is platform specific. # <p> # Note: Disposing of a control that has a pop up menu will # dispose of the menu. To avoid this behavior, set the # menu to null before the control is disposed. # </p> # # @param menu the new pop up menu # # @exception IllegalArgumentException <ul> # <li>ERROR_MENU_NOT_POP_UP - the menu is not a pop up menu</li> # <li>ERROR_INVALID_PARENT - if the menu is not in the same widget tree</li> # <li>ERROR_INVALID_ARGUMENT - if the menu 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> def set_menu(menu) check_widget if (!(menu).nil?) if (menu.is_disposed) SWT.error(SWT::ERROR_INVALID_ARGUMENT) end if (((menu.attr_style & SWT::POP_UP)).equal?(0)) error(SWT::ERROR_MENU_NOT_POP_UP) end if (!(menu.attr_parent).equal?(menu_shell)) error(SWT::ERROR_INVALID_PARENT) end end @menu = menu end typesig { [::Java::Boolean] } def set_radio_focus(tabbing) return false end typesig { [::Java::Boolean] } def set_radio_selection(value) return false end typesig { [::Java::Boolean] } # If the argument is <code>false</code>, causes subsequent drawing # operations in the receiver to be ignored. No drawing of any kind # can occur in the receiver until the flag is set to true. # Graphics operations that occurred while the flag was # <code>false</code> are lost. When the flag is set to <code>true</code>, # the entire widget is marked as needing to be redrawn. Nested calls # to this method are stacked. # <p> # Note: This operation is a hint and may not be supported on some # platforms or for some widgets. # </p> # # @param redraw the new redraw 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 #redraw(int, int, int, int, boolean) # @see #update() def set_redraw(redraw_) check_widget # Feature in Windows. When WM_SETREDRAW is used to turn # off drawing in a widget, it clears the WS_VISIBLE bits # and then sets them when redraw is turned back on. This # means that WM_SETREDRAW will make a widget unexpectedly # visible. The fix is to track the visibility state while # drawing is turned off and restore it when drawing is # turned back on. if ((@draw_count).equal?(0)) bits = OS._get_window_long(@handle, OS::GWL_STYLE) if (((bits & OS::WS_VISIBLE)).equal?(0)) self.attr_state |= HIDDEN end end if (redraw_) if (((@draw_count -= 1)).equal?(0)) # long top_handle_ = top_handle OS._send_message(top_handle_, OS::WM_SETREDRAW, 1, 0) if (!(@handle).equal?(top_handle_)) OS._send_message(@handle, OS::WM_SETREDRAW, 1, 0) end if (!((self.attr_state & HIDDEN)).equal?(0)) self.attr_state &= ~HIDDEN OS._show_window(top_handle_, OS::SW_HIDE) if (!(@handle).equal?(top_handle_)) OS._show_window(@handle, OS::SW_HIDE) end else if (OS::IsWinCE) OS._invalidate_rect(top_handle_, nil, true) if (!(@handle).equal?(top_handle_)) OS._invalidate_rect(@handle, nil, true) end else flags = OS::RDW_ERASE | OS::RDW_FRAME | OS::RDW_INVALIDATE | OS::RDW_ALLCHILDREN OS._redraw_window(top_handle_, nil, 0, flags) end end end else if ((((@draw_count += 1) - 1)).equal?(0)) # long top_handle_ = top_handle OS._send_message(top_handle_, OS::WM_SETREDRAW, 0, 0) if (!(@handle).equal?(top_handle_)) OS._send_message(@handle, OS::WM_SETREDRAW, 0, 0) end end end end typesig { [Region] } # Sets the shape of the control to the region specified # by the argument. When the argument is null, the # default shape of the control is restored. # # @param region the region that defines the shape of the control (or null) # # @exception IllegalArgumentException <ul> # <li>ERROR_INVALID_ARGUMENT - if the region 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.4 def set_region(region) check_widget if (!(region).nil? && region.is_disposed) error(SWT::ERROR_INVALID_ARGUMENT) end # long h_region = 0 if (!(region).nil?) h_region = OS._create_rect_rgn(0, 0, 0, 0) OS._combine_rgn(h_region, region.attr_handle, h_region, OS::RGN_OR) end OS._set_window_rgn(@handle, h_region, true) @region = region end typesig { [] } def set_saved_focus return force_focus end typesig { [::Java::Int, ::Java::Int] } # Sets the receiver's size to the point specified by the arguments. # <p> # Note: Attempting to set the width or height of the # receiver to a negative number will cause that # value to be set to zero instead. # </p> # # @param width the new width for the receiver # @param height the new height for the receiver # # @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> def set_size(width, height) check_widget flags = OS::SWP_NOMOVE | OS::SWP_NOZORDER | OS::SWP_DRAWFRAME | OS::SWP_NOACTIVATE set_bounds(0, 0, Math.max(0, width), Math.max(0, height), flags) end typesig { [Point] } # Sets the receiver's size to the point specified by the argument. # <p> # Note: Attempting to set the width or height of the # receiver to a negative number will cause them to be # set to zero instead. # </p> # # @param size the new size for the receiver # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the point 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> def set_size(size) check_widget if ((size).nil?) error(SWT::ERROR_NULL_ARGUMENT) end set_size(size.attr_x, size.attr_y) end typesig { [] } def set_tab_item_focus if (!is_showing) return false end return force_focus end typesig { [String] } # Sets the receiver's tool tip text to the argument, which # may be null indicating that the default tool tip for the # control will be shown. For a control that has a default # tool tip, such as the Tree control on Windows, setting # the tool tip text to an empty string replaces the default, # causing no tool tip text to be shown. # <p> # The mnemonic indicator (character '&amp;') is not displayed in a tool tip. # To display a single '&amp;' in the tool tip, the character '&amp;' can be # escaped by doubling it in the string. # </p> # # @param string the new tool tip text (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> def set_tool_tip_text(string) check_widget @tool_tip_text = string set_tool_tip_text(get_shell, string) end typesig { [Shell, String] } def set_tool_tip_text(shell, string) shell.set_tool_tip_text(@handle, string) end typesig { [::Java::Boolean] } # Marks the receiver as visible if the argument is <code>true</code>, # and marks it invisible otherwise. # <p> # If one of the receiver's ancestors is not visible or some # other condition makes the receiver not visible, marking # it visible may not actually cause it to be displayed. # </p> # # @param visible the new visibility 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> def set_visible(visible) check_widget if (!get_drawing) if (((((self.attr_state & HIDDEN)).equal?(0))).equal?(visible)) return end else bits = OS._get_window_long(@handle, OS::GWL_STYLE) if (((!((bits & OS::WS_VISIBLE)).equal?(0))).equal?(visible)) return end end if (visible) send_event___org_eclipse_swt_widgets_control_7(SWT::Show) if (is_disposed) return end end # Feature in Windows. If the receiver has focus, hiding # the receiver causes no window to have focus. The fix is # to assign focus to the first ancestor window that takes # focus. If no window will take focus, set focus to the # desktop. control = nil fix_focus_ = false if (!visible) if (!(self.attr_display.attr_focus_event).equal?(SWT::FocusOut)) control = self.attr_display.get_focus_control fix_focus_ = is_focus_ancestor(control) end end if (!get_drawing) self.attr_state = visible ? self.attr_state & ~HIDDEN : self.attr_state | HIDDEN else show_widget(visible) if (is_disposed) return end end if (!visible) send_event___org_eclipse_swt_widgets_control_9(SWT::Hide) if (is_disposed) return end end if (fix_focus_) fix_focus(control) end end typesig { [Array.typed(::Java::Int)] } def sort(items) # Shell Sort from K&R, pg 108 length_ = items.attr_length gap = length_ / 2 while gap > 0 i = gap while i < length_ j = i - gap while j >= 0 if (items[j] <= items[j + gap]) swap = items[j] items[j] = items[j + gap] items[j + gap] = swap end j -= gap end i += 1 end gap /= 2 end end typesig { [] } def subclass # long old_proc = window_proc___org_eclipse_swt_widgets_control_11 # long new_proc = self.attr_display.attr_window_proc if ((old_proc).equal?(new_proc)) return end OS._set_window_long_ptr(@handle, OS::GWLP_WNDPROC, new_proc) end typesig { [::Java::Int, ::Java::Int] } # Returns a point which is the result of converting the # argument, which is specified in display relative coordinates, # to coordinates relative to the receiver. # <p> # @param x the x coordinate to be translated # @param y the y coordinate to be translated # @return the translated coordinates # # @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 2.1 def to_control(x, y) check_widget pt = POINT.new pt.attr_x = x pt.attr_y = y OS._screen_to_client(@handle, pt) return Point.new(pt.attr_x, pt.attr_y) end typesig { [Point] } # Returns a point which is the result of converting the # argument, which is specified in display relative coordinates, # to coordinates relative to the receiver. # <p> # @param point the point to be translated (must not be null) # @return the translated coordinates # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the point 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> def to_control(point) check_widget if ((point).nil?) error(SWT::ERROR_NULL_ARGUMENT) end return to_control(point.attr_x, point.attr_y) end typesig { [::Java::Int, ::Java::Int] } # Returns a point which is the result of converting the # argument, which is specified in coordinates relative to # the receiver, to display relative coordinates. # <p> # @param x the x coordinate to be translated # @param y the y coordinate to be translated # @return the translated coordinates # # @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 2.1 def to_display(x, y) check_widget pt = POINT.new pt.attr_x = x pt.attr_y = y OS._client_to_screen(@handle, pt) return Point.new(pt.attr_x, pt.attr_y) end typesig { [Point] } # Returns a point which is the result of converting the # argument, which is specified in coordinates relative to # the receiver, to display relative coordinates. # <p> # @param point the point to be translated (must not be null) # @return the translated coordinates # # @exception IllegalArgumentException <ul> # <li>ERROR_NULL_ARGUMENT - if the point 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> def to_display(point) check_widget if ((point).nil?) error(SWT::ERROR_NULL_ARGUMENT) end return to_display(point.attr_x, point.attr_y) end typesig { [] } # long def top_handle return @handle end typesig { [MSG] } def translate_accelerator(msg) return menu_shell.translate_accelerator(msg) end typesig { [Event, Control] } def translate_mnemonic(event, control) if ((control).equal?(self)) return false end if (!is_visible || !is_enabled) return false end event.attr_doit = mnemonic_match(event.attr_character) return traverse(event) end typesig { [MSG] } def translate_mnemonic(msg) if (msg.attr_w_param < 0x20) return false end # long hwnd = msg.attr_hwnd if (OS._get_key_state(OS::VK_MENU) >= 0) # long code = OS._send_message(hwnd, OS::WM_GETDLGCODE, 0, 0) if (!((code & OS::DLGC_WANTALLKEYS)).equal?(0)) return false end if (((code & OS::DLGC_BUTTON)).equal?(0)) return false end end shell = menu_shell if (shell.is_visible && shell.is_enabled) # 64 self.attr_display.attr_last_ascii = RJava.cast_to_int(msg.attr_w_param) self.attr_display.attr_last_null = self.attr_display.attr_last_dead = false event = Event.new event.attr_detail = SWT::TRAVERSE_MNEMONIC if (set_key_state(event, SWT::Traverse, msg.attr_w_param, msg.attr_l_param)) return translate_mnemonic(event, nil) || shell.translate_mnemonic(event, self) end end return false end typesig { [MSG] } def translate_traversal(msg) # long hwnd = msg.attr_hwnd # 64 key = RJava.cast_to_int(msg.attr_w_param) if ((key).equal?(OS::VK_MENU)) OS._send_message(hwnd, OS::WM_CHANGEUISTATE, OS::UIS_INITIALIZE, 0) return false end detail = SWT::TRAVERSE_NONE doit = true all = false last_virtual = false last_key = key last_ascii = 0 case (key) when OS::VK_ESCAPE all = true last_ascii = 27 # long code = OS._send_message(hwnd, OS::WM_GETDLGCODE, 0, 0) if (!((code & OS::DLGC_WANTALLKEYS)).equal?(0)) # Use DLGC_HASSETSEL to determine that the control # is a text widget. A text widget normally wants # all keys except VK_ESCAPE. If this bit is not # set, then assume the control wants all keys, # including VK_ESCAPE. if (((code & OS::DLGC_HASSETSEL)).equal?(0)) doit = false end end detail = SWT::TRAVERSE_ESCAPE when OS::VK_RETURN all = true last_ascii = Character.new(?\r.ord) # long code = OS._send_message(hwnd, OS::WM_GETDLGCODE, 0, 0) if (!((code & OS::DLGC_WANTALLKEYS)).equal?(0)) doit = false end detail = SWT::TRAVERSE_RETURN when OS::VK_TAB last_ascii = Character.new(?\t.ord) next_ = OS._get_key_state(OS::VK_SHIFT) >= 0 # long code = OS._send_message(hwnd, OS::WM_GETDLGCODE, 0, 0) if (!((code & (OS::DLGC_WANTTAB | OS::DLGC_WANTALLKEYS))).equal?(0)) # Use DLGC_HASSETSEL to determine that the control is a # text widget. If the control is a text widget, then # Ctrl+Tab and Shift+Tab should traverse out of the widget. # If the control is not a text widget, the correct behavior # is to give every character, including Tab, Ctrl+Tab and # Shift+Tab to the control. if (!((code & OS::DLGC_HASSETSEL)).equal?(0)) if (next_ && OS._get_key_state(OS::VK_CONTROL) >= 0) doit = false end else doit = false end end detail = next_ ? SWT::TRAVERSE_TAB_NEXT : SWT::TRAVERSE_TAB_PREVIOUS when OS::VK_UP, OS::VK_LEFT, OS::VK_DOWN, OS::VK_RIGHT # On WinCE SP there is no tab key. Focus is assigned # using the VK_UP and VK_DOWN keys, not with VK_LEFT # or VK_RIGHT. if (OS::IsSP) if ((key).equal?(OS::VK_LEFT) || (key).equal?(OS::VK_RIGHT)) return false end end last_virtual = true # long code = OS._send_message(hwnd, OS::WM_GETDLGCODE, 0, 0) # | OS.DLGC_WANTALLKEYS if (!((code & (OS::DLGC_WANTARROWS))).equal?(0)) doit = false end next_ = (key).equal?(OS::VK_DOWN) || (key).equal?(OS::VK_RIGHT) if (!(@parent).nil? && !((@parent.attr_style & SWT::MIRRORED)).equal?(0)) if ((key).equal?(OS::VK_LEFT) || (key).equal?(OS::VK_RIGHT)) next_ = !next_ end end detail = next_ ? SWT::TRAVERSE_ARROW_NEXT : SWT::TRAVERSE_ARROW_PREVIOUS when OS::VK_PRIOR, OS::VK_NEXT all = true last_virtual = true if (OS._get_key_state(OS::VK_CONTROL) >= 0) return false end # long code = OS._send_message(hwnd, OS::WM_GETDLGCODE, 0, 0) if (!((code & OS::DLGC_WANTALLKEYS)).equal?(0)) # Use DLGC_HASSETSEL to determine that the control is a # text widget. If the control is a text widget, then # Ctrl+PgUp and Ctrl+PgDn should traverse out of the widget. if (((code & OS::DLGC_HASSETSEL)).equal?(0)) doit = false end end detail = (key).equal?(OS::VK_PRIOR) ? SWT::TRAVERSE_PAGE_PREVIOUS : SWT::TRAVERSE_PAGE_NEXT else return false end event = Event.new event.attr_doit = doit event.attr_detail = detail self.attr_display.attr_last_key = last_key self.attr_display.attr_last_ascii = last_ascii self.attr_display.attr_last_virtual = last_virtual self.attr_display.attr_last_null = self.attr_display.attr_last_dead = false if (!set_key_state(event, SWT::Traverse, msg.attr_w_param, msg.attr_l_param)) return false end shell = get_shell control = self begin if (control.traverse(event)) OS._send_message(hwnd, OS::WM_CHANGEUISTATE, OS::UIS_INITIALIZE, 0) return true end if (!event.attr_doit && control.hooks(SWT::Traverse)) return false end if ((control).equal?(shell)) return false end control = control.attr_parent end while (all && !(control).nil?) return false end typesig { [Event] } def traverse(event) # It is possible (but unlikely), that application # code could have disposed the widget in the traverse # event. If this happens, return true to stop further # event processing. send_event___org_eclipse_swt_widgets_control_13(SWT::Traverse, event) if (is_disposed) return true end if (!event.attr_doit) return false end case (event.attr_detail) when SWT::TRAVERSE_NONE return true when SWT::TRAVERSE_ESCAPE return traverse_escape when SWT::TRAVERSE_RETURN return traverse_return when SWT::TRAVERSE_TAB_NEXT return traverse_group(true) when SWT::TRAVERSE_TAB_PREVIOUS return traverse_group(false) when SWT::TRAVERSE_ARROW_NEXT return traverse_item(true) when SWT::TRAVERSE_ARROW_PREVIOUS return traverse_item(false) when SWT::TRAVERSE_MNEMONIC return traverse_mnemonic(event.attr_character) when SWT::TRAVERSE_PAGE_NEXT return traverse_page(true) when SWT::TRAVERSE_PAGE_PREVIOUS return traverse_page(false) end return false end typesig { [::Java::Int] } # Based on the argument, perform one of the expected platform # traversal action. The argument should be one of the constants: # <code>SWT.TRAVERSE_ESCAPE</code>, <code>SWT.TRAVERSE_RETURN</code>, # <code>SWT.TRAVERSE_TAB_NEXT</code>, <code>SWT.TRAVERSE_TAB_PREVIOUS</code>, # <code>SWT.TRAVERSE_ARROW_NEXT</code> and <code>SWT.TRAVERSE_ARROW_PREVIOUS</code>. # # @param traversal the type of traversal # @return true if the traversal succeeded # # @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> def traverse(traversal) check_widget event = Event.new event.attr_doit = true event.attr_detail = traversal return traverse(event) end typesig { [] } def traverse_escape return false end typesig { [::Java::Boolean] } def traverse_group(next_) root = compute_tab_root group = compute_tab_group list = root.compute_tab_list length_ = list.attr_length index = 0 while (index < length_) if ((list[index]).equal?(group)) break end index += 1 end # 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. if ((index).equal?(length_)) return false end start = index offset = (next_) ? 1 : -1 while (!((index = ((index + offset + length_) % length_))).equal?(start)) widget = list[index] if (!widget.is_disposed && widget.set_tab_group_focus) return true end end if (group.is_disposed) return false end return group.set_tab_group_focus end typesig { [::Java::Boolean] } def traverse_item(next_) children = @parent.__get_children length_ = children.attr_length index = 0 while (index < length_) if ((children[index]).equal?(self)) break end index += 1 end # 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. if ((index).equal?(length_)) return false end start = index offset = (next_) ? 1 : -1 while (!((index = (index + offset + length_) % length_)).equal?(start)) child = children[index] if (!child.is_disposed && child.is_tab_item) if (child.set_tab_item_focus) return true end end end return false end typesig { [::Java::Char] } def traverse_mnemonic(key) if (mnemonic_hit(key)) OS._send_message(@handle, OS::WM_CHANGEUISTATE, OS::UIS_INITIALIZE, 0) return true end return false end typesig { [::Java::Boolean] } def traverse_page(next_) return false end typesig { [] } def traverse_return return false end typesig { [] } def unsubclass # long new_proc = window_proc___org_eclipse_swt_widgets_control_15 # long old_proc = self.attr_display.attr_window_proc if ((old_proc).equal?(new_proc)) return end OS._set_window_long_ptr(@handle, OS::GWLP_WNDPROC, new_proc) end typesig { [] } # Forces all outstanding paint requests for the widget # to be processed before this method returns. If there # are no outstanding paint request, this method does # nothing. # <p> # Note: This method does not cause a redraw. # </p> # # @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 #redraw() # @see #redraw(int, int, int, int, boolean) # @see PaintListener # @see SWT#Paint def update check_widget update(false) end typesig { [::Java::Boolean] } def update(all) # checkWidget (); if (OS::IsWinCE) OS._update_window(@handle) else flags = OS::RDW_UPDATENOW if (all) flags |= OS::RDW_ALLCHILDREN end OS._redraw_window(@handle, nil, 0, flags) end end typesig { [] } def update_background_color control = find_background_control if ((control).nil?) control = self end set_background_pixel(control.attr_background) end typesig { [] } def update_background_image control = find_background_control image = !(control).nil? ? control.attr_background_image : @background_image set_background_image(!(image).nil? ? image.attr_handle : 0) end typesig { [] } def update_background_mode old_state = self.attr_state & PARENT_BACKGROUND check_background if (!(old_state).equal?((self.attr_state & PARENT_BACKGROUND))) set_background end end typesig { [Font, Font] } def update_font(old_font, new_font) if ((get_font == old_font)) set_font(new_font) end end typesig { [] } def update_images # Do nothing end typesig { [::Java::Boolean, ::Java::Boolean] } def update_layout(resize, all) # Do nothing end typesig { [] } def widget_create_struct return nil end typesig { [] } def widget_ext_style bits = 0 if (!OS::IsPPC) if (!((self.attr_style & SWT::BORDER)).equal?(0)) bits |= OS::WS_EX_CLIENTEDGE end end # if ((style & SWT.BORDER) != 0) { # if ((style & SWT.FLAT) == 0) bits |= OS.WS_EX_CLIENTEDGE; # } # # Feature in Windows NT. When CreateWindowEx() is called with # WS_EX_LAYOUTRTL or WS_EX_NOINHERITLAYOUT, CreateWindowEx() # fails to create the HWND. The fix is to not use these bits. if (OS::WIN32_VERSION < OS._version(4, 10)) return bits end bits |= OS::WS_EX_NOINHERITLAYOUT if (!((self.attr_style & SWT::RIGHT_TO_LEFT)).equal?(0)) bits |= OS::WS_EX_LAYOUTRTL end return bits end typesig { [] } # long def widget_parent return @parent.attr_handle end typesig { [] } def widget_style # Force clipping of siblings by setting WS_CLIPSIBLINGS bits = OS::WS_CHILD | OS::WS_VISIBLE | OS::WS_CLIPSIBLINGS # if ((style & SWT.BORDER) != 0) { # if ((style & SWT.FLAT) != 0) bits |= OS.WS_BORDER; # } if (OS::IsPPC) if (!((self.attr_style & SWT::BORDER)).equal?(0)) bits |= OS::WS_BORDER end end return bits # This code is intentionally commented. When clipping # of both siblings and children is not enforced, it is # possible for application code to draw outside of the # control. # # int bits = OS.WS_CHILD | OS.WS_VISIBLE; # if ((style & SWT.CLIP_SIBLINGS) != 0) bits |= OS.WS_CLIPSIBLINGS; # if ((style & SWT.CLIP_CHILDREN) != 0) bits |= OS.WS_CLIPCHILDREN; # return bits; end typesig { [Composite] } # Changes the parent of the widget to be the one provided if # the underlying operating system supports this feature. # Returns <code>true</code> if the parent is successfully changed. # # @param parent the new parent for the control. # @return <code>true</code> if the parent is changed and <code>false</code> otherwise. # # @exception IllegalArgumentException <ul> # <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed</li> # <li>ERROR_NULL_ARGUMENT - if the parent is <code>null</code></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> def set_parent(parent) check_widget if ((parent).nil?) error(SWT::ERROR_NULL_ARGUMENT) end if (parent.is_disposed) SWT.error(SWT::ERROR_INVALID_ARGUMENT) end if ((@parent).equal?(parent)) return true end if (!is_reparentable) return false end release_parent new_shell = parent.get_shell old_shell = get_shell new_decorations = parent.menu_shell old_decorations = menu_shell if (!(old_shell).equal?(new_shell) || !(old_decorations).equal?(new_decorations)) menus = old_shell.find_menus(self) fix_children(new_shell, old_shell, new_decorations, old_decorations, menus) end # long top_handle_ = top_handle if ((OS._set_parent(top_handle_, parent.attr_handle)).equal?(0)) return false end @parent = parent flags = OS::SWP_NOSIZE | OS::SWP_NOMOVE | OS::SWP_NOACTIVATE _set_window_pos(top_handle_, OS::HWND_BOTTOM, 0, 0, 0, 0, flags) return true end typesig { [] } def window_class raise NotImplementedError end typesig { [] } # long def window_proc raise NotImplementedError end typesig { [::Java::Int, ::Java::Int, ::Java::Int, ::Java::Int] } # long # long # long # long def window_proc(hwnd, msg, w_param, l_param) result = nil case (msg) when OS::WM_ACTIVATE result = _wm_activate(w_param, l_param) when OS::WM_CAPTURECHANGED result = _wm_capturechanged(w_param, l_param) when OS::WM_CHANGEUISTATE result = _wm_changeuistate(w_param, l_param) when OS::WM_CHAR result = _wm_char(w_param, l_param) when OS::WM_CLEAR result = _wm_clear(w_param, l_param) when OS::WM_CLOSE result = _wm_close(w_param, l_param) when OS::WM_COMMAND result = _wm_command(w_param, l_param) when OS::WM_CONTEXTMENU result = _wm_contextmenu(w_param, l_param) when OS::WM_CTLCOLORBTN, OS::WM_CTLCOLORDLG, OS::WM_CTLCOLOREDIT, OS::WM_CTLCOLORLISTBOX, OS::WM_CTLCOLORMSGBOX, OS::WM_CTLCOLORSCROLLBAR, OS::WM_CTLCOLORSTATIC result = _wm_ctlcolor(w_param, l_param) when OS::WM_CUT result = _wm_cut(w_param, l_param) when OS::WM_DESTROY result = _wm_destroy(w_param, l_param) when OS::WM_DRAWITEM result = _wm_drawitem(w_param, l_param) when OS::WM_ENDSESSION result = _wm_endsession(w_param, l_param) when OS::WM_ENTERIDLE result = _wm_enteridle(w_param, l_param) when OS::WM_ERASEBKGND result = _wm_erasebkgnd(w_param, l_param) when OS::WM_GETDLGCODE result = _wm_getdlgcode(w_param, l_param) when OS::WM_GETFONT result = _wm_getfont(w_param, l_param) when OS::WM_GETOBJECT result = _wm_getobject(w_param, l_param) when OS::WM_GETMINMAXINFO result = _wm_getminmaxinfo(w_param, l_param) when OS::WM_HELP result = _wm_help(w_param, l_param) when OS::WM_HSCROLL result = _wm_hscroll(w_param, l_param) when OS::WM_IME_CHAR result = _wm_ime_char(w_param, l_param) when OS::WM_IME_COMPOSITION result = _wm_ime_composition(w_param, l_param) when OS::WM_IME_COMPOSITION_START result = _wm_ime_composition_start(w_param, l_param) when OS::WM_IME_ENDCOMPOSITION result = _wm_ime_endcomposition(w_param, l_param) when OS::WM_INITMENUPOPUP result = _wm_initmenupopup(w_param, l_param) when OS::WM_INPUTLANGCHANGE result = _wm_inputlangchange(w_param, l_param) when OS::WM_HOTKEY result = _wm_hotkey(w_param, l_param) when OS::WM_KEYDOWN result = _wm_keydown(w_param, l_param) when OS::WM_KEYUP result = _wm_keyup(w_param, l_param) when OS::WM_KILLFOCUS result = _wm_killfocus(w_param, l_param) when OS::WM_LBUTTONDBLCLK result = _wm_lbuttondblclk(w_param, l_param) when OS::WM_LBUTTONDOWN result = _wm_lbuttondown(w_param, l_param) when OS::WM_LBUTTONUP result = _wm_lbuttonup(w_param, l_param) when OS::WM_MBUTTONDBLCLK result = _wm_mbuttondblclk(w_param, l_param) when OS::WM_MBUTTONDOWN result = _wm_mbuttondown(w_param, l_param) when OS::WM_MBUTTONUP result = _wm_mbuttonup(w_param, l_param) when OS::WM_MEASUREITEM result = _wm_measureitem(w_param, l_param) when OS::WM_MENUCHAR result = _wm_menuchar(w_param, l_param) when OS::WM_MENUSELECT result = _wm_menuselect(w_param, l_param) when OS::WM_MOUSEACTIVATE result = _wm_mouseactivate(w_param, l_param) when OS::WM_MOUSEHOVER result = _wm_mousehover(w_param, l_param) when OS::WM_MOUSELEAVE result = _wm_mouseleave(w_param, l_param) when OS::WM_MOUSEMOVE result = _wm_mousemove(w_param, l_param) when OS::WM_MOUSEWHEEL result = _wm_mousewheel(w_param, l_param) when OS::WM_MOVE result = _wm_move(w_param, l_param) when OS::WM_NCACTIVATE result = _wm_ncactivate(w_param, l_param) when OS::WM_NCCALCSIZE result = _wm_nccalcsize(w_param, l_param) when OS::WM_NCHITTEST result = _wm_nchittest(w_param, l_param) when OS::WM_NCLBUTTONDOWN result = _wm_nclbuttondown(w_param, l_param) when OS::WM_NCPAINT result = _wm_ncpaint(w_param, l_param) when OS::WM_NOTIFY result = _wm_notify(w_param, l_param) when OS::WM_PAINT result = _wm_paint(w_param, l_param) when OS::WM_PALETTECHANGED result = _wm_palettechanged(w_param, l_param) when OS::WM_PARENTNOTIFY result = _wm_parentnotify(w_param, l_param) when OS::WM_PASTE result = _wm_paste(w_param, l_param) when OS::WM_PRINT result = _wm_print(w_param, l_param) when OS::WM_PRINTCLIENT result = _wm_printclient(w_param, l_param) when OS::WM_QUERYENDSESSION result = _wm_queryendsession(w_param, l_param) when OS::WM_QUERYNEWPALETTE result = _wm_querynewpalette(w_param, l_param) when OS::WM_QUERYOPEN result = _wm_queryopen(w_param, l_param) when OS::WM_RBUTTONDBLCLK result = _wm_rbuttondblclk(w_param, l_param) when OS::WM_RBUTTONDOWN result = _wm_rbuttondown(w_param, l_param) when OS::WM_RBUTTONUP result = _wm_rbuttonup(w_param, l_param) when OS::WM_SETCURSOR result = _wm_setcursor(w_param, l_param) when OS::WM_SETFOCUS result = _wm_setfocus(w_param, l_param) when OS::WM_SETFONT result = _wm_setfont(w_param, l_param) when OS::WM_SETTINGCHANGE result = _wm_settingchange(w_param, l_param) when OS::WM_SETREDRAW result = _wm_setredraw(w_param, l_param) when OS::WM_SHOWWINDOW result = _wm_showwindow(w_param, l_param) when OS::WM_SIZE result = _wm_size(w_param, l_param) when OS::WM_SYSCHAR result = _wm_syschar(w_param, l_param) when OS::WM_SYSCOLORCHANGE result = _wm_syscolorchange(w_param, l_param) when OS::WM_SYSCOMMAND result = _wm_syscommand(w_param, l_param) when OS::WM_SYSKEYDOWN result = _wm_syskeydown(w_param, l_param) when OS::WM_SYSKEYUP result = _wm_syskeyup(w_param, l_param) when OS::WM_TIMER result = _wm_timer(w_param, l_param) when OS::WM_UNDO result = _wm_undo(w_param, l_param) when OS::WM_UPDATEUISTATE result = _wm_updateuistate(w_param, l_param) when OS::WM_VSCROLL result = _wm_vscroll(w_param, l_param) when OS::WM_WINDOWPOSCHANGED result = _wm_windowposchanged(w_param, l_param) when OS::WM_WINDOWPOSCHANGING result = _wm_windowposchanging(w_param, l_param) when OS::WM_XBUTTONDBLCLK result = _wm_xbuttondblclk(w_param, l_param) when OS::WM_XBUTTONDOWN result = _wm_xbuttondown(w_param, l_param) when OS::WM_XBUTTONUP result = _wm_xbuttonup(w_param, l_param) end if (!(result).nil?) return result.attr_value end return call_window_proc(hwnd, msg, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_activate(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_capturechanged(w_param, l_param) return wm_capture_changed(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_changeuistate(w_param, l_param) if (!((self.attr_state & IGNORE_WM_CHANGEUISTATE)).equal?(0)) return LRESULT::ZERO end return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_char(w_param, l_param) return wm_char(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_clear(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_close(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_command(w_param, l_param) # When the WM_COMMAND message is sent from a # menu, the HWND parameter in LPARAM is zero. if ((l_param).equal?(0)) shell = menu_shell if (shell.is_enabled) id = OS._loword(w_param) item = self.attr_display.get_menu_item(id) if (!(item).nil? && item.is_enabled) return item.wm_command_child(w_param, l_param) end end return nil end control = self.attr_display.get_control(l_param) if ((control).nil?) return nil end return control.wm_command_child(w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_contextmenu(w_param, l_param) return wm_context_menu(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_ctlcolor(w_param, l_param) # long h_palette = self.attr_display.attr_h_palette if (!(h_palette).equal?(0)) OS._select_palette(w_param, h_palette, false) OS._realize_palette(w_param) end control = self.attr_display.get_control(l_param) if ((control).nil?) return nil end return control.wm_color_child(w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_cut(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_destroy(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_drawitem(w_param, l_param) struct = DRAWITEMSTRUCT.new OS._move_memory(struct, l_param, DRAWITEMSTRUCT.attr_sizeof) if ((struct.attr_ctl_type).equal?(OS::ODT_MENU)) item = self.attr_display.get_menu_item(struct.attr_item_id) if ((item).nil?) return nil end return item.wm_draw_child(w_param, l_param) end control = self.attr_display.get_control(struct.attr_hwnd_item) if ((control).nil?) return nil end return control.wm_draw_child(w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_endsession(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_enteridle(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_erasebkgnd(w_param, l_param) if (!((self.attr_state & DRAW_BACKGROUND)).equal?(0)) if (!(find_image_control).nil?) return LRESULT::ONE end end if (!((self.attr_state & THEME_BACKGROUND)).equal?(0)) if (OS::COMCTL32_MAJOR >= 6 && OS._is_app_themed) if (!(find_theme_control).nil?) return LRESULT::ONE end end end return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_getdlgcode(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_getfont(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_getobject(w_param, l_param) if (!(@accessible).nil?) # long result = @accessible.internal__wm_getobject(w_param, l_param) if (!(result).equal?(0)) return LRESULT.new(result) end end return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_getminmaxinfo(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_hotkey(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_help(w_param, l_param) if (OS::IsWinCE) return nil end lphi = HELPINFO.new OS._move_memory(lphi, l_param, HELPINFO.attr_sizeof) shell = menu_shell if (!shell.is_enabled) return nil end if ((lphi.attr_i_context_type).equal?(OS::HELPINFO_MENUITEM)) item = self.attr_display.get_menu_item(lphi.attr_i_ctrl_id) if (!(item).nil? && item.is_enabled) widget = nil if (item.hooks(SWT::Help)) widget = item else menu = item.attr_parent if (menu.hooks(SWT::Help)) widget = menu end end if (!(widget).nil?) # long hwnd_shell = shell.attr_handle OS._send_message(hwnd_shell, OS::WM_CANCELMODE, 0, 0) widget.post_event___org_eclipse_swt_widgets_control_17(SWT::Help) return LRESULT::ONE end end return nil end if (hooks(SWT::Help)) post_event___org_eclipse_swt_widgets_control_19(SWT::Help) return LRESULT::ONE end return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_hscroll(w_param, l_param) control = self.attr_display.get_control(l_param) if ((control).nil?) return nil end return control.wm_scroll_child(w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_ime_char(w_param, l_param) return wm_imechar(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_ime_composition(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_ime_composition_start(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_ime_endcomposition(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_initmenupopup(w_param, l_param) # Ignore WM_INITMENUPOPUP for an accelerator if (self.attr_display.attr_accel_key_hit) return nil end # If the high order word of LPARAM is non-zero, # the menu is the system menu and we can ignore # WPARAM. Otherwise, use WPARAM to find the menu. shell = get_shell old_menu = shell.attr_active_menu new_menu = nil if ((OS._hiword(l_param)).equal?(0)) new_menu = menu_shell.find_menu(w_param) if (!(new_menu).nil?) new_menu.update end end menu = new_menu while (!(menu).nil? && !(menu).equal?(old_menu)) menu = menu.get_parent_menu end if ((menu).nil?) menu = shell.attr_active_menu while (!(menu).nil?) # It is possible (but unlikely), that application # code could have disposed the widget in the hide # event. If this happens, stop searching up the # ancestor list because there is no longer a link # to follow. menu.send_event___org_eclipse_swt_widgets_control_21(SWT::Hide) if (menu.is_disposed) break end menu = menu.get_parent_menu ancestor = new_menu while (!(ancestor).nil? && !(ancestor).equal?(menu)) ancestor = ancestor.get_parent_menu end if (!(ancestor).nil?) break end end end # The shell and the new menu may be disposed because of # sending the hide event to the ancestor menus but setting # a field to null in a disposed shell is not harmful. if (!(new_menu).nil? && new_menu.is_disposed) new_menu = nil end shell.attr_active_menu = new_menu # Send the show event if (!(new_menu).nil? && !(new_menu).equal?(old_menu)) new_menu.send_event___org_eclipse_swt_widgets_control_23(SWT::Show) # widget could be disposed at this point end return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_inputlangchange(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_keydown(w_param, l_param) return wm_key_down(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_keyup(w_param, l_param) return wm_key_up(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_killfocus(w_param, l_param) return wm_kill_focus(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_lbuttondblclk(w_param, l_param) return wm_lbutton_dbl_clk(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_lbuttondown(w_param, l_param) return wm_lbutton_down(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_lbuttonup(w_param, l_param) return wm_lbutton_up(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_mbuttondblclk(w_param, l_param) return wm_mbutton_dbl_clk(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_mbuttondown(w_param, l_param) return wm_mbutton_down(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_mbuttonup(w_param, l_param) return wm_mbutton_up(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_measureitem(w_param, l_param) struct = MEASUREITEMSTRUCT.new OS._move_memory(struct, l_param, MEASUREITEMSTRUCT.attr_sizeof) if ((struct.attr_ctl_type).equal?(OS::ODT_MENU)) item = self.attr_display.get_menu_item(struct.attr_item_id) if ((item).nil?) return nil end return item.wm_measure_child(w_param, l_param) end # long hwnd = OS._get_dlg_item(@handle, struct.attr_ctl_id) control = self.attr_display.get_control(hwnd) if ((control).nil?) return nil end return control.wm_measure_child(w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_menuchar(w_param, l_param) # Feature in Windows. When the user types Alt+<key> # and <key> does not match a mnemonic in the System # menu or the menu bar, Windows beeps. This beep is # unexpected and unwanted by applications that look # for Alt+<key>. The fix is to detect the case and # stop Windows from beeping by closing the menu. type = OS._hiword(w_param) if ((type).equal?(0) || (type).equal?(OS::MF_SYSMENU)) self.attr_display.attr_mnemonic_key_hit = false return LRESULT.new(OS._makelresult(0, OS::MNC_CLOSE)) end return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_menuselect(w_param, l_param) code = OS._hiword(w_param) shell = get_shell if ((code).equal?(0xffff) && (l_param).equal?(0)) menu = shell.attr_active_menu while (!(menu).nil?) # When the user cancels any menu that is not the # menu bar, assume a mnemonic key was pressed to open # the menu from WM_SYSCHAR. When the menu was invoked # using the mouse, this assumption is wrong but not # harmful. This variable is only used in WM_SYSCHAR # and WM_SYSCHAR is only sent after the user has pressed # a mnemonic. self.attr_display.attr_mnemonic_key_hit = true # It is possible (but unlikely), that application # code could have disposed the widget in the hide # event. If this happens, stop searching up the # parent list because there is no longer a link # to follow. menu.send_event___org_eclipse_swt_widgets_control_25(SWT::Hide) if (menu.is_disposed) break end menu = menu.get_parent_menu end # The shell may be disposed because of sending the hide # event to the last active menu menu but setting a field # to null in a destroyed widget is not harmful. shell.attr_active_menu = nil return nil end if (!((code & OS::MF_SYSMENU)).equal?(0)) return nil end if (!((code & OS::MF_HILITE)).equal?(0)) item = nil menu_shell_ = menu_shell if (!((code & OS::MF_POPUP)).equal?(0)) index = OS._loword(w_param) info = MENUITEMINFO.new info.attr_cb_size = MENUITEMINFO.attr_sizeof info.attr_f_mask = OS::MIIM_SUBMENU if (OS._get_menu_item_info(l_param, index, true, info)) new_menu = menu_shell_.find_menu(info.attr_h_sub_menu) if (!(new_menu).nil?) item = new_menu.attr_cascade end end else new_menu = menu_shell_.find_menu(l_param) if (!(new_menu).nil?) id = OS._loword(w_param) item = self.attr_display.get_menu_item(id) end old_menu = shell.attr_active_menu if (!(old_menu).nil?) ancestor = old_menu while (!(ancestor).nil? && !(ancestor).equal?(new_menu)) ancestor = ancestor.get_parent_menu end if ((ancestor).equal?(new_menu)) ancestor = old_menu while (!(ancestor).equal?(new_menu)) # It is possible (but unlikely), that application # code could have disposed the widget in the hide # event or the item about to be armed. If this # happens, stop searching up the ancestor list # because there is no longer a link to follow. ancestor.send_event___org_eclipse_swt_widgets_control_27(SWT::Hide) if (ancestor.is_disposed) break end ancestor = ancestor.get_parent_menu if ((ancestor).nil?) break end end # The shell and/or the item could be disposed when # processing hide events from above. If this happens, # ensure that the shell is not accessed and that no # arm event is sent to the item. if (!shell.is_disposed) if (!(new_menu).nil? && new_menu.is_disposed) new_menu = nil end shell.attr_active_menu = new_menu end if (!(item).nil? && item.is_disposed) item = nil end end end end if (!(item).nil?) item.send_event___org_eclipse_swt_widgets_control_29(SWT::Arm) end end return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_mouseactivate(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_mousehover(w_param, l_param) return wm_mouse_hover(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_mouseleave(w_param, l_param) if (OS::COMCTL32_MAJOR >= 6) get_shell.fix_tool_tip end return wm_mouse_leave(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_mousemove(w_param, l_param) return wm_mouse_move(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_mousewheel(w_param, l_param) return wm_mouse_wheel(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_move(w_param, l_param) self.attr_state |= MOVE_OCCURRED if (!(find_image_control).nil?) if (!(self).equal?(get_shell)) redraw_children end else if (!((self.attr_state & THEME_BACKGROUND)).equal?(0)) if (OS::COMCTL32_MAJOR >= 6 && OS._is_app_themed) if (OS._is_window_visible(@handle)) if (!(find_theme_control).nil?) redraw_children end end end end end if (((self.attr_state & MOVE_DEFERRED)).equal?(0)) send_event___org_eclipse_swt_widgets_control_31(SWT::Move) end # widget could be disposed at this point return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_ncactivate(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_nccalcsize(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_nchittest(w_param, l_param) if (!OS._is_window_enabled(@handle)) return nil end if (!is_active) return LRESULT.new(OS::HTTRANSPARENT) end return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_nclbuttondown(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_ncpaint(w_param, l_param) return wm_ncpaint(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_notify(w_param, l_param) hdr = NMHDR.new OS._move_memory(hdr, l_param, NMHDR.attr_sizeof) return wm_notify(hdr, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_paint(w_param, l_param) return wm_paint(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_palettechanged(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_parentnotify(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_paste(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_print(w_param, l_param) return wm_print(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_printclient(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_queryendsession(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_querynewpalette(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_queryopen(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_rbuttondblclk(w_param, l_param) return wm_rbutton_dbl_clk(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_rbuttondown(w_param, l_param) return wm_rbutton_down(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_rbuttonup(w_param, l_param) return wm_rbutton_up(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_setcursor(w_param, l_param) hit_test = RJava.cast_to_short(OS._loword(l_param)) if ((hit_test).equal?(OS::HTCLIENT)) control = self.attr_display.get_control(w_param) if ((control).nil?) return nil end cursor = control.find_cursor if (!(cursor).nil?) OS._set_cursor(cursor.attr_handle) return LRESULT::ONE end end return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_setfocus(w_param, l_param) return wm_set_focus(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_settingchange(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_setfont(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_setredraw(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_showwindow(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_size(w_param, l_param) self.attr_state |= RESIZE_OCCURRED if (((self.attr_state & RESIZE_DEFERRED)).equal?(0)) send_event___org_eclipse_swt_widgets_control_33(SWT::Resize) end # widget could be disposed at this point return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_syschar(w_param, l_param) return wm_sys_char(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_syscolorchange(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_syscommand(w_param, l_param) # Check to see if the command is a system command or # a user menu item that was added to the System menu. # When a user item is added to the System menu, # WM_SYSCOMMAND must always return zero. # # NOTE: This is undocumented. if (((w_param & 0xf000)).equal?(0)) shell = menu_shell if (shell.is_enabled) item = self.attr_display.get_menu_item(OS._loword(w_param)) if (!(item).nil?) item.wm_command_child(w_param, l_param) end end return LRESULT::ZERO end # Process the System Command # 64 cmd = RJava.cast_to_int(w_param) & 0xfff0 case (cmd) # FALL THROUGH when OS::SC_CLOSE # long hwnd_shell = menu_shell.attr_handle bits = OS._get_window_long(hwnd_shell, OS::GWL_STYLE) if (((bits & OS::WS_SYSMENU)).equal?(0)) return LRESULT::ZERO end when OS::SC_KEYMENU # When lParam is zero, one of F10, Shift+F10, Ctrl+F10 or # Ctrl+Shift+F10 was pressed. If there is no menu bar and # the focus control is interested in keystrokes, give the # key to the focus control. Normally, F10 with no menu bar # moves focus to the System menu but this can be achieved # using Alt+Space. To allow the application to see F10, # avoid running the default window proc. # # NOTE: When F10 is pressed, WM_SYSCOMMAND is sent to the # shell, not the focus control. This is undocumented Windows # behavior. if ((l_param).equal?(0)) shell = menu_shell menu = shell.get_menu_bar if ((menu).nil?) control = self.attr_display.__get_focus_control if (!(control).nil?) if (control.hooks(SWT::KeyDown) || control.hooks(SWT::KeyUp)) self.attr_display.attr_mnemonic_key_hit = false return LRESULT::ZERO end end end else # When lParam is not zero, Alt+<key> was pressed. If the # application is interested in keystrokes and there is a # menu bar, check to see whether the key that was pressed # matches a mnemonic on the menu bar. Normally, Windows # matches the first character of a menu item as well as # matching the mnemonic character. To allow the application # to see the keystrokes in this case, avoid running the default # window proc. # # NOTE: When the user types Alt+Space, the System menu is # activated. In this case the application should not see # the keystroke. if (hooks(SWT::KeyDown) || hooks(SWT::KeyUp)) if (!(l_param).equal?(Character.new(?\s.ord))) shell = menu_shell menu = shell.get_menu_bar if (!(menu).nil?) # 64 key = Display.mbcs_to_wcs(RJava.cast_to_int(l_param)) if (!(key).equal?(0)) key = Character.to_upper_case(key) items = menu.get_items i = 0 while i < items.attr_length item = items[i] text = item.get_text mnemonic = find_mnemonic(text) if (text.length > 0 && (mnemonic).equal?(0)) ch = text.char_at(0) if ((Character.to_upper_case(ch)).equal?(key)) self.attr_display.attr_mnemonic_key_hit = false return LRESULT::ZERO end end i += 1 end end else self.attr_display.attr_mnemonic_key_hit = false end end end end # Do not allow keyboard traversal of the menu bar # or scrolling when the shell is not enabled. shell = menu_shell if (!shell.is_enabled || !shell.is_active) return LRESULT::ZERO end when OS::SC_HSCROLL, OS::SC_VSCROLL # Do not allow keyboard traversal of the menu bar # or scrolling when the shell is not enabled. shell = menu_shell if (!shell.is_enabled || !shell.is_active) return LRESULT::ZERO end when OS::SC_MINIMIZE # Save the focus widget when the shell is minimized menu_shell.save_focus end return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_syskeydown(w_param, l_param) return wm_sys_key_down(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_syskeyup(w_param, l_param) return wm_sys_key_up(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_timer(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_undo(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_updateuistate(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_vscroll(w_param, l_param) control = self.attr_display.get_control(l_param) if ((control).nil?) return nil end return control.wm_scroll_child(w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_windowposchanged(w_param, l_param) begin self.attr_display.attr_resize_count += 1 # long code = call_window_proc(@handle, OS::WM_WINDOWPOSCHANGED, w_param, l_param) return (code).equal?(0) ? LRESULT::ZERO : LRESULT.new(code) ensure (self.attr_display.attr_resize_count -= 1) end end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_windowposchanging(w_param, l_param) # Bug in Windows. When WM_SETREDRAW is used to turn off drawing # for a control and the control is moved or resized, Windows does # not redraw the area where the control once was in the parent. # The fix is to detect this case and redraw the area. if (!get_drawing) shell = get_shell if (!(shell).equal?(self)) lpwp = WINDOWPOS.new OS._move_memory(lpwp, l_param, WINDOWPOS.attr_sizeof) if (((lpwp.attr_flags & OS::SWP_NOMOVE)).equal?(0) || ((lpwp.attr_flags & OS::SWP_NOSIZE)).equal?(0)) rect = RECT.new OS._get_window_rect(top_handle, rect) width = rect.attr_right - rect.attr_left height = rect.attr_bottom - rect.attr_top if (!(width).equal?(0) && !(height).equal?(0)) # long hwnd_parent = (@parent).nil? ? 0 : @parent.attr_handle OS._map_window_points(0, hwnd_parent, rect, 2) if (OS::IsWinCE) OS._invalidate_rect(hwnd_parent, rect, true) else # long rgn1 = OS._create_rect_rgn(rect.attr_left, rect.attr_top, rect.attr_right, rect.attr_bottom) # long rgn2 = OS._create_rect_rgn(lpwp.attr_x, lpwp.attr_y, lpwp.attr_x + lpwp.attr_cx, lpwp.attr_y + lpwp.attr_cy) OS._combine_rgn(rgn1, rgn1, rgn2, OS::RGN_DIFF) flags = OS::RDW_ERASE | OS::RDW_FRAME | OS::RDW_INVALIDATE | OS::RDW_ALLCHILDREN OS._redraw_window(hwnd_parent, nil, rgn1, flags) OS._delete_object(rgn1) OS._delete_object(rgn2) end end end end end return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_xbuttondblclk(w_param, l_param) return wm_xbutton_dbl_clk(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_xbuttondown(w_param, l_param) return wm_xbutton_down(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def _wm_xbuttonup(w_param, l_param) return wm_xbutton_up(@handle, w_param, l_param) end typesig { [::Java::Int, ::Java::Int] } # long # long def wm_color_child(w_param, l_param) control = find_background_control if ((control).nil?) if (!((self.attr_state & THEME_BACKGROUND)).equal?(0)) if (OS::COMCTL32_MAJOR >= 6 && OS._is_app_themed) control = find_theme_control if (!(control).nil?) rect = RECT.new OS._get_client_rect(@handle, rect) OS._set_text_color(w_param, get_foreground_pixel) OS._set_bk_color(w_param, get_background_pixel) fill_theme_background(w_param, control, rect) OS._set_bk_mode(w_param, OS::TRANSPARENT) return LRESULT.new(OS._get_stock_object(OS::NULL_BRUSH)) end end end if ((@foreground).equal?(-1)) return nil end end if ((control).nil?) control = self end fore_pixel = get_foreground_pixel back_pixel = control.get_background_pixel OS._set_text_color(w_param, fore_pixel) OS._set_bk_color(w_param, back_pixel) if (!(control.attr_background_image).nil?) rect = RECT.new OS._get_client_rect(@handle, rect) # long hwnd = control.attr_handle # long h_bitmap = control.attr_background_image.attr_handle OS._map_window_points(@handle, hwnd, rect, 2) lp_point = POINT.new OS._get_window_org_ex(w_param, lp_point) OS._set_brush_org_ex(w_param, -rect.attr_left - lp_point.attr_x, -rect.attr_top - lp_point.attr_y, lp_point) # long h_brush = find_brush(h_bitmap, OS::BS_PATTERN) if (!((self.attr_state & DRAW_BACKGROUND)).equal?(0)) # long h_old_brush = OS._select_object(w_param, h_brush) OS._map_window_points(hwnd, @handle, rect, 2) OS._pat_blt(w_param, rect.attr_left, rect.attr_top, rect.attr_right - rect.attr_left, rect.attr_bottom - rect.attr_top, OS::PATCOPY) OS._select_object(w_param, h_old_brush) end OS._set_bk_mode(w_param, OS::TRANSPARENT) return LRESULT.new(h_brush) end # long h_brush = find_brush(back_pixel, OS::BS_SOLID) if (!((self.attr_state & DRAW_BACKGROUND)).equal?(0)) rect = RECT.new OS._get_client_rect(@handle, rect) # long h_old_brush = OS._select_object(w_param, h_brush) OS._pat_blt(w_param, rect.attr_left, rect.attr_top, rect.attr_right - rect.attr_left, rect.attr_bottom - rect.attr_top, OS::PATCOPY) OS._select_object(w_param, h_old_brush) end return LRESULT.new(h_brush) end typesig { [::Java::Int, ::Java::Int] } # long # long def wm_command_child(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def wm_draw_child(w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def wm_measure_child(w_param, l_param) return nil end typesig { [NMHDR, ::Java::Int, ::Java::Int] } # long # long def wm_notify(hdr, w_param, l_param) control = self.attr_display.get_control(hdr.attr_hwnd_from) if ((control).nil?) return nil end return control.wm_notify_child(hdr, w_param, l_param) end typesig { [NMHDR, ::Java::Int, ::Java::Int] } # long # long def wm_notify_child(hdr, w_param, l_param) return nil end typesig { [::Java::Int, ::Java::Int] } # long # long def wm_scroll_child(w_param, l_param) return nil end private alias_method :initialize__control, :initialize end end